diff --git a/calliope-backend/scripts/audit_reference_conversion.py b/calliope-backend/scripts/audit_reference_conversion.py index c0e5169e..a87365db 100644 --- a/calliope-backend/scripts/audit_reference_conversion.py +++ b/calliope-backend/scripts/audit_reference_conversion.py @@ -39,7 +39,12 @@ from calliope.comfyui.serialization_reference import ( serialize_promoted_node, serialize_reference_widgets, ) -from calliope.comfyui.structure_reference import PROMOTED_PROFILES, STRUCTURE_PROFILES +from calliope.comfyui.structure_reference import ( + PROMOTED_PROFILES, + SETGET_COMMIT, + SETGET_PROFILES, + STRUCTURE_PROFILES, +) from calliope.comfyui.ui2api import convert, convert_reference @@ -293,6 +298,7 @@ REFERENCE_PROFILES = ( SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, *VHS_PROFILES, + *SETGET_PROFILES, ) @@ -495,6 +501,7 @@ def profile_attempt(source, profile): **PROMOTED_PROFILES, CASE04_PROFILE: "1.53.6", **VHS_PROFILES, + **SETGET_PROFILES, }.get(profile, "1.37.11") assumptions = { "frontend": expected, @@ -572,6 +579,38 @@ def profile_attempt(source, profile): "serialization-evidence/sources.json", ] base = {"profile": profile, "assumptions": assumptions} + if profile in SETGET_PROFILES: + assumptions["setget_reference"] = { + "commit": SETGET_COMMIT, + "missing_version": "explicit_fixed_reference_assumption_only", + "provider_policy": "exact_aux_id_required; missing/literal/conflict_rejected", + "scope": "root_only; nested_and_cross_boundary_rejected", + "name": "widgets_values/0 exact string; no normalization or previousName lookup", + "duplicates": "reject_all; frontend_first_match_is_not_emulated", + "unmodified_pinned_extensions": True, + "target_installation_and_UE_match": "unknown", + } + assumptions["reference_sources"] = [ + "setget-reference/sources.json", + "vhs-reference/sources.json", + "serialization-evidence/sources.json", + ] + base["verified_reference_facts"] = "setget-reference/contract.json" + base["source_declarations"] = [ + { + "pointer": f"/nodes/{i}", + **{k: (n.get("properties") or {}).get(k) for k in ("cnr_id", "aux_id", "ver")}, + } + for i, n in enumerate(source.get("nodes", [])) + ] + if not any(n.get("type") in ("SetNode", "GetNode") for n in source.get("nodes", [])): + return { + **base, + "status": "not_applicable", + "issues": [ + {"code": "setget_not_present", "message": "新profile仅覆盖包含Set/Get的根图"} + ], + } if profile in (*CROP_SPLIT_PROFILES, *VHS_PROFILES): base["source_declarations"] = [ { @@ -594,21 +633,29 @@ def profile_attempt(source, profile): else "requires_explicit_1.48.6" ) assumptions["missing_frontend_policy"] = ( - "explicit_media_reference_assumption" + "explicit_1.37.11_reference_assumption" + if profile in SETGET_PROFILES + else "explicit_media_reference_assumption" if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, *VHS_PROFILES) else "explicit_legacy_reference_assumption" if profile in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE) else "requires_explicit_declaration" ) - if profile in VHS_PROFILES and expected == "1.48.6": + if profile in (*VHS_PROFILES, *SETGET_PROFILES) and expected == "1.48.6": assumptions["missing_frontend_policy"] = "requires_explicit_1.48.6" assumptions["missing_node_declarations"] = [ n["pointer"] - for n in node_inventory(source, include_aux=profile in CROP_SPLIT_PROFILES) + for n in node_inventory( + source, include_aux=profile in (*CROP_SPLIT_PROFILES, *SETGET_PROFILES) + ) if n["type"] not in ("Note", "MarkdownNote", "Reroute", "PrimitiveNode") and (n["provider"] is None or n["version"] is None) ] - if (profile in VHS_PROFILES and expected == "1.48.6" and declared_frontend is None) or ( + if ( + profile in (*VHS_PROFILES, *SETGET_PROFILES) + and expected == "1.48.6" + and declared_frontend is None + ) or ( declared_frontend != expected and not ( declared_frontend is None @@ -621,6 +668,7 @@ def profile_attempt(source, profile): SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, *VHS_PROFILES, + *SETGET_PROFILES, ) ) ): @@ -644,6 +692,11 @@ def profile_attempt(source, profile): else "serializer_or_structure_rejected", "issues": result.issues, "unresolved_boundaries": result.unresolved_boundaries, + **( + {"virtual_resolutions": result.virtual_resolutions} + if profile in SETGET_PROFILES + else {} + ), } # Legacy core serializers explicitly assume absent declarations. Record # that assumption instead of implying that a type-name match proved it. @@ -655,6 +708,11 @@ def profile_attempt(source, profile): or "restored_saved_state_before_queue_hooks", "candidate_sha256": canonical_sha(result.prompt), "candidate_prompt": result.prompt, + **( + {"virtual_resolutions": result.virtual_resolutions} + if profile in SETGET_PROFILES + else {} + ), **( {"field_evidence": asr_field_evidence(source, result.prompt)} if profile == ASR_PROFILE @@ -740,7 +798,7 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles= for issue in attempt["issues"]: gap_inventory = ( node_inventory(source, include_aux=True) - if attempt["profile"] in CROP_SPLIT_PROFILES + if attempt["profile"] in (*CROP_SPLIT_PROFILES, *SETGET_PROFILES) else inventory ) matches = [n for n in gap_inventory if n["node_id"] == issue.get("node_id")] @@ -766,7 +824,11 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles= } if baseline_profiles is None: excluded_profiles = ( - VHS_PROFILES if any(p in VHS_PROFILES for p in profiles) else CROP_SPLIT_PROFILES + SETGET_PROFILES + if any(p in SETGET_PROFILES for p in profiles) + else VHS_PROFILES + if any(p in VHS_PROFILES for p in profiles) + else CROP_SPLIT_PROFILES ) baseline_profiles = tuple(p for p in profiles if p not in excluded_profiles) old_complete = { diff --git a/calliope-backend/src/calliope/comfyui/serialization_reference.py b/calliope-backend/src/calliope/comfyui/serialization_reference.py index b79a15d4..4bb01e2f 100644 --- a/calliope-backend/src/calliope/comfyui/serialization_reference.py +++ b/calliope-backend/src/calliope/comfyui/serialization_reference.py @@ -14,6 +14,8 @@ import json import math from typing import Any +from .structure_reference import SETGET_PROFILES + MP3_PROFILE = "comfy-frontend-1.37.11-mp3-core-0.11.0-reference" REEL_PROFILE = "comfy-frontend-1.37.11-layerstyle-mixed-core-0.4.0-reference" MEDIA_PROFILES = (MP3_PROFILE, REEL_PROFILE) @@ -100,6 +102,8 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]: "output": outputs, } + if profile in SETGET_PROFILES: + return {**reference_definitions(PROFILE), **vhs_definitions()} if profile in VHS_PROFILES: return vhs_definitions() if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES): @@ -176,6 +180,16 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]: def serialize_reference_widgets(node: dict[str, Any], profile: str = PROFILE) -> dict[str, Any]: """Apply only the pinned identity serializers; reject any extra/missing value.""" + if profile in SETGET_PROFILES: + if node.get("type") in vhs_definitions(): + return serialize_vhs_node(node) + if any( + k in container + for container in (node, node.get("properties") or {}) + for k in ("widgets", "widgets_values_named", "serializeValue", "comfyDynamic") + ): + raise ValueError("Set/Get组合核心参考不接受自定义serializer或额外控件") + return serialize_reference_widgets(node, PROFILE) if profile in VHS_PROFILES: return serialize_vhs_node(node) if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES): diff --git a/calliope-backend/src/calliope/comfyui/structure_reference.py b/calliope-backend/src/calliope/comfyui/structure_reference.py index 596205ed..e571b7b7 100644 --- a/calliope-backend/src/calliope/comfyui/structure_reference.py +++ b/calliope-backend/src/calliope/comfyui/structure_reference.py @@ -7,11 +7,17 @@ node serializers, third-party behavior, target versions or execution eligibility from __future__ import annotations +import re from copy import deepcopy from dataclasses import dataclass, field from typing import Any from uuid import UUID +SETGET_COMMIT = "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18" +SETGET_PROFILES = { + f"comfy-frontend-{v}-kj-setget-ab72eda7-vhs-reference": v for v in ("1.37.11", "1.48.6") +} + STRUCTURE_PROFILES = { f"comfy-frontend-{version}-structure-reference": version for version in ("1.48.7", "1.53.6", "1.48.6") @@ -44,6 +50,292 @@ def _uuid(value): return False +def project_reference_setget(source: dict) -> Structure: + """Pinned KJ same-root saved-state projection, never a partial prompt. + + Diagnostics may retain literal, unique-name topology when provenance is + ambiguous. Such paths carry rejections and NEVER yield a projected graph. + Every virtual node, edge and dependency cycle is checked, including unused + branches. No subgraph scope, rename callback or type inference is emulated. + """ + from .serialization_reference import validate_reroute + + issues, resolved = [], [] + + def reject(message, nid=""): + issues.append({"code": "setget_reference_invalid", "node_id": str(nid), "message": message}) + + try: + if (source.get("definitions") or {}).get("subgraphs") or any( + _uuid(n.get("type")) for n in source["nodes"] + ): + reject("Set/Get仅覆盖根图;嵌套或跨边界名字作用域未证明") + if any((source.get("extra") or {}).get(k) for k in ("ue_links", "links_added_by_ue")): + raise ValueError("Set/Get不解释UE附加连线") + nodes, indices, links, link_indices = {}, {}, {}, {} + for i, n in enumerate(source["nodes"]): + nid = _id(n["id"]) + if nid in nodes: + raise ValueError("重复根图节点ID") + nodes[nid], indices[nid] = n, i + if n.get("type") not in ("Note", "MarkdownNote") and ( + type(n.get("mode", 0)) is not int or n.get("mode", 0) != 0 + ): + reject("根图运行节点仅支持正常mode=0", nid) + if any( + k in container + for container in (n, n.get("properties") or {}) + for k in ( + "getInputLink", + "resolveInput", + "resolveOutput", + "onExecute", + "isVirtualNode", + "applyToGraph", + ) + ): + reject("根图含自定义执行/追线覆盖", nid) + for i, edge in enumerate(source.get("links", [])): + if not isinstance(edge, list) or len(edge) != 6: + raise ValueError("Set/Get仅接受六字段根图连线") + lid, a, oslot, b, islot, typ = edge + if type(lid) is not int or lid < 0 or lid in links: + raise ValueError("连线ID非法或重复") + a, b = _id(a), _id(b) + for nid, slot, direction in ((a, oslot, "outputs"), (b, islot, "inputs")): + if ( + nid not in nodes + or type(slot) is not int + or not (0 <= slot < len(nodes[nid].get(direction, []))) + ): + raise ValueError("连线端点/原槽缺失") + s = nodes[nid][direction][slot] + if direction == "outputs": + ids = s.get("links") or [] + if any(type(x) is not int for x in ids) or ids.count(lid) != 1: + raise ValueError("输出与连线不互指") + elif type(s.get("link")) is not int or s["link"] != lid: + raise ValueError("输入与连线不互指") + if s.get("type") != typ: + raise ValueError("每跳连线类型与两端槽必须精确一致") + if not isinstance(typ, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", typ): + raise ValueError("通配/联合/动态连线类型未证明") + links[lid], link_indices[lid] = edge, i + for nid, n in nodes.items(): + for direction in ("inputs", "outputs"): + for slot, s in enumerate(n.get(direction, [])): + ids = ( + [s["link"]] + if direction == "inputs" and s.get("link") is not None + else (s.get("links") or []) + if direction == "outputs" + else [] + ) + for lid in ids: + e = links.get(lid) + offset = 1 if direction == "outputs" else 3 + if e is None or [str(e[offset]), e[offset + 1]] != [nid, slot]: + raise ValueError("槽引用缺失连线或错误端点") + + setters, names, node_rejections = {}, {}, {} + virtual = { + nid for nid, n in nodes.items() if n.get("type") in ("SetNode", "GetNode", "Reroute") + } + for nid in sorted(virtual): + n = nodes[nid] + start = len(issues) + if type(n.get("mode", 0)) is not int or n.get("mode", 0) != 0: + reject("Set/Get/Reroute只支持正常mode=0", nid) + if n["type"] == "Reroute": + try: + validate_reroute(n) + except ValueError as exc: + reject(str(exc), nid) + types = [s.get("type") for s in n.get("inputs", []) + n.get("outputs", [])] + if ( + len(types) != 2 + or types[0] != types[1] + or not isinstance(types[0], str) + or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", types[0]) + ): + reject("Reroute仅支持已保存且精确相同的具体类型", nid) + else: + props = n.get("properties") or {} + if ( + props.get("aux_id") != "kijai/ComfyUI-KJNodes" + or props.get("cnr_id") is not None + ): + reject("Set/Get提供方歧义或冲突;类名字面aux_id不是来源证明", nid) + if props.get("ver") not in (None, SETGET_COMMIT): + reject("Set/Get显式版本不等于固定完整提交", nid) + values = n.get("widgets_values") + if ( + not isinstance(values, list) + or len(values) != 1 + or type(values[0]) is not str + or not values[0] + ): + reject("Set/Get要求唯一非空字符串名字控件", nid) + else: + names[nid] = values[0] + if n["type"] == "SetNode": + setters.setdefault(values[0], []).append(nid) + if ( + len(n.get("inputs", [])) != (1 if n["type"] == "SetNode" else 0) + or len(n.get("outputs", [])) != 1 + ): + reject("Set/Get有额外或缺失槽", nid) + sockets = n.get("inputs", []) + n.get("outputs", []) + types = [s.get("type") for s in sockets] + if ( + not types + or any( + not isinstance(t, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", t) + for t in types + ) + or len(set(types)) != 1 + ): + reject("Set/Get槽类型未知或不一致;不按名字推断类型", nid) + if any(s.get("name") != s.get("type") or s.get("widget") for s in sockets): + reject("Set/Get槽构造/绑定与固定形式不符", nid) + for container in (n, n.get("properties") or {}): + if any( + k in container + for k in ( + "widgets", + "widgets_values_named", + "serializeValue", + "comfyDynamic", + "getInputLink", + "onExecute", + "isVirtualNode", + ) + ): + reject("虚拟节点存在自定义覆盖或额外控件", nid) + props = n.get("properties") or {} + ue = props.get("ue_properties") or {} + if any( + props.get(k) or ue.get(k) + for k in ("widget_ue_connectable", "input_ue_unconnectable") + ): + reject("虚拟节点UE自定义绑定未证明", nid) + node_rejections[nid] = issues[start:] + for name, ids in setters.items(): + if len(ids) != 1: + reject(f"重名Set:{name!r};保守拒绝而非取首个") + + def trace(nid, slot, seen=()): + token = (nid, slot) + if token in seen: + raise ValueError("Set/Get逻辑环或链式自引用") + n = nodes[nid] + hop = { + "node_id": nid, + "output_slot": slot, + "node_pointer": f"/nodes/{indices[nid]}", + "output_pointer": f"/nodes/{indices[nid]}/outputs/{slot}", + } + if nid not in virtual: + return [nid, slot], [hop], [] + if slot != 0: + raise ValueError("虚拟节点出口必须为零槽") + rejection = list(node_rejections[nid]) + if nid in names: + hop.update(name=names[nid], name_pointer=hop["node_pointer"] + "/widgets_values/0") + if n["type"] == "GetNode": + ids = setters.get(names.get(nid), []) + if len(ids) != 1: + raise ValueError("Get缺少唯一精确名字Set;不使用previousName/标题或规范化") + sid = ids[0] + if n["outputs"][0]["type"] != nodes[sid]["outputs"][0]["type"]: + raise ValueError("Get与Set类型冲突") + endpoint, hops, errors = trace(sid, 0, (*seen, token)) + hop.update( + name=names[nid], + name_pointer=hop["node_pointer"] + "/widgets_values/0", + setter_id=sid, + ) + return endpoint, [hop, *hops], rejection + errors + lid = n.get("inputs", [{}])[0].get("link") + if lid not in links: + raise ValueError("Set/Reroute无上游实际输入") + e = links[lid] + hop.update(input_slot=0, link_pointer=f"/links/{link_indices[lid]}", original_link=e) + endpoint, hops, errors = trace(str(e[1]), e[2], (*seen, token)) + return endpoint, [hop, *hops], rejection + errors + + # Include logical binding edges when checking ALL cycles, including + # ordinary-node cycles containing a Set/Get hop and unused bad branches. + adjacency = {nid: [] for nid in nodes} + for e in links.values(): + adjacency[str(e[1])].append(str(e[3])) + for nid, n in nodes.items(): + if n.get("type") == "GetNode" and len(setters.get(names.get(nid), [])) == 1: + adjacency[setters[names[nid]][0]].append(nid) + indegree = dict.fromkeys(nodes, 0) + for targets in adjacency.values(): + for t in targets: + indegree[t] += 1 + pending = [k for k, v in indegree.items() if not v] + visited = 0 + while pending: + visited += 1 + for target in adjacency[pending.pop()]: + indegree[target] -= 1 + if not indegree[target]: + pending.append(target) + if visited != len(nodes): + reject("根图含物理或Set/Get逻辑依赖环") + # Resolve every virtual node, even if its output has no consumers. + for nid in sorted(virtual): + try: + trace(nid, 0) + except (ValueError, KeyError, IndexError, TypeError) as exc: + reject(str(exc), nid) + graph = deepcopy(source) + kept = {str(n["id"]): n for n in graph["nodes"] if str(n["id"]) not in virtual} + edges = [] + for e in links.values(): + if str(e[3]) in virtual: + continue + try: + endpoint, hops, errors = trace(str(e[1]), e[2]) + if str(e[1]) in virtual: + resolved.append( + { + "target_node_id": str(e[3]), + "target_input_slot": e[4], + "target_input_name": nodes[str(e[3])]["inputs"][e[4]]["name"], + "original_link_pointer": f"/links/{link_indices[e[0]]}", + "original_link": e, + "endpoint": endpoint, + "hops": hops, + "binding_rejections": errors, + "authority": "literal_topology_only" + if errors or issues + else "pinned_reference_assumption_only", + } + ) + edges.append([e[0], int(endpoint[0]), endpoint[1], *e[3:]]) + except (ValueError, KeyError, IndexError, TypeError) as exc: + reject(str(exc), e[3]) + if issues: + for resolution in resolved: + resolution["whole_graph_rejected"] = True + resolution["authority"] = "literal_topology_only" + return Structure(None, issues, resolved=resolved) + for n in kept.values(): + for s in n.get("outputs", []): + s["links"] = [] + for e in edges: + kept[str(e[1])]["outputs"][e[2]]["links"].append(e[0]) + graph["nodes"], graph["links"] = list(kept.values()), edges + return Structure(graph, resolved=resolved) + except (ValueError, TypeError, KeyError, IndexError, AttributeError, RecursionError) as exc: + reject(str(exc)) + return Structure(None, issues, resolved=resolved) + + def expand_reference_subgraphs( source: dict, profile: str, *, widgets: bool = False, case04: bool = False ) -> Structure: diff --git a/calliope-backend/src/calliope/comfyui/ui2api.py b/calliope-backend/src/calliope/comfyui/ui2api.py index 5dd00ffe..bd20657d 100644 --- a/calliope-backend/src/calliope/comfyui/ui2api.py +++ b/calliope-backend/src/calliope/comfyui/ui2api.py @@ -34,7 +34,13 @@ from .serialization_reference import ( serialize_reference_widgets, validate_reroute, ) -from .structure_reference import PROMOTED_PROFILES, STRUCTURE_PROFILES, expand_reference_subgraphs +from .structure_reference import ( + PROMOTED_PROFILES, + SETGET_PROFILES, + STRUCTURE_PROFILES, + expand_reference_subgraphs, + project_reference_setget, +) @dataclass @@ -46,6 +52,7 @@ class Conversion: unresolved_boundaries: list[dict[str, Any]] = field(default_factory=list) resolved_boundaries: list[dict[str, Any]] = field(default_factory=list) serialization_stage: str | None = None + virtual_resolutions: list[dict[str, Any]] = field(default_factory=list) def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversion: @@ -67,6 +74,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, *VHS_PROFILES, + *SETGET_PROFILES, AUX_PROFILE, PRIMITIVE_PROFILE, PREVIEW_PROFILE, @@ -83,6 +91,27 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: True, ) try: + if profile in SETGET_PROFILES: + expected = SETGET_PROFILES[profile] + declared = (source.get("extra") or {}).get("frontendVersion") + if declared != expected and not (declared is None and expected == "1.37.11"): + raise ValueError("Set/Get前端声明不匹配;缺失仅显式选择1.37.11") + structure = project_reference_setget(source) + if structure.graph is None: + return Conversion( + None, structure.issues, True, virtual_resolutions=structure.resolved + ) + result = _convert( + structure.graph, + reference_definitions(profile), + reference=True, + reference_profile=profile, + ) + result.reference_only = True + result.virtual_resolutions = structure.resolved + result.diagnostic_graph = structure.graph + result.serialization_stage = "restored_saved_state_before_queue_hooks" + return result if ( profile in VHS_PROFILES and VHS_PROFILES[profile] == "1.48.6" @@ -226,6 +255,7 @@ def _convert( **PROMOTED_PROFILES, CASE04_PROFILE: "1.53.6", **VHS_PROFILES, + **SETGET_PROFILES, }.get(reference_profile, "1.37.11") if frontend_version is not None and frontend_version != expected_version: fail("reference_frontend_mismatch", "源图声明的前端版本与固定参考不一致") diff --git a/calliope-backend/tests/test_audio_separation_reference.py b/calliope-backend/tests/test_audio_separation_reference.py index c8d5a9e1..22a0809c 100644 --- a/calliope-backend/tests/test_audio_separation_reference.py +++ b/calliope-backend/tests/test_audio_separation_reference.py @@ -362,7 +362,7 @@ def test_library_actual_delta_keeps_every_old_attempt_and_all_six_golden_compari profiles = tuple( p for p in audit.REFERENCE_PROFILES - if p not in (*audit.CROP_SPLIT_PROFILES, *audit.VHS_PROFILES) + if p not in (*audit.CROP_SPLIT_PROFILES, *audit.VHS_PROFILES, *audit.SETGET_PROFILES) ) baseline = tuple(p for p in profiles if p != SEPARATION_PROFILE) old = audit.audit_library(REPO, baseline) diff --git a/calliope-backend/tests/test_crop_split_reference.py b/calliope-backend/tests/test_crop_split_reference.py index dd9f46a9..f41a9e74 100644 --- a/calliope-backend/tests/test_crop_split_reference.py +++ b/calliope-backend/tests/test_crop_split_reference.py @@ -351,7 +351,9 @@ def test_two_disjoint_instances_preserve_nodes_links_and_values(profile): def test_all_old_fourteen_profiles_attempts_gaps_and_six_differences_unchanged(): - historical_profiles = tuple(p for p in audit.REFERENCE_PROFILES if p not in VHS_PROFILES) + historical_profiles = tuple( + p for p in audit.REFERENCE_PROFILES if p not in (*VHS_PROFILES, *audit.SETGET_PROFILES) + ) profiles = tuple(p for p in historical_profiles if p not in CROP_SPLIT_PROFILES) historical = json.loads((REPO / "docs/hel-892/separation-evidence/library.json").read_bytes()) baseline = audit.audit_library(REPO, profiles) diff --git a/calliope-backend/tests/test_setget_reference.py b/calliope-backend/tests/test_setget_reference.py new file mode 100644 index 00000000..84430151 --- /dev/null +++ b/calliope-backend/tests/test_setget_reference.py @@ -0,0 +1,423 @@ +"""Saved-state transformation tests; never execute upstream JS or a ComfyUI job.""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path + +import pytest +from scripts import audit_reference_conversion as audit +from scripts.verify_frontend_sources import verify + +from calliope.comfyui.structure_reference import ( + SETGET_PROFILES, + project_reference_setget, +) +from calliope.comfyui.ui2api import convert, convert_reference + +REPO = Path(__file__).resolve().parents[2] +PROFILE = next(iter(SETGET_PROFILES)) + + +def virtual(nid, kind, name, typ="IMAGE"): + return { + "id": nid, + "type": kind, + "mode": 0, + "properties": {"aux_id": "kijai/ComfyUI-KJNodes", "previousName": "old"}, + "widgets_values": [name], + "inputs": [{"name": typ, "type": typ, "link": None}] if kind == "SetNode" else [], + "outputs": [{"name": typ, "type": typ, "links": []}], + } + + +def connect(graph, lid, origin, oslot, target, tslot, typ="IMAGE"): + nodes = {n["id"]: n for n in graph["nodes"]} + nodes[origin]["outputs"][oslot].setdefault("links", []).append(lid) + nodes[target]["inputs"][tslot]["link"] = lid + graph["links"].append([lid, origin, oslot, target, tslot, typ]) + + +def synthetic(): + graph = { + "nodes": [ + { + "id": 1, + "type": "LoadImage", + "widgets_values": ["one.png", "image"], + "inputs": [], + "outputs": [{"type": "IMAGE", "links": []}, {"type": "MASK", "links": []}], + }, + virtual(2, "SetNode", "图片"), + virtual(3, "GetNode", "图片"), + { + "id": 4, + "type": "PreviewImage", + "widgets_values": [], + "inputs": [{"name": "images", "type": "IMAGE", "link": None}], + "outputs": [], + }, + ], + "links": [], + } + connect(graph, 1, 1, 0, 2, 0) + connect(graph, 2, 3, 0, 4, 0) + return graph + + +def test_fixed_originals_and_registration_call_chain(): + root = REPO / "docs/hel-892/setget-reference" + assert len(verify(root)["sources_verified"]) == 19 + js = (root / "web__js__setgetnodes.js").read_text() + for text in ( + 'LiteGraph.registerNodeType("SetNode", SetNode)', + 'LiteGraph.registerNodeType("GetNode", GetNode)', + "this.isVirtualNode = true", + "getInputLink(slot)", + "n.type === 'SetNode' && n.widgets[0].value === name", + "if (app.configuringGraph) return;", + "if (this._justAdded && !app.configuringGraph)", + "this.properties.previousName = this.widgets[0].value;", + ): + assert text in js + for v in SETGET_PROFILES.values(): + dto = (root / f"{v}__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts").read_text() + assert "const virtualLink = this.node.getInputLink(slot)" in dto + assert "return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)" in dto + node = (root / f"{v}__src__lib__litegraph__src__LGraphNode.ts").read_text() + assert "widget.value = info.widgets_values[i++]" in node + assert "getInputLink(slot: number)" in node + + +@pytest.mark.parametrize("profile", SETGET_PROFILES) +def test_complete_projection_and_production_stays_closed(profile): + g = synthetic() + g["extra"] = {"frontendVersion": SETGET_PROFILES[profile]} + original = copy.deepcopy(g) + result = convert_reference(g, profile) + assert result.prompt is not None, result.issues + assert set(result.prompt) == {"1", "4"} + assert result.prompt["4"]["inputs"]["images"] == ["1", 0] + assert result.prompt["1"]["inputs"]["image"] == "one.png" + assert [h["node_id"] for h in result.virtual_resolutions[0]["hops"]] == ["3", "2", "1"] + assert result.reference_only + assert convert(g).prompt is None + assert g == original + + +@pytest.mark.parametrize("name", ["图片", " A ", "a", "A", "e\u0301", "\u00e9", " "]) +def test_exact_names_rename_previous_name_and_upstream_changes(name): + g = synthetic() + g["nodes"][1]["widgets_values"] = [name] + g["nodes"][2]["widgets_values"] = [name] + g["nodes"][1]["properties"]["previousName"] = "图片" + result = convert_reference(g, PROFILE) + assert result.prompt is not None + assert result.virtual_resolutions[0]["hops"][0]["name"] == name + g["nodes"][0]["widgets_values"][0] = "changed.png" + assert convert_reference(g, PROFILE).prompt["1"]["inputs"]["image"] == "changed.png" + g["nodes"][2]["widgets_values"] = ["not_current"] + g["nodes"][1]["properties"]["previousName"] = "not_current" + g["nodes"][1]["title"] = "not_current" + assert convert_reference(g, PROFILE).prompt is None + + +@pytest.mark.parametrize("other", ["a", "A ", " A", "e\u0301"]) +def test_no_name_normalization(other): + g = synthetic() + g["nodes"][1]["widgets_values"] = ["A" if other != "e\u0301" else "\u00e9"] + g["nodes"][2]["widgets_values"] = [other] + assert convert_reference(g, PROFILE).prompt is None + + +def test_multiple_names_and_changing_binding_selects_correct_source(): + g = synthetic() + other = copy.deepcopy(g["nodes"][0]) + other["id"] = 11 + other["widgets_values"][0] = "two.png" + other["outputs"][0]["links"] = [] + g["nodes"] += [other, virtual(12, "SetNode", "second")] + connect(g, 11, 11, 0, 12, 0) + assert convert_reference(g, PROFILE).prompt["4"]["inputs"]["images"] == ["1", 0] + g["nodes"][2]["widgets_values"] = ["second"] + result = convert_reference(g, PROFILE) + assert result.prompt["4"]["inputs"]["images"] == ["11", 0] + assert result.prompt["11"]["inputs"]["image"] == "two.png" + + +def test_fanout_direct_set_and_multilevel_reroute_preserve_original_slot(): + g = synthetic() + g["nodes"][0]["outputs"][1]["type"] = "IMAGE" # topology fixture only + g["nodes"][0]["outputs"][0]["links"] = [] + g["nodes"][0]["outputs"][1]["links"] = [1] + g["links"][0][2] = 1 + g["nodes"] += [ + virtual(5, "GetNode", "图片"), + virtual(6, "SetNode", "next"), + virtual(7, "GetNode", "next"), + { + "id": 8, + "type": "Reroute", + "widgets_values": [], + "inputs": [{"name": "", "type": "IMAGE", "link": None}], + "outputs": [{"name": "", "type": "IMAGE", "links": []}], + }, + copy.deepcopy(g["nodes"][3]), + ] + g["nodes"][-1]["id"] = 9 + g["nodes"][-1]["inputs"][0]["link"] = None + connect(g, 3, 5, 0, 6, 0) + connect(g, 4, 7, 0, 8, 0) + connect(g, 5, 8, 0, 9, 0) + # Direct Set output feeds an additional sink; Get fanout is independent. + sink = copy.deepcopy(g["nodes"][3]) + sink["id"] = 10 + sink["inputs"][0]["link"] = None + g["nodes"].append(sink) + connect(g, 6, 2, 0, 10, 0) + projected = project_reference_setget(g) + assert projected.graph is not None, projected.issues + assert {tuple(e["endpoint"]) for e in projected.resolved} == {("1", 1)} + assert len(projected.resolved) == 3 + last = next(r for r in projected.resolved if r["target_node_id"] == "9") + assert [h["node_id"] for h in last["hops"]] == ["8", "7", "6", "5", "2", "1"] + assert [e[2] for e in projected.graph["links"]] == [1, 1, 1] + + +@pytest.mark.parametrize( + "mutation", + [ + "duplicate", + "missing_set", + "empty", + "bad_name", + "extra_widget", + "mapping_widget", + "bad_aux", + "missing_aux", + "literal_aux", + "bad_version", + "bad_cnr", + "extra_input", + "extra_output", + "bad_type", + "wildcard", + "union", + "mode", + "bool_mode", + "custom_serializer", + "custom_properties", + "custom_binding", + "bad_slot_name", + "bad_reciprocal", + "dangling", + "bool_slot", + "bool_link", + "wrong_edge_type", + "physical_cycle", + "logical_cycle", + "unused_bad_get", + "unused_bad_set", + "nested", + "uuid", + "ue_edges", + ], +) +def test_fail_closed_mutations_including_unused_branches(mutation): + g = synthetic() + s = g["nodes"][1] + get = g["nodes"][2] + if mutation == "duplicate": + extra = copy.deepcopy(s) + extra["id"] = 22 + extra["inputs"][0]["link"] = None + g["nodes"].append(extra) + elif mutation == "missing_set": + s["widgets_values"] = ["other"] + elif mutation == "empty": + get["widgets_values"] = [""] + elif mutation == "bad_name": + get["widgets_values"] = [True] + elif mutation == "extra_widget": + get["widgets_values"].append("extra") + elif mutation == "mapping_widget": + get["widgets_values"] = {"Constant": "图片"} + elif mutation == "bad_aux": + s["properties"]["aux_id"] = "rgthree/rgthree-comfy" + elif mutation == "missing_aux": + s["properties"].pop("aux_id") + elif mutation == "literal_aux": + s["properties"]["aux_id"] = "SetNode" + elif mutation == "bad_version": + s["properties"]["ver"] = "1.0.0" + elif mutation == "bad_cnr": + s["properties"]["cnr_id"] = "other" + elif mutation == "extra_input": + get["inputs"] = [{"name": "IMAGE", "type": "IMAGE", "link": None}] + elif mutation == "extra_output": + get["outputs"].append(copy.deepcopy(get["outputs"][0])) + elif mutation == "bad_type": + get["outputs"][0]["type"] = "FLOAT" + g["links"][1][5] = "FLOAT" + g["nodes"][3]["inputs"][0]["type"] = "FLOAT" + elif mutation in ("wildcard", "union"): + s["outputs"][0]["type"] = "*" if mutation == "wildcard" else "IMAGE,MASK" + elif mutation == "mode": + get["mode"] = 4 + elif mutation == "bool_mode": + get["mode"] = False + elif mutation == "custom_serializer": + get["serializeValue"] = "override" + elif mutation == "custom_properties": + s["properties"]["getInputLink"] = "override" + elif mutation == "custom_binding": + s["properties"]["ue_properties"] = {"widget_ue_connectable": {"Constant": True}} + elif mutation == "bad_slot_name": + s["inputs"][0]["name"] = "other" + elif mutation == "bad_reciprocal": + g["nodes"][0]["outputs"][0]["links"] = [] + elif mutation == "dangling": + g["links"][0][1] = 999 + elif mutation == "bool_slot": + g["links"][0][2] = False + elif mutation == "bool_link": + g["links"][0][0] = True + elif mutation == "wrong_edge_type": + g["links"][0][5] = "MASK" + elif mutation in ("physical_cycle", "logical_cycle"): + g["nodes"][0]["outputs"][0]["links"] = [] + g["links"].pop(0) + connect(g, 1, 2 if mutation == "physical_cycle" else 3, 0, 2, 0) + elif mutation == "unused_bad_get": + g["nodes"].append(virtual(99, "GetNode", "missing")) + elif mutation == "unused_bad_set": + g["nodes"].append(virtual(99, "SetNode", "unused")) + elif mutation == "nested": + g["definitions"] = {"subgraphs": [{"id": "any"}]} + elif mutation == "uuid": + g["nodes"].append({"id": 88, "type": "e61f4fd0-e251-4d58-bfa4-cf163fa86577"}) + elif mutation == "ue_edges": + g["extra"] = {"ue_links": [1]} + result = convert_reference(g, PROFILE) + assert result.prompt is None, mutation + assert result.issues, mutation + + +def test_unknown_ordinary_node_blocks_whole_graph_with_reference_trace_retained(): + g = synthetic() + g["nodes"][0]["type"] = "UnknownImageProducer" + result = convert_reference(g, PROFILE) + assert result.prompt is None + assert result.virtual_resolutions[0]["endpoint"] == ["1", 0] + assert any(i["code"] == "reference_node_unsupported" for i in result.issues) + + +def test_ambiguous_provider_trace_is_explicitly_untrusted(): + g = synthetic() + g["nodes"][1]["properties"]["aux_id"] = "SetNode" + result = convert_reference(g, PROFILE) + assert result.prompt is None and result.diagnostic_graph is None + trace = result.virtual_resolutions[0] + assert trace["endpoint"] == ["1", 0] + assert trace["authority"] == "literal_topology_only" and trace["binding_rejections"] + + +def test_wrong_frontend_missing_policy_and_profile_inventory(): + p1486 = list(SETGET_PROFILES)[1] + assert convert_reference(synthetic(), p1486).prompt is None + for v in ["1.48.7", "1.53.6", "1.37.11-other"]: + g = synthetic() + g["extra"] = {"frontendVersion": v} + assert convert_reference(g, PROFILE).prompt is None + assert len(audit.REFERENCE_PROFILES) == 20 + + +@pytest.mark.parametrize("profile", SETGET_PROFILES) +def test_vhs_composition_preserves_nonzero_audio_slot_and_exact_commits(profile): + prefix = "example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/" + source = json.loads((REPO / (prefix + "多视频合成分屏展示.json")).read_bytes()) + load = next(n for n in source["nodes"] if n["id"] == 17) + source = json.loads( + ( + REPO + / ( + "example_ComfyUI_workflows/4-视频生成/Minimax-h3/" + "Minimax_H3_T8双时钟采样_参考生视频-8步高质量极速版.json" + ) + ).read_bytes() + ) + combine = next(n for n in source["nodes"] if n["id"] == 12) + for n in (load, combine): + n.pop("widgets_values_named", None) + for s in n["inputs"]: + s["link"] = None + for s in n["outputs"]: + s["links"] = [] + graph = { + "nodes": [ + load, + combine, + virtual(900, "SetNode", "audio", "AUDIO"), + virtual(901, "GetNode", "audio", "AUDIO"), + ], + "links": [], + "extra": {"frontendVersion": SETGET_PROFILES[profile]}, + } + connect(graph, 1, 17, 0, 12, 0) + connect(graph, 2, 17, 2, 900, 0, "AUDIO") + connect(graph, 3, 901, 0, 12, 1, "AUDIO") + result = convert_reference(graph, profile) + assert result.prompt is not None, result.issues + assert result.prompt["12"]["inputs"]["audio"] == ["17", 2] + assert result.prompt["12"]["inputs"]["images"] == ["17", 0] + assert result.prompt["17"]["inputs"]["force_rate"] == 16 + load["widgets_values"]["force_rate"] = 20 + assert convert_reference(graph, profile).prompt["17"]["inputs"]["force_rate"] == 20 + load["properties"]["ver"] = "1.7.9" + assert convert_reference(graph, profile).prompt is None + + +@pytest.mark.parametrize( + "mutation", ["reroute_type", "ordinary_override", "ordinary_mode", "ordinary_cycle"] +) +def test_combined_structure_rejects_other_graph_overrides_and_cycles(mutation): + g = synthetic() + if mutation == "reroute_type": + g["nodes"][1] = { + "id": 2, + "type": "Reroute", + "widgets_values": [], + "inputs": [{"name": "", "type": "IMAGE", "link": 1}], + "outputs": [{"type": "MASK", "links": []}], + } + elif mutation == "ordinary_override": + g["nodes"][0]["resolveOutput"] = "custom" + elif mutation == "ordinary_mode": + g["nodes"][0]["mode"] = False + else: + # Ordinary producer feeds Set, Get feeds the same producer input. + g["nodes"][0]["inputs"] = [{"name": "images", "type": "IMAGE", "link": None}] + connect(g, 3, 3, 0, 1, 0) + assert convert_reference(g, PROFILE).prompt is None + + +def test_historical_18_profiles_attempts_gaps_and_six_comparisons_unchanged(): + old = json.loads((REPO / "docs/hel-892/vhs-evidence/library.json").read_bytes()) + baseline = tuple(p for p in audit.REFERENCE_PROFILES if p not in SETGET_PROFILES) + now = audit.audit_library(REPO, baseline_profiles=baseline) + actual_old = audit.audit_library(REPO, baseline) + assert len(baseline) == 18 + assert actual_old["gap_groups"] == old["gap_groups"] + for historical, previous, current in zip(old["cases"], actual_old["cases"], now["cases"]): + assert historical["source_path"] == previous["source_path"] == current["source_path"] + assert historical["attempts"] == previous["attempts"] == current["attempts"][:18] + assert ( + historical.get("comparisons") + == previous.get("comparisons") + == current.get("comparisons") + ) + assert now["coverage_delta"]["baseline_profiles"] == list(baseline) + assert audit.audit(REPO, "case04-batch-reference") == json.loads( + (REPO / "docs/hel-892/media-evidence/protected-six-cases.json").read_bytes() + ) diff --git a/calliope-backend/tests/test_vhs_reference.py b/calliope-backend/tests/test_vhs_reference.py index 20d016da..42a0963a 100644 --- a/calliope-backend/tests/test_vhs_reference.py +++ b/calliope-backend/tests/test_vhs_reference.py @@ -285,9 +285,13 @@ def test_real_five_load_instances_are_distinct_and_modes_not_dropped(): def test_old_sixteen_attempts_gaps_candidates_and_six_comparisons_protected(): old = json.loads((REPO / "docs/hel-892/crop-split-evidence/library.json").read_bytes()) - profiles = tuple(p for p in audit.REFERENCE_PROFILES if p not in VHS_PROFILES) + # Freeze this batch's 18-profile history; Set/Get has separate current protection. + historical_profiles = tuple( + p for p in audit.REFERENCE_PROFILES if p not in audit.SETGET_PROFILES + ) + profiles = tuple(p for p in historical_profiles if p not in VHS_PROFILES) baseline = audit.audit_library(REPO, profiles) - now = audit.audit_library(REPO, baseline_profiles=profiles) + now = audit.audit_library(REPO, historical_profiles, baseline_profiles=profiles) assert len(profiles) == 16 and len(now["profiles"]) == 18 assert old["gap_groups"] == baseline["gap_groups"] for previous, before, after in zip(old["cases"], baseline["cases"], now["cases"]): diff --git a/docs/hel-892/setget-reference/1.37.11__LICENSE b/docs/hel-892/setget-reference/1.37.11__LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/docs/hel-892/setget-reference/1.37.11__LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/docs/hel-892/setget-reference/1.37.11__build__plugins__comfyAPIPlugin.ts b/docs/hel-892/setget-reference/1.37.11__build__plugins__comfyAPIPlugin.ts new file mode 100644 index 00000000..6441dd78 --- /dev/null +++ b/docs/hel-892/setget-reference/1.37.11__build__plugins__comfyAPIPlugin.ts @@ -0,0 +1,118 @@ +import path from 'path' +import type { Plugin } from 'vite' + +interface ShimResult { + code: string + exports: string[] +} + +const SKIP_WARNING_FILES = new Set(['scripts/app', 'scripts/api']) + +/** Files that will be removed in v1.34 */ +const DEPRECATED_FILES = ['scripts/ui', 'extensions/core/groupNode'] as const + +function getWarningMessage( + fileKey: string, + shimFileName: string +): string | null { + if (SKIP_WARNING_FILES.has(fileKey)) { + return null + } + + const isDeprecated = DEPRECATED_FILES.some((deprecatedPath) => + fileKey.startsWith(deprecatedPath) + ) + + if (isDeprecated) { + return `[ComfyUI Deprecated] Importing from "${shimFileName}" is deprecated and will be removed in v1.34.` + } + + return `[ComfyUI Notice] "${shimFileName}" is an internal module, not part of the public API. Future updates may break this import.` +} + +function isLegacyFile(id: string): boolean { + return ( + id.endsWith('.ts') && + (id.includes('src/extensions/core') || id.includes('src/scripts')) + ) +} + +function transformExports(code: string, id: string): ShimResult { + const moduleName = getModuleName(id) + const exports: string[] = [] + let newCode = code + + // Regex to match different types of exports + const regex = + /export\s+(const|let|var|function|class|async function)\s+([a-zA-Z$_][a-zA-Z\d$_]*)(\s|\()/g + let match + + while ((match = regex.exec(code)) !== null) { + const name = match[2] + // All exports should be bind to the window object as new API endpoint. + if (exports.length == 0) { + newCode += `\nwindow.comfyAPI = window.comfyAPI || {};` + newCode += `\nwindow.comfyAPI.${moduleName} = window.comfyAPI.${moduleName} || {};` + } + newCode += `\nwindow.comfyAPI.${moduleName}.${name} = ${name};` + exports.push( + `export const ${name} = window.comfyAPI.${moduleName}.${name};\n` + ) + } + + return { + code: newCode, + exports + } +} + +function getModuleName(id: string): string { + // Simple example to derive a module name from the file path + const parts = id.split('/') + const fileName = parts[parts.length - 1] + return fileName.replace(/\.\w+$/, '') // Remove file extension +} + +export function comfyAPIPlugin(isDev: boolean): Plugin { + return { + name: 'comfy-api-plugin', + transform(code: string, id: string) { + if (isDev) return null + + if (isLegacyFile(id)) { + const result = transformExports(code, id) + + if (result.exports.length > 0) { + const projectRoot = process.cwd() + const relativePath = path + .relative(path.join(projectRoot, 'src'), id) + .replace(/\\/g, '/') + const shimFileName = relativePath.replace(/\.ts$/, '.js') + + let shimContent = `// Shim for ${relativePath}\n` + + const fileKey = relativePath.replace(/\.ts$/, '') + const warningMessage = getWarningMessage(fileKey, shimFileName) + + if (warningMessage) { + // It will only display once because it is at the root of the file. + shimContent += `console.warn('${warningMessage}');\n` + } + + shimContent += result.exports.join('') + + this.emitFile({ + type: 'asset', + fileName: shimFileName, + source: shimContent + }) + } + + return { + code: result.code, + map: null // If you're not modifying the source map, return null + } + } + } + } +} diff --git a/docs/hel-892/setget-reference/1.37.11__src__config__comfyApi.ts b/docs/hel-892/setget-reference/1.37.11__src__config__comfyApi.ts new file mode 100644 index 00000000..8efd651b --- /dev/null +++ b/docs/hel-892/setget-reference/1.37.11__src__config__comfyApi.ts @@ -0,0 +1,43 @@ +import { isCloud } from '@/platform/distribution/types' +import { + configValueOrDefault, + remoteConfig +} from '@/platform/remoteConfig/remoteConfig' + +const PROD_API_BASE_URL = 'https://api.comfy.org' +const STAGING_API_BASE_URL = 'https://stagingapi.comfy.org' + +const PROD_PLATFORM_BASE_URL = 'https://platform.comfy.org' +const STAGING_PLATFORM_BASE_URL = 'https://stagingplatform.comfy.org' + +const BUILD_TIME_API_BASE_URL = __USE_PROD_CONFIG__ + ? PROD_API_BASE_URL + : STAGING_API_BASE_URL + +const BUILD_TIME_PLATFORM_BASE_URL = __USE_PROD_CONFIG__ + ? PROD_PLATFORM_BASE_URL + : STAGING_PLATFORM_BASE_URL + +export function getComfyApiBaseUrl(): string { + if (!isCloud) { + return BUILD_TIME_API_BASE_URL + } + + return configValueOrDefault( + remoteConfig.value, + 'comfy_api_base_url', + BUILD_TIME_API_BASE_URL + ) +} + +export function getComfyPlatformBaseUrl(): string { + if (!isCloud) { + return BUILD_TIME_PLATFORM_BASE_URL + } + + return configValueOrDefault( + remoteConfig.value, + 'comfy_platform_base_url', + BUILD_TIME_PLATFORM_BASE_URL + ) +} diff --git a/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__LGraphNode.ts b/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__LGraphNode.ts new file mode 100644 index 00000000..0ca41a73 --- /dev/null +++ b/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__LGraphNode.ts @@ -0,0 +1,4198 @@ +import { LGraphNodeProperties } from '@/lib/litegraph/src/LGraphNodeProperties' +import { + calculateInputSlotPos, + calculateInputSlotPosFromSlot, + calculateOutputSlotPos, + getSlotPosition +} from '@/renderer/core/canvas/litegraph/slotCalculations' +import type { SlotPositionContext } from '@/renderer/core/canvas/litegraph/slotCalculations' +import { useLayoutMutations } from '@/renderer/core/layout/operations/layoutMutations' +import { LayoutSource } from '@/renderer/core/layout/types' +import { adjustColor } from '@/utils/colorUtil' +import type { ColorAdjustOptions } from '@/utils/colorUtil' +import { commonType, toClass } from '@/lib/litegraph/src/utils/type' + +import { SUBGRAPH_OUTPUT_ID } from '@/lib/litegraph/src/constants' +import type { DragAndScale } from './DragAndScale' +import type { LGraph } from './LGraph' +import { BadgePosition, LGraphBadge } from './LGraphBadge' +import { LGraphButton } from './LGraphButton' +import type { LGraphButtonOptions } from './LGraphButton' +import { LGraphCanvas } from './LGraphCanvas' +import { LLink } from './LLink' +import type { Reroute, RerouteId } from './Reroute' +import { getNodeInputOnPos, getNodeOutputOnPos } from './canvas/measureSlots' +import type { IDrawBoundingOptions } from './draw' +import { NullGraphError } from './infrastructure/NullGraphError' +import type { ReadOnlyRectangle } from './infrastructure/Rectangle' +import { Rectangle } from './infrastructure/Rectangle' +import type { + ColorOption, + CompassCorners, + DefaultConnectionColors, + Dictionary, + IColorable, + IContextMenuValue, + IFoundSlot, + INodeFlags, + INodeInputSlot, + INodeOutputSlot, + INodeSlot, + INodeSlotContextItem, + IPinnable, + ISlotType, + Point, + Positionable, + ReadOnlyRect, + Rect, + Size +} from './interfaces' +import { LiteGraph, Subgraph } from './litegraph' +import type { LGraphNodeConstructor, SubgraphNode } from './litegraph' +import { + createBounds, + isInRect, + isInRectangle, + isPointInRect, + snapPoint +} from './measure' +import { NodeInputSlot } from './node/NodeInputSlot' +import { NodeOutputSlot } from './node/NodeOutputSlot' +import { + inputAsSerialisable, + isINodeInputSlot, + isWidgetInputSlot, + outputAsSerialisable +} from './node/slotUtils' +import type { SubgraphInputNode } from './subgraph/SubgraphInputNode' +import type { SubgraphOutputNode } from './subgraph/SubgraphOutputNode' +import type { NodeLike } from './types/NodeLike' +import type { CanvasPointerEvent } from './types/events' +import { + LGraphEventMode, + NodeSlotType, + RenderShape, + TitleMode +} from './types/globalEnums' +import type { ISerialisedNode, SubgraphIO } from './types/serialisation' +import type { + IBaseWidget, + IWidgetOptions, + TWidgetType, + TWidgetValue +} from './types/widgets' +import { findFreeSlotOfType } from './utils/collections' +import { warnDeprecated } from './utils/feedback' +import { distributeSpace } from './utils/spaceDistribution' +import { truncateText } from './utils/textUtils' +import { BaseWidget } from './widgets/BaseWidget' +import { toConcreteWidget } from './widgets/widgetMap' +import type { WidgetTypeMap } from './widgets/widgetMap' + +// #region Types + +export type NodeId = number | string + +export type NodeProperty = string | number | boolean | object + +interface INodePropertyInfo { + name: string + type?: string + default_value: NodeProperty | undefined +} + +interface IMouseOverData { + inputId?: number + outputId?: number + overWidget?: IBaseWidget +} + +interface ConnectByTypeOptions { + /** @deprecated Events */ + createEventInCase?: boolean + /** Allow our wildcard slot to connect to typed slots on remote node. Default: true */ + wildcardToTyped?: boolean + /** Allow our typed slot to connect to wildcard slots on remote node. Default: true */ + typedToWildcard?: boolean + /** The {@link Reroute.id} that the connection is being dragged from. */ + afterRerouteId?: RerouteId +} + +/** Internal type used for type safety when implementing generic checks for inputs & outputs */ +interface IGenericLinkOrLinks { + links?: INodeOutputSlot['links'] + link?: INodeInputSlot['link'] +} + +interface FindFreeSlotOptions { + /** Slots matching these types will be ignored. Default: [] */ + typesNotAccepted?: ISlotType[] + /** If true, the slot itself is returned instead of the index. Default: false */ + returnObj?: boolean +} + +interface DrawSlotsOptions { + fromSlot?: INodeInputSlot | INodeOutputSlot + colorContext: DefaultConnectionColors + editorAlpha: number + lowQuality: boolean +} + +interface DrawWidgetsOptions { + lowQuality?: boolean + editorAlpha?: number +} + +interface DrawTitleOptions { + scale: number + title_height?: number + low_quality?: boolean +} + +interface DrawTitleTextOptions extends DrawTitleOptions { + default_title_color: string +} + +export interface DrawTitleBoxOptions extends DrawTitleOptions { + box_size?: number +} + +/* +title: string +pos: [x,y] +size: [x,y] + +input|output: every connection + + { name:string, type:string, pos: [x,y]=Optional, direction: "input"|"output", links: Array }); + +general properties: + + clip_area: if you render outside the node, it will be clipped + + unsafe_execution: not allowed for safe execution + + skip_repeated_outputs: when adding new outputs, it won't show if there is one already connected + + resizable: if set to false it won't be resizable with the mouse + + widgets_start_y: widgets start at y distance from the top of the node + +flags object: + + collapsed: if it is collapsed + +supported callbacks: + + onAdded: when added to graph (warning: this is called BEFORE the node is configured when loading) + + onRemoved: when removed from graph + + onStart: when the graph starts playing + + onStop: when the graph stops playing + + onDrawForeground: render the inside widgets inside the node + + onDrawBackground: render the background area inside the node (only in edit mode) + + onMouseDown + + onMouseMove + + onMouseUp + + onMouseEnter + + onMouseLeave + + onExecute: execute the node + + onPropertyChanged: when a property is changed in the panel (return true to skip default behaviour) + + onGetInputs: returns an array of possible inputs + + onGetOutputs: returns an array of possible outputs + + onBounding: in case this node has a bigger bounding than the node itself (the callback receives the bounding as [x,y,w,h]) + + onDblClick: double clicked in the node + + onNodeTitleDblClick: double clicked in the node title + + onInputDblClick: input slot double clicked (can be used to automatically create a node connected) + + onOutputDblClick: output slot double clicked (can be used to automatically create a node connected) + + onConfigure: called after the node has been configured + + onSerialize: to add extra info when serializing (the callback receives the object that should be filled with the data) + + onSelected + + onDeselected + + onDropItem : DOM item dropped over the node + + onDropFile : file dropped over the node + + onConnectInput : if returns false the incoming connection will be canceled + + onConnectionsChange : a connection changed (new one or removed) (NodeSlotType.INPUT or NodeSlotType.OUTPUT, slot, true if connected, link_info, input_info ) + + onAction: action slot triggered + + getExtraMenuOptions: to add option to context menu +*/ + +export interface LGraphNode { + constructor: LGraphNodeConstructor +} + +// #endregion Types + +/** + * Base class for all nodes + * @param title a name for the node + * @param type a type for the node + */ + +export class LGraphNode + implements NodeLike, Positionable, IPinnable, IColorable +{ + // Static properties used by dynamic child classes + static title?: string + static MAX_CONSOLE?: number + static type?: string + static category?: string + static description?: string + static filter?: string + static skip_list?: boolean + + static resizeHandleSize = 15 + static resizeEdgeSize = 5 + + /** Default setting for {@link LGraphNode.connectInputToOutput}. @see {@link INodeFlags.keepAllLinksOnBypass} */ + static keepAllLinksOnBypass: boolean = false + + /** The title text of the node. */ + title: string + /** + * The font style used to render the node's title text. + */ + get titleFontStyle(): string { + return `${LiteGraph.NODE_TEXT_SIZE}px ${LiteGraph.NODE_FONT}` + } + + get innerFontStyle(): string { + return `normal ${LiteGraph.NODE_SUBTEXT_SIZE}px ${LiteGraph.NODE_FONT}` + } + + get displayType(): string { + return this.type + } + + graph: LGraph | Subgraph | null = null + id: NodeId + type: string = '' + inputs: INodeInputSlot[] = [] + outputs: INodeOutputSlot[] = [] + + #concreteInputs: NodeInputSlot[] = [] + #concreteOutputs: NodeOutputSlot[] = [] + + properties: Dictionary = {} + properties_info: INodePropertyInfo[] = [] + flags: INodeFlags = {} + widgets?: IBaseWidget[] + + /** Property manager for this node */ + changeTracker: LGraphNodeProperties + + /** + * The amount of space available for widgets to grow into. + * @see {@link layoutWidgets} + */ + freeWidgetSpace?: number + + locked?: boolean + + /** Execution order, automatically computed during run @see {@link LGraph.computeExecutionOrder} */ + order: number = 0 + mode: LGraphEventMode = LGraphEventMode.ALWAYS + last_serialization?: ISerialisedNode + serialize_widgets?: boolean + /** + * The overridden fg color used to render the node. + * @see {@link renderingColor} + */ + color?: string + /** + * The overridden bg color used to render the node. + * @see {@link renderingBgColor} + */ + bgcolor?: string + /** + * The overridden box color used to render the node. + * @see {@link renderingBoxColor} + */ + boxcolor?: string + + /** The fg color used to render the node. */ + get renderingColor(): string { + const baseColor = + this.color || this.constructor.color || LiteGraph.NODE_DEFAULT_COLOR + return adjustColor(baseColor, { lightness: LiteGraph.nodeLightness }) + } + + /** The bg color used to render the node. */ + get renderingBgColor(): string { + const baseBgColor = + this.bgcolor || this.constructor.bgcolor || LiteGraph.NODE_DEFAULT_BGCOLOR + const adjustments: ColorAdjustOptions = { + opacity: LiteGraph.nodeOpacity, + lightness: LiteGraph.nodeLightness + } + + return adjustColor( + this.mode === LGraphEventMode.BYPASS + ? LiteGraph.NODE_DEFAULT_BYPASS_COLOR + : baseBgColor, + adjustments + ) + } + + /** The box color used to render the node. */ + get renderingBoxColor(): string { + if (this.boxcolor) return this.boxcolor + + if (LiteGraph.node_box_coloured_when_on) { + if (this.action_triggered) return '#FFF' + if (this.execute_triggered) return '#AAA' + } + + if (LiteGraph.node_box_coloured_by_mode) { + const modeColour = + LiteGraph.NODE_MODES_COLORS[this.mode ?? LGraphEventMode.ALWAYS] + if (modeColour) return modeColour + } + return LiteGraph.NODE_DEFAULT_BOXCOLOR + } + + /** @inheritdoc {@link IColorable.setColorOption} */ + setColorOption(colorOption: ColorOption | null): void { + if (colorOption == null) { + this.color = undefined + this.bgcolor = undefined + } else { + this.color = colorOption.color + this.bgcolor = colorOption.bgcolor + } + } + + /** @inheritdoc {@link IColorable.getColorOption} */ + getColorOption(): ColorOption | null { + return ( + Object.values(LGraphCanvas.node_colors).find( + (colorOption) => + colorOption.color === this.color && + colorOption.bgcolor === this.bgcolor + ) ?? null + ) + } + + /** + * The stroke styles that should be applied to the node. + */ + strokeStyles: Record< + string, + (this: LGraphNode) => IDrawBoundingOptions | undefined + > + + /** + * The progress of node execution. Used to render a progress bar. Value between 0 and 1. + */ + progress?: number + + exec_version?: number + action_call?: string + execute_triggered?: number + action_triggered?: number + widgets_up?: boolean + widgets_start_y?: number + lostFocusAt?: number + gotFocusAt?: number + badges: (LGraphBadge | (() => LGraphBadge))[] = [] + title_buttons: LGraphButton[] = [] + badgePosition: BadgePosition = BadgePosition.TopLeft + onOutputRemoved?(this: LGraphNode, slot: number): void + onInputRemoved?(this: LGraphNode, slot: number, input: INodeInputSlot): void + /** + * The width of the node when collapsed. + * Updated by {@link LGraphCanvas.drawNode} + */ + _collapsed_width?: number + /** + * Called once at the start of every frame. Caller may change the values in {@link out}, which will be reflected in {@link boundingRect}. + * WARNING: Making changes to boundingRect via onBounding is poorly supported, and will likely result in strange behaviour. + */ + onBounding?(this: LGraphNode, out: Rect): void + console?: string[] + _level?: number + _shape?: RenderShape + mouseOver?: IMouseOverData + redraw_on_mouse?: boolean + resizable?: boolean + clonable?: boolean + _relative_id?: number + clip_area?: boolean + ignore_remove?: boolean + has_errors?: boolean + removable?: boolean + block_delete?: boolean + selected?: boolean + showAdvanced?: boolean + + declare comfyDynamic?: Record + declare comfyClass?: string + declare isVirtualNode?: boolean + applyToGraph?(extraLinks?: LLink[]): void + + isSubgraphNode(): this is SubgraphNode { + return false + } + + /** @inheritdoc {@link renderArea} */ + #renderArea = new Rectangle() + /** + * Rect describing the node area, including shadows and any protrusions. + * Determines if the node is visible. Calculated once at the start of every frame. + */ + get renderArea(): ReadOnlyRect { + return this.#renderArea + } + + /** @inheritdoc {@link boundingRect} */ + #boundingRect: Rectangle = new Rectangle() + /** + * Cached node position & area as `x, y, width, height`. Includes changes made by {@link onBounding}, if present. + * + * Determines the node hitbox and other rendering effects. Calculated once at the start of every frame. + */ + get boundingRect(): ReadOnlyRectangle { + return this.#boundingRect + } + + /** The offset from {@link pos} to the top-left of {@link boundingRect}. */ + get boundingOffset(): Readonly { + const { + pos: [posX, posY], + boundingRect: [bX, bY] + } = this + return [posX - bX, posY - bY] + } + + /** {@link pos} and {@link size} values are backed by this {@link Rectangle}. */ + _posSize = new Rectangle() + _pos: Point = this._posSize.pos + _size: Size = this._posSize.size + + public get pos() { + return this._pos + } + + /** Node position does not necessarily correlate to the top-left corner. */ + public set pos(value) { + if (!value || value.length < 2) return + + this._pos[0] = value[0] + this._pos[1] = value[1] + } + + public get size() { + return this._size + } + + public set size(value) { + if (!value || value.length < 2) return + + this._size[0] = value[0] + this._size[1] = value[1] + } + + /** + * The size of the node used for rendering. + */ + get renderingSize(): Size { + return this.flags.collapsed ? [this._collapsed_width ?? 0, 0] : this._size + } + + get shape(): RenderShape | undefined { + return this._shape + } + + set shape(v: RenderShape | 'default' | 'box' | 'round' | 'circle' | 'card') { + const oldValue = this._shape + switch (v) { + case 'default': + this._shape = undefined + break + case 'box': + this._shape = RenderShape.BOX + break + case 'round': + this._shape = RenderShape.ROUND + break + case 'circle': + this._shape = RenderShape.CIRCLE + break + case 'card': + this._shape = RenderShape.CARD + break + default: + this._shape = v + } + if (oldValue !== this._shape) { + this.graph?.trigger('node:property:changed', { + nodeId: this.id, + property: 'shape', + oldValue, + newValue: this._shape + }) + } + } + + /** + * The shape of the node used for rendering. @see {@link RenderShape} + */ + get renderingShape(): RenderShape { + return this._shape || this.constructor.shape || LiteGraph.NODE_DEFAULT_SHAPE + } + + public get is_selected(): boolean | undefined { + return this.selected + } + + public set is_selected(value: boolean) { + this.selected = value + } + + public get title_mode(): TitleMode { + return this.constructor.title_mode ?? TitleMode.NORMAL_TITLE + } + + onConnectInput?( + this: LGraphNode, + target_slot: number, + type: unknown, + output: INodeOutputSlot | SubgraphIO, + node: LGraphNode | SubgraphInputNode, + slot: number + ): boolean + onConnectOutput?( + this: LGraphNode, + slot: number, + type: unknown, + input: INodeInputSlot | SubgraphIO, + target_node: number | LGraphNode | SubgraphOutputNode, + target_slot: number + ): boolean + onResize?(this: LGraphNode, size: Size): void + onPropertyChanged?( + this: LGraphNode, + name: string, + value: unknown, + prev_value?: unknown + ): boolean + /** Called for each connection that is created, updated, or removed. This includes "restored" connections when deserialising. */ + onConnectionsChange?( + this: LGraphNode, + type: ISlotType, + index: number, + isConnected: boolean, + link_info: LLink | null | undefined, + inputOrOutput: INodeInputSlot | INodeOutputSlot | SubgraphIO + ): void + onInputAdded?(this: LGraphNode, input: INodeInputSlot): void + onOutputAdded?(this: LGraphNode, output: INodeOutputSlot): void + onConfigure?(this: LGraphNode, serialisedNode: ISerialisedNode): void + onSerialize?(this: LGraphNode, serialised: ISerialisedNode): void + onExecute?( + this: LGraphNode, + param?: unknown, + options?: { action_call?: string } + ): void + onAction?( + this: LGraphNode, + action: string, + param: unknown, + options: { action_call?: string } + ): void + onDrawBackground?(this: LGraphNode, ctx: CanvasRenderingContext2D): void + onNodeCreated?(this: LGraphNode): void + /** + * Callback invoked by {@link connect} to override the target slot index. + * Its return value overrides the target index selection. + * @param target_slot The current input slot index + * @param requested_slot The originally requested slot index - could be negative, or if using (deprecated) name search, a string + * @returns {number | null} If a number is returned, the connection will be made to that input index. + * If an invalid index or non-number (false, null, NaN etc) is returned, the connection will be cancelled. + */ + onBeforeConnectInput?( + this: LGraphNode, + target_slot: number, + requested_slot?: number | string + ): number | false | null + onShowCustomPanelInfo?(this: LGraphNode, panel: any): void + onAddPropertyToPanel?(this: LGraphNode, pName: string, panel: any): boolean + onWidgetChanged?( + this: LGraphNode, + name: string, + value: unknown, + old_value: unknown, + w: IBaseWidget + ): void + onDeselected?(this: LGraphNode): void + onKeyUp?(this: LGraphNode, e: KeyboardEvent): void + onKeyDown?(this: LGraphNode, e: KeyboardEvent): void + onSelected?(this: LGraphNode): void + getExtraMenuOptions?( + this: LGraphNode, + canvas: LGraphCanvas, + options: (IContextMenuValue | null)[] + ): (IContextMenuValue | null)[] + getMenuOptions?(this: LGraphNode, canvas: LGraphCanvas): IContextMenuValue[] + onAdded?(this: LGraphNode, graph: LGraph): void + onDrawCollapsed?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + cavnas: LGraphCanvas + ): boolean + onDrawForeground?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + canvas: LGraphCanvas, + canvasElement: HTMLCanvasElement + ): void + onMouseLeave?(this: LGraphNode, e: CanvasPointerEvent): void + /** + * Override the default slot menu options. + */ + getSlotMenuOptions?(this: LGraphNode, slot: IFoundSlot): IContextMenuValue[] + /** + * Add extra menu options to the slot context menu. + */ + getExtraSlotMenuOptions?( + this: LGraphNode, + slot: IFoundSlot + ): IContextMenuValue[] + + // FIXME: Re-typing + onDropItem?(this: LGraphNode, event: Event): boolean + onDropData?( + this: LGraphNode, + data: string | ArrayBuffer, + filename: string, + file: File + ): void + onDropFile?(this: LGraphNode, file: File): void + onInputClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void + onInputDblClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void + onOutputClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void + onOutputDblClick?( + this: LGraphNode, + index: number, + e: CanvasPointerEvent + ): void + // TODO: Return type + onGetPropertyInfo?(this: LGraphNode, property: string): any + onNodeOutputAdd?(this: LGraphNode, value: unknown): void + onNodeInputAdd?(this: LGraphNode, value: unknown): void + onMenuNodeInputs?( + this: LGraphNode, + entries: (IContextMenuValue | null)[] + ): (IContextMenuValue | null)[] + onMenuNodeOutputs?( + this: LGraphNode, + entries: (IContextMenuValue | null)[] + ): (IContextMenuValue | null)[] + onMouseUp?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): void + onMouseEnter?(this: LGraphNode, e: CanvasPointerEvent): void + /** Blocks drag if return value is truthy. @param pos Offset from {@link LGraphNode.pos}. */ + onMouseDown?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): boolean + /** @param pos Offset from {@link LGraphNode.pos}. */ + onDblClick?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): void + /** @param pos Offset from {@link LGraphNode.pos}. */ + onNodeTitleDblClick?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): void + onDrawTitle?(this: LGraphNode, ctx: CanvasRenderingContext2D): void + onDrawTitleText?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + title_height: number, + size: Size, + scale: number, + title_text_font: string, + selected?: boolean + ): void + onDrawTitleBox?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + title_height: number, + size: Size, + scale: number + ): void + onDrawTitleBar?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + title_height: number, + size: Size, + scale: number, + fgcolor: string + ): void + onRemoved?(this: LGraphNode): void + onMouseMove?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + arg2: LGraphCanvas + ): void + onPropertyChange?(this: LGraphNode): void + updateOutputData?(this: LGraphNode, origin_slot: number): void + + #getErrorStrokeStyle(this: LGraphNode): IDrawBoundingOptions | undefined { + if (this.has_errors) { + return { + padding: 12, + lineWidth: 10, + color: LiteGraph.NODE_ERROR_COLOUR + } + } + } + + #getSelectedStrokeStyle(this: LGraphNode): IDrawBoundingOptions | undefined { + if (this.selected) { + return { + padding: this.has_errors ? 20 : undefined + } + } + } + + constructor(title: string, type?: string) { + this.id = LiteGraph.use_uuids ? LiteGraph.uuidv4() : -1 + this.title = title || 'Unnamed' + this.type = type ?? '' + this.size = [LiteGraph.NODE_WIDTH, 60] + this.pos = [10, 10] + this.strokeStyles = { + error: this.#getErrorStrokeStyle, + selected: this.#getSelectedStrokeStyle + } + // Initialize property manager with tracked properties + this.changeTracker = new LGraphNodeProperties(this) + } + + /** Internal callback for subgraph nodes. Do not implement externally. */ + _internalConfigureAfterSlots?(): void + + /** + * configure a node from an object containing the serialized info + */ + configure(info: ISerialisedNode): void { + if (this.graph) { + this.graph._version++ + } + for (const j in info) { + if (j == 'properties') { + // i don't want to clone properties, I want to reuse the old container + for (const k in info.properties) { + this.properties[k] = info.properties[k] + this.onPropertyChanged?.(k, info.properties[k]) + } + continue + } + + // @ts-expect-error #594 + if (info[j] == null) { + continue + // @ts-expect-error #594 + } else if (typeof info[j] == 'object') { + // @ts-expect-error #594 + if (this[j]?.configure) { + // @ts-expect-error #594 + this[j]?.configure(info[j]) + } else { + // @ts-expect-error #594 + this[j] = LiteGraph.cloneObject(info[j], this[j]) + } + } else { + // value + // @ts-expect-error #594 + this[j] = info[j] + } + } + + if (!info.title) { + this.title = this.constructor.title + } + + this.inputs ??= [] + this.inputs = this.inputs.map((input) => + toClass(NodeInputSlot, input, this) + ) + for (const [i, input] of this.inputs.entries()) { + const link = + this.graph && input.link != null + ? this.graph._links.get(input.link) + : null + this.onConnectionsChange?.(NodeSlotType.INPUT, i, true, link, input) + this.onInputAdded?.(input) + } + + this.outputs ??= [] + this.outputs = this.outputs.map((output) => + toClass(NodeOutputSlot, output, this) + ) + for (const [i, output] of this.outputs.entries()) { + if (!output.links) continue + + for (const linkId of output.links) { + const link = this.graph ? this.graph._links.get(linkId) : null + this.onConnectionsChange?.(NodeSlotType.OUTPUT, i, true, link, output) + } + this.onOutputAdded?.(output) + } + + // SubgraphNode callback. + this._internalConfigureAfterSlots?.() + + if (this.widgets) { + for (const w of this.widgets) { + if (!w) continue + + const input = this.inputs.find((i) => i.widget?.name === w.name) + if (input?.label) w.label = input.label + + if ( + w.options?.property && + this.properties[w.options.property] != undefined + ) + w.value = JSON.parse( + JSON.stringify(this.properties[w.options.property]) + ) + } + + if (info.widgets_values) { + let i = 0 + for (const widget of this.widgets ?? []) { + if (widget.serialize === false) continue + if (i >= info.widgets_values.length) break + widget.value = info.widgets_values[i++] + } + } + } + + // Sync the state of this.resizable. + if (this.pinned) this.resizable = false + + this.onConfigure?.(info) + } + + /** + * serialize the content + */ + serialize(): ISerialisedNode { + // create serialization object + const o: ISerialisedNode = { + id: this.id, + type: this.type, + pos: [this.pos[0], this.pos[1]], + size: [this.size[0], this.size[1]], + flags: LiteGraph.cloneObject(this.flags), + order: this.order, + mode: this.mode, + showAdvanced: this.showAdvanced + } + + // special case for when there were errors + if (this.constructor === LGraphNode && this.last_serialization) + return { ...this.last_serialization, mode: o.mode, pos: o.pos } + + if (this.inputs) + o.inputs = this.inputs.map((input) => inputAsSerialisable(input)) + if (this.outputs) + // @ts-expect-error - Output serialization type mismatch + o.outputs = this.outputs.map((output) => outputAsSerialisable(output)) + + if (this.title && this.title != this.constructor.title) o.title = this.title + + if (this.properties) o.properties = LiteGraph.cloneObject(this.properties) + + const { widgets } = this + if (widgets && this.serialize_widgets) { + o.widgets_values = [] + for (const [i, widget] of widgets.entries()) { + if (widget.serialize === false) continue + // @ts-expect-error #595 No-null + o.widgets_values[i] = widget ? widget.value : null + } + } + + if (!o.type && this.constructor.type) o.type = this.constructor.type + + if (this.color) o.color = this.color + if (this.bgcolor) o.bgcolor = this.bgcolor + if (this.boxcolor) o.boxcolor = this.boxcolor + if (this.shape) o.shape = this.shape + + if (this.onSerialize?.(o)) + console.warn( + "node onSerialize shouldn't return anything, data should be stored in the object pass in the first parameter" + ) + + return o + } + + /* Creates a clone of this node */ + clone(): LGraphNode | null { + if (this.type == null) return null + const node = LiteGraph.createNode(this.type) + if (!node) return null + + // we clone it because serialize returns shared containers + const data = LiteGraph.cloneObject(this.serialize()) + const { inputs, outputs } = data + + // remove links + if (inputs) { + for (const input of inputs) { + input.link = null + } + } + + if (outputs) { + for (const { links } of outputs) { + if (links) links.length = 0 + } + } + + // @ts-expect-error Exceptional case: id is removed so that the graph can assign a new one on add. + data.id = undefined + + if (LiteGraph.use_uuids) data.id = LiteGraph.uuidv4() + + node.configure(data) + + return node + } + + /** + * serialize and stringify + */ + toString(): string { + return JSON.stringify(this.serialize()) + } + + /** + * get the title string + */ + getTitle(): string { + return this.title || this.constructor.title + } + + /** + * sets the value of a property + * @param name + * @param value + */ + setProperty(name: string, value: TWidgetValue): void { + this.properties ||= {} + if (value === this.properties[name]) return + + const prev_value = this.properties[name] + this.properties[name] = value + // abort change + if (this.onPropertyChanged?.(name, value, prev_value) === false) + this.properties[name] = prev_value + + if (this.widgets) { + for (const w of this.widgets) { + if (!w) continue + + if (w.options.property == name) { + w.value = value + break + } + } + } + } + + /** + * sets the output data + * @param slot + * @param data + */ + setOutputData( + slot: number, + data: number | string | boolean | { toToolTip?(): string } + ): void { + const { outputs } = this + if (!outputs) return + + // this maybe slow and a niche case + if (slot == -1 || slot >= outputs.length) return + + const output_info = outputs[slot] + if (!output_info) return + + // store data in the output itself in case we want to debug + output_info._data = data + + if (!this.graph) throw new NullGraphError() + + // if there are connections, pass the data to the connections + const { links } = outputs[slot] + if (links) { + for (const id of links) { + const link = this.graph._links.get(id) + if (link) link.data = data + } + } + } + + /** + * sets the output data type, useful when you want to be able to overwrite the data type + */ + setOutputDataType(slot: number, type: ISlotType): void { + const { outputs } = this + if (!outputs || slot == -1 || slot >= outputs.length) return + + const output_info = outputs[slot] + if (!output_info) return + // store data in the output itself in case we want to debug + output_info.type = type + + if (!this.graph) throw new NullGraphError() + + // if there are connections, pass the data to the connections + const { links } = outputs[slot] + if (links) { + for (const id of links) { + const link = this.graph._links.get(id) + if (link) link.type = type + } + } + } + + /** + * Retrieves the input data (data traveling through the connection) from one slot + * @param slot + * @param force_update if set to true it will force the connected node of this slot to output data into this link + * @returns data or if it is not connected returns undefined + */ + getInputData(slot: number, force_update?: boolean): unknown { + if (!this.inputs) return + + if (slot >= this.inputs.length || this.inputs[slot].link == null) return + if (!this.graph) throw new NullGraphError() + + const link_id = this.inputs[slot].link + const link = this.graph._links.get(link_id) + // bug: weird case but it happens sometimes + if (!link) return null + + if (!force_update) return link.data + + // special case: used to extract data from the incoming connection before the graph has been executed + const node = this.graph.getNodeById(link.origin_id) + if (!node) return link.data + + if (node.updateOutputData) { + node.updateOutputData(link.origin_slot) + } else { + node.onExecute?.() + } + + return link.data + } + + /** + * Retrieves the input data type (in case this supports multiple input types) + * @param slot + * @returns datatype in string format + */ + getInputDataType(slot: number): ISlotType | null { + if (!this.inputs) return null + if (slot >= this.inputs.length || this.inputs[slot].link == null) + return null + if (!this.graph) throw new NullGraphError() + + const link_id = this.inputs[slot].link + const link = this.graph._links.get(link_id) + // bug: weird case but it happens sometimes + if (!link) return null + + const node = this.graph.getNodeById(link.origin_id) + if (!node) return link.type + + const output_info = node.outputs[link.origin_slot] + return output_info ? output_info.type : null + } + + /** + * Retrieves the input data from one slot using its name instead of slot number + * @param slot_name + * @param force_update if set to true it will force the connected node of this slot to output data into this link + * @returns data or if it is not connected returns null + */ + getInputDataByName(slot_name: string, force_update: boolean): unknown { + const slot = this.findInputSlot(slot_name) + return slot == -1 ? null : this.getInputData(slot, force_update) + } + + /** + * tells you if there is a connection in one input slot + * @param slot The 0-based index of the input to check + * @returns `true` if the input slot has a link ID (does not perform validation) + */ + isInputConnected(slot: number): boolean { + if (!this.inputs) return false + return slot < this.inputs.length && this.inputs[slot].link != null + } + + /** + * tells you info about an input connection (which node, type, etc) + * @returns object or null { link: id, name: string, type: string or 0 } + */ + getInputInfo(slot: number): INodeInputSlot | null { + return !this.inputs || !(slot < this.inputs.length) + ? null + : this.inputs[slot] + } + + /** + * Returns the link info in the connection of an input slot + * @returns object or null + */ + getInputLink(slot: number): LLink | null { + if (!this.inputs) return null + + if (slot < this.inputs.length) { + if (!this.graph) throw new NullGraphError() + + const input = this.inputs[slot] + if (input.link != null) { + return this.graph._links.get(input.link) ?? null + } + } + return null + } + + /** + * returns the node connected in the input slot + * @returns node or null + */ + getInputNode(slot: number): LGraphNode | null { + if (!this.inputs) return null + if (slot >= this.inputs.length) return null + + const input = this.inputs[slot] + if (!input || input.link === null) return null + if (!this.graph) throw new NullGraphError() + + const link_info = this.graph._links.get(input.link) + if (!link_info) return null + + return this.graph.getNodeById(link_info.origin_id) + } + + /** + * returns the value of an input with this name, otherwise checks if there is a property with that name + * @returns value + */ + getInputOrProperty(name: string): unknown { + const { inputs } = this + if (!inputs?.length) { + return this.properties ? this.properties[name] : null + } + if (!this.graph) throw new NullGraphError() + + for (const input of inputs) { + if (name == input.name && input.link != null) { + const link = this.graph._links.get(input.link) + if (link) return link.data + } + } + return this.properties[name] + } + + /** + * tells you the last output data that went in that slot + * @returns object or null + */ + getOutputData(slot: number): unknown { + if (!this.outputs) return null + if (slot >= this.outputs.length) return null + + const info = this.outputs[slot] + return info._data + } + + /** + * tells you info about an output connection (which node, type, etc) + * @returns object or null { name: string, type: string, links: [ ids of links in number ] } + */ + getOutputInfo(slot: number): INodeOutputSlot | null { + return !this.outputs || !(slot < this.outputs.length) + ? null + : this.outputs[slot] + } + + /** + * tells you if there is a connection in one output slot + */ + isOutputConnected(slot: number): boolean { + if (!this.outputs) return false + return ( + slot < this.outputs.length && Number(this.outputs[slot].links?.length) > 0 + ) + } + + /** + * tells you if there is any connection in the output slots + */ + isAnyOutputConnected(): boolean { + const { outputs } = this + if (!outputs) return false + + for (const output of outputs) { + if (output.links?.length) return true + } + return false + } + + /** + * retrieves all the nodes connected to this output slot + */ + getOutputNodes(slot: number): LGraphNode[] | null { + const { outputs } = this + if (!outputs || outputs.length == 0) return null + + if (slot >= outputs.length) return null + + const { links } = outputs[slot] + if (!links || links.length == 0) return null + if (!this.graph) throw new NullGraphError() + + const r: LGraphNode[] = [] + for (const id of links) { + const link = this.graph._links.get(id) + if (link) { + const target_node = this.graph.getNodeById(link.target_id) + if (target_node) { + r.push(target_node) + } + } + } + return r + } + + addOnTriggerInput(): number { + const trigS = this.findInputSlot('onTrigger') + if (trigS == -1) { + this.addInput('onTrigger', LiteGraph.EVENT, { + nameLocked: true + }) + return this.findInputSlot('onTrigger') + } + return trigS + } + + addOnExecutedOutput(): number { + const trigS = this.findOutputSlot('onExecuted') + if (trigS == -1) { + this.addOutput('onExecuted', LiteGraph.ACTION, { + nameLocked: true + }) + return this.findOutputSlot('onExecuted') + } + return trigS + } + + onAfterExecuteNode(param: unknown, options?: { action_call?: string }) { + const trigS = this.findOutputSlot('onExecuted') + if (trigS != -1) { + this.triggerSlot(trigS, param, null, options) + } + } + + changeMode(modeTo: number): boolean { + switch (modeTo) { + case LGraphEventMode.ON_EVENT: + break + + case LGraphEventMode.ON_TRIGGER: + this.addOnTriggerInput() + this.addOnExecutedOutput() + break + + case LGraphEventMode.NEVER: + break + + case LGraphEventMode.ALWAYS: + break + + // @ts-expect-error Not impl. + case LiteGraph.ON_REQUEST: + break + + default: + return false + break + } + this.mode = modeTo + return true + } + + /** + * Triggers the node code execution, place a boolean/counter to mark the node as being executed + */ + doExecute(param?: unknown, options?: { action_call?: string }): void { + options = options || {} + if (this.onExecute) { + // enable this to give the event an ID + options.action_call ||= `${this.id}_exec_${Math.floor(Math.random() * 9999)}` + if (!this.graph) throw new NullGraphError() + + // @ts-expect-error Technically it works when id is a string. Array gets props. + this.graph.nodes_executing[this.id] = true + this.onExecute(param, options) + // @ts-expect-error deprecated + this.graph.nodes_executing[this.id] = false + + // save execution/action ref + this.exec_version = this.graph.iteration + if (options?.action_call) { + this.action_call = options.action_call + // @ts-expect-error deprecated + this.graph.nodes_executedAction[this.id] = options.action_call + } + } + // the nFrames it will be used (-- each step), means "how old" is the event + this.execute_triggered = 2 + this.onAfterExecuteNode?.(param, options) + } + + /** + * Triggers an action, wrapped by logics to control execution flow + * @param action name + */ + actionDo( + action: string, + param: unknown, + options: { action_call?: string } + ): void { + options = options || {} + if (this.onAction) { + // enable this to give the event an ID + options.action_call ||= `${this.id}_${action || 'action'}_${Math.floor(Math.random() * 9999)}` + if (!this.graph) throw new NullGraphError() + + // @ts-expect-error deprecated + this.graph.nodes_actioning[this.id] = action || 'actioning' + this.onAction(action, param, options) + // @ts-expect-error deprecated + this.graph.nodes_actioning[this.id] = false + + // save execution/action ref + if (options?.action_call) { + this.action_call = options.action_call + // @ts-expect-error deprecated + this.graph.nodes_executedAction[this.id] = options.action_call + } + } + // the nFrames it will be used (-- each step), means "how old" is the event + this.action_triggered = 2 + this.onAfterExecuteNode?.(param, options) + } + + /** + * Triggers an event in this node, this will trigger any output with the same name + * @param action name ( "on_play", ... ) if action is equivalent to false then the event is send to all + */ + trigger( + action: string, + param: unknown, + options: { action_call?: string } + ): void { + const { outputs } = this + if (!outputs || !outputs.length) { + return + } + + if (this.graph) this.graph._last_trigger_time = LiteGraph.getTime() + + for (const [i, output] of outputs.entries()) { + if ( + !output || + output.type !== LiteGraph.EVENT || + (action && output.name != action) + ) { + continue + } + this.triggerSlot(i, param, null, options) + } + } + + /** + * Triggers a slot event in this node: cycle output slots and launch execute/action on connected nodes + * @param slot the index of the output slot + * @param link_id [optional] in case you want to trigger and specific output link in a slot + */ + triggerSlot( + slot: number, + param: unknown, + link_id: number | null, + options?: { action_call?: string } + ): void { + options = options || {} + if (!this.outputs) return + + if (slot == null) { + console.error('slot must be a number') + return + } + + if (typeof slot !== 'number') + console.warn( + "slot must be a number, use node.trigger('name') if you want to use a string" + ) + + const output = this.outputs[slot] + if (!output) return + + const links = output.links + if (!links || !links.length) return + + if (!this.graph) throw new NullGraphError() + this.graph._last_trigger_time = LiteGraph.getTime() + + // for every link attached here + for (const id of links) { + // to skip links + if (link_id != null && link_id != id) continue + + const link_info = this.graph._links.get(id) + // not connected + if (!link_info) continue + + link_info._last_time = LiteGraph.getTime() + const node = this.graph.getNodeById(link_info.target_id) + // node not found? + if (!node) continue + + if (node.mode === LGraphEventMode.ON_TRIGGER) { + // generate unique trigger ID if not present + if (!options.action_call) + options.action_call = `${this.id}_trigg_${Math.floor(Math.random() * 9999)}` + // -- wrapping node.onExecute(param); -- + node.doExecute?.(param, options) + } else if (node.onAction) { + // generate unique action ID if not present + if (!options.action_call) + options.action_call = `${this.id}_act_${Math.floor(Math.random() * 9999)}` + // pass the action name + const target_connection = node.inputs[link_info.target_slot] + node.actionDo(target_connection.name, param, options) + } + } + } + + /** + * clears the trigger slot animation + * @param slot the index of the output slot + * @param link_id [optional] in case you want to trigger and specific output link in a slot + */ + clearTriggeredSlot(slot: number, link_id: number): void { + if (!this.outputs) return + + const output = this.outputs[slot] + if (!output) return + + const links = output.links + if (!links || !links.length) return + + if (!this.graph) throw new NullGraphError() + + // for every link attached here + for (const id of links) { + // to skip links + if (link_id != null && link_id != id) continue + + const link_info = this.graph._links.get(id) + // not connected + if (!link_info) continue + + link_info._last_time = 0 + } + } + + /** + * changes node size and triggers callback + */ + setSize(size: Size): void { + this.size = size + this.onResize?.(this.size) + } + + /** + * Expands the node size to fit its content. + */ + expandToFitContent(): void { + const newSize = this.computeSize() + this.setSize([ + Math.max(this.size[0], newSize[0]), + Math.max(this.size[1], newSize[1]) + ]) + } + + /** + * add a new property to this node + * @param type string defining the output type ("vec3","number",...) + * @param extra_info this can be used to have special properties of the property (like values, etc) + */ + addProperty( + name: string, + default_value: NodeProperty | undefined, + type?: string, + extra_info?: Partial + ): INodePropertyInfo { + const o: INodePropertyInfo = { name, type, default_value } + if (extra_info) Object.assign(o, extra_info) + + this.properties_info ||= [] + this.properties_info.push(o) + this.properties ||= {} + this.properties[name] = default_value + return o + } + + /** + * add a new output slot to use in this node + * @param type string defining the output type ("vec3","number",...) + * @param extra_info this can be used to have special properties of an output (label, special color, position, etc) + */ + addOutput>( + name: string, + type: ISlotType, + extra_info?: TProperties + ): INodeOutputSlot & TProperties { + const output = Object.assign( + new NodeOutputSlot({ name, type, links: null }, this), + extra_info + ) + + this.outputs ||= [] + this.outputs.push(output) + this.onOutputAdded?.(output) + + if (LiteGraph.auto_load_slot_types) + LiteGraph.registerNodeAndSlotType(this, type, true) + + this.expandToFitContent() + this.setDirtyCanvas(true, true) + return output + } + + /** + * remove an existing output slot + */ + removeOutput(slot: number): void { + // Only disconnect if node is part of a graph + if (this.graph) { + this.disconnectOutput(slot) + } + const { outputs } = this + outputs.splice(slot, 1) + + for (let i = slot; i < outputs.length; ++i) { + const output = outputs[i] + if (!output || !output.links) continue + + // Only update link indices if node is part of a graph + if (this.graph) { + for (const linkId of output.links) { + const link = this.graph._links.get(linkId) + if (link) link.origin_slot-- + } + } + } + + this.onOutputRemoved?.(slot) + this.setDirtyCanvas(true, true) + } + + /** + * add a new input slot to use in this node + * @param type string defining the input type ("vec3","number",...), it its a generic one use 0 + * @param extra_info this can be used to have special properties of an input (label, color, position, etc) + */ + addInput>( + name: string, + type: ISlotType, + extra_info?: TProperties + ): INodeInputSlot & TProperties { + type ||= 0 + + const input = Object.assign( + new NodeInputSlot({ name, type, link: null }, this), + extra_info + ) + + this.inputs ||= [] + this.inputs.push(input) + this.expandToFitContent() + + this.onInputAdded?.(input) + LiteGraph.registerNodeAndSlotType(this, type) + + this.setDirtyCanvas(true, true) + return input + } + + /** + * remove an existing input slot + */ + removeInput(slot: number): void { + // Only disconnect if node is part of a graph + if (this.graph) { + this.disconnectInput(slot, true) + } + const { inputs } = this + const slot_info = inputs.splice(slot, 1) + + for (let i = slot; i < inputs.length; ++i) { + const input = inputs[i] + if (!input?.link) continue + + // Only update link indices if node is part of a graph + if (this.graph) { + const link = this.graph._links.get(input.link) + if (link) link.target_slot-- + } + } + this.onInputRemoved?.(slot, slot_info[0]) + this.setDirtyCanvas(true, true) + } + + /** + * computes the minimum size of a node according to its inputs and output slots + * @returns the total size + */ + computeSize(out?: Size): Size { + const ctorSize = this.constructor.size + if (ctorSize) return [ctorSize[0], ctorSize[1]] + + const { inputs, outputs, widgets } = this + let rows = Math.max( + inputs ? inputs.filter((input) => !isWidgetInputSlot(input)).length : 1, + outputs ? outputs.length : 1 + ) + const size = out ?? [0, 0] + rows = Math.max(rows, 1) + // although it should be graphcanvas.inner_text_font size + const font_size = LiteGraph.NODE_TEXT_SIZE + + const padLeft = LiteGraph.NODE_TITLE_HEIGHT + const padRight = padLeft * 0.33 + const title_width = + padLeft + compute_text_size(this.title, this.titleFontStyle) + padRight + let input_width = 0 + let widgetWidth = 0 + let output_width = 0 + + if (inputs) { + for (const input of inputs) { + const text = input.label || input.localized_name || input.name || '' + const text_width = compute_text_size(text, this.innerFontStyle) + if (isWidgetInputSlot(input)) { + const widget = this.getWidgetFromSlot(input) + if (widget && !this.isWidgetVisible(widget)) continue + + if (text_width > widgetWidth) widgetWidth = text_width + } else { + if (text_width > input_width) input_width = text_width + } + } + } + + if (outputs) { + for (const output of outputs) { + const text = output.label || output.localized_name || output.name || '' + const text_width = compute_text_size(text, this.innerFontStyle) + if (output_width < text_width) output_width = text_width + } + } + + const minWidth = LiteGraph.NODE_WIDTH * (widgets?.length ? 1.5 : 1) + // Text + slot width + centre padding + const centrePadding = input_width && output_width ? 5 : 0 + const slotsWidth = + input_width + + output_width + + 2 * LiteGraph.NODE_SLOT_HEIGHT + + centrePadding + + // Total distance from edge of node to the inner edge of the widget 'previous' arrow button + const widgetMargin = + BaseWidget.margin + BaseWidget.arrowMargin + BaseWidget.arrowWidth + const widgetPadding = BaseWidget.minValueWidth + 2 * widgetMargin + if (widgetWidth) widgetWidth += widgetPadding + + size[0] = Math.max(slotsWidth, widgetWidth, title_width, minWidth) + size[1] = + (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT + + // Get widget height & expand size if necessary + let widgets_height = 0 + if (widgets?.length) { + for (const widget of widgets) { + if (!this.isWidgetVisible(widget)) continue + + let widget_height = 0 + if (widget.computeSize) { + widget_height += widget.computeSize(size[0])[1] + } else if (widget.computeLayoutSize) { + // Expand widget width if necessary + const { minHeight, minWidth } = widget.computeLayoutSize(this) + const widgetWidth = minWidth + widgetPadding + if (widgetWidth > size[0]) size[0] = widgetWidth + + widget_height += minHeight + } else { + widget_height += LiteGraph.NODE_WIDGET_HEIGHT + } + widgets_height += widget_height + 4 + } + widgets_height += 8 + } + + // compute height using widgets height + if (this.widgets_up) size[1] = Math.max(size[1], widgets_height) + else if (this.widgets_start_y != null) + size[1] = Math.max(size[1], widgets_height + this.widgets_start_y) + else size[1] += widgets_height + + function compute_text_size(text: string, fontStyle: string) { + return ( + LGraphCanvas._measureText?.(text, fontStyle) ?? + font_size * (text?.length ?? 0) * 0.6 + ) + } + + if (this.constructor.min_height && size[1] < this.constructor.min_height) { + size[1] = this.constructor.min_height + } + + // margin + size[1] += 6 + + return size + } + + inResizeCorner(canvasX: number, canvasY: number): boolean { + const rows = this.outputs ? this.outputs.length : 1 + const outputs_offset = + (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT + return isInRectangle( + canvasX, + canvasY, + this.pos[0] + this.size[0] - 15, + this.pos[1] + Math.max(this.size[1] - 15, outputs_offset), + 20, + 20 + ) + } + + /** + * Returns which resize corner the point is over, if any. + * @param canvasX X position in canvas coordinates + * @param canvasY Y position in canvas coordinates + * @returns The compass corner the point is in, otherwise `undefined`. + */ + findResizeDirection( + canvasX: number, + canvasY: number + ): CompassCorners | undefined { + if (this.resizable === false) return + + const { boundingRect } = this + if (!boundingRect.containsXy(canvasX, canvasY)) return + + // Check corners first (they take priority over edges) + return boundingRect.findContainingCorner( + canvasX, + canvasY, + LGraphNode.resizeHandleSize + ) + } + + /** + * returns all the info available about a property of this node. + * @param property name of the property + * @returns the object with all the available info + */ + getPropertyInfo(property: string) { + let info = null + + // there are several ways to define info about a property + // legacy mode + const { properties_info } = this + if (properties_info) { + for (const propInfo of properties_info) { + if (propInfo.name == property) { + info = propInfo + break + } + } + } + // litescene mode using the constructor + // @ts-expect-error deprecated https://github.com/Comfy-Org/litegraph.js/issues/639 + if (this.constructor[`@${property}`]) + // @ts-expect-error deprecated https://github.com/Comfy-Org/litegraph.js/issues/639 + info = this.constructor[`@${property}`] + + if (this.constructor.widgets_info?.[property]) + info = this.constructor.widgets_info[property] + + // litescene mode using the constructor + if (!info && this.onGetPropertyInfo) { + info = this.onGetPropertyInfo(property) + } + + info ||= {} + info.type ||= typeof this.properties[property] + if (info.widget == 'combo') info.type = 'enum' + + return info + } + + /** + * Defines a widget inside the node, it will be rendered on top of the node, you can control lots of properties + * @param type the widget type + * @param name the text to show on the widget + * @param value the default value + * @param callback function to call when it changes (optionally, it can be the name of the property to modify) + * @param options the object that contains special properties of this widget + * @returns the created widget object + */ + addWidget< + Type extends TWidgetType, + TValue extends WidgetTypeMap[Type]['value'] + >( + type: Type, + name: string, + value: TValue, + callback: IBaseWidget['callback'] | string | null, + options?: IWidgetOptions | string + ): WidgetTypeMap[Type] | IBaseWidget { + this.widgets ||= [] + + if (!options && callback && typeof callback === 'object') { + options = callback + callback = null + } + + // options can be the property name + options ||= {} + if (typeof options === 'string') options = { property: options } + + // callback can be the property name + if (callback && typeof callback === 'string') { + options.property = callback + callback = null + } + + const w: IBaseWidget & { type: Type } = { + // @ts-expect-error - Type casting for widget type property + type: type.toLowerCase(), + name: name, + value: value, + callback: typeof callback !== 'function' ? undefined : callback, + options, + y: 0 + } + + if (w.options.y !== undefined) { + w.y = w.options.y + } + + if (!callback && !w.options.callback && !w.options.property) { + console.warn( + 'LiteGraph addWidget(...) without a callback or property assigned' + ) + } + if (type == 'combo' && !w.options.values) { + throw "LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }" + } + + const widget = this.addCustomWidget(w) + this.expandToFitContent() + return widget + } + + addCustomWidget( + custom_widget: TPlainWidget + ): TPlainWidget | WidgetTypeMap[TPlainWidget['type']] { + this.widgets ||= [] + const widget = toConcreteWidget(custom_widget, this, false) ?? custom_widget + this.widgets.push(widget) + return widget + } + + addTitleButton(options: LGraphButtonOptions): LGraphButton { + this.title_buttons ||= [] + const button = new LGraphButton(options) + this.title_buttons.push(button) + return button + } + + onTitleButtonClick(button: LGraphButton, canvas: LGraphCanvas): void { + // Dispatch event for button click + canvas.dispatch('litegraph:node-title-button-clicked', { + node: this, + button: button + }) + } + + removeWidgetByName(name: string): void { + const widget = this.widgets?.find((x) => x.name === name) + if (widget) this.removeWidget(widget) + } + + removeWidget(widget: IBaseWidget): void { + if (!this.widgets) + throw new Error('removeWidget called on node without widgets') + + const widgetIndex = this.widgets.indexOf(widget) + if (widgetIndex === -1) throw new Error('Widget not found on this node') + + // Clean up slot references to prevent memory leaks + if (this.inputs) { + for (const input of this.inputs) { + if (input._widget === widget) { + input._widget = undefined + input.widget = undefined + } + } + } + + widget.onRemove?.() + this.widgets.splice(widgetIndex, 1) + } + + ensureWidgetRemoved(widget: IBaseWidget): void { + try { + this.removeWidget(widget) + } catch (error) { + console.error('Failed to remove widget', error) + } + } + + move(deltaX: number, deltaY: number): void { + if (this.pinned) return + + // If Vue nodes mode is enabled, skip LiteGraph's direct position update + // The layout store will handle the movement and sync back to LiteGraph + if (LiteGraph.vueNodesMode) { + // Vue nodes handle their own dragging through the layout store + // This prevents the snap-back issue from conflicting position updates + return + } + + this.pos[0] += deltaX + this.pos[1] += deltaY + } + + /** + * Internal method to measure the node for rendering. Prefer {@link boundingRect} where possible. + * + * Populates {@link out} with the results in graph space. + * Populates {@link _collapsed_width} with the collapsed width if the node is collapsed. + * Adjusts for title and collapsed status, but does not call {@link onBounding}. + * @param out `x, y, width, height` are written to this array. + * @param ctx The canvas context to use for measuring text. + */ + measure(out: Rect, ctx?: CanvasRenderingContext2D): void { + const titleMode = this.title_mode + const renderTitle = + titleMode != TitleMode.TRANSPARENT_TITLE && + titleMode != TitleMode.NO_TITLE + const titleHeight = renderTitle ? LiteGraph.NODE_TITLE_HEIGHT : 0 + + out[0] = this.pos[0] + out[1] = this.pos[1] + -titleHeight + if (!this.flags?.collapsed) { + out[2] = this.size[0] + out[3] = this.size[1] + titleHeight + } else { + if (ctx) ctx.font = this.innerFontStyle + this._collapsed_width = Math.min( + this.size[0], + ctx + ? ctx.measureText(this.getTitle() ?? '').width + + LiteGraph.NODE_TITLE_HEIGHT * 2 + : 0 + ) + out[2] = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH + out[3] = LiteGraph.NODE_TITLE_HEIGHT + } + } + + /** + * returns the bounding of the object, used for rendering purposes + * @param out {Rect?} [optional] a place to store the output, to free garbage + * @param includeExternal {boolean?} [optional] set to true to + * include the shadow and connection points in the bounding calculation + * @returns the bounding box in format of [topleft_cornerx, topleft_cornery, width, height] + */ + getBounding(out?: Rect, includeExternal?: boolean): Rect { + out ||= [0, 0, 0, 0] + + const rect = includeExternal ? this.renderArea : this.boundingRect + out[0] = rect[0] + out[1] = rect[1] + out[2] = rect[2] + out[3] = rect[3] + + return out + } + + /** + * Calculates the render area of this node, populating both {@link boundingRect} and {@link renderArea}. + * Called automatically at the start of every frame. + */ + updateArea(ctx?: CanvasRenderingContext2D): void { + const bounds = this.#boundingRect + this.measure(bounds, ctx) + this.onBounding?.(bounds) + + const renderArea = this.#renderArea + renderArea.set(bounds) + // 4 offset for collapsed node connection points + renderArea[0] -= 4 + renderArea[1] -= 4 + // Add shadow & left offset + renderArea[2] += 6 + 4 + // Add shadow & top offsets + renderArea[3] += 5 + 4 + } + + /** + * checks if a point is inside the shape of a node + */ + isPointInside(x: number, y: number): boolean { + return isInRect(x, y, this.boundingRect) + } + + /** + * Checks if the provided point is inside this node's collapse button area. + * @param x X co-ordinate to check + * @param y Y co-ordinate to check + * @returns true if the x,y point is in the collapse button area, otherwise false + */ + isPointInCollapse(x: number, y: number): boolean { + const squareLength = LiteGraph.NODE_TITLE_HEIGHT + return isInRectangle( + x, + y, + this.pos[0], + this.pos[1] - squareLength, + squareLength, + squareLength + ) + } + + /** + * Returns the input slot at the given position. Uses full 20 height, and approximates the label length. + * @param pos The graph co-ordinates to check + * @returns The input slot at the given position if found, otherwise `undefined`. + */ + getInputOnPos(pos: Point): INodeInputSlot | undefined { + return getNodeInputOnPos(this, pos[0], pos[1])?.input + } + + /** + * Returns the output slot at the given position. Uses full 20x20 box for the slot. + * @param pos The graph co-ordinates to check + * @returns The output slot at the given position if found, otherwise `undefined`. + */ + getOutputOnPos(pos: Point): INodeOutputSlot | undefined { + return getNodeOutputOnPos(this, pos[0], pos[1])?.output + } + + /** + * Returns the input or output slot at the given position. + * + * Tries {@link getNodeInputOnPos} first, then {@link getNodeOutputOnPos}. + * @param pos The graph co-ordinates to check + * @returns The input or output slot at the given position if found, otherwise `undefined`. + */ + getSlotOnPos(pos: Point): INodeInputSlot | INodeOutputSlot | undefined { + if (!isPointInRect(pos, this.boundingRect)) return + + return this.getInputOnPos(pos) ?? this.getOutputOnPos(pos) + } + + /** + * @deprecated Use {@link getSlotOnPos} instead. + * checks if a point is inside a node slot, and returns info about which slot + * @param x + * @param y + * @returns if found the object contains { input|output: slot object, slot: number, link_pos: [x,y] } + */ + getSlotInPosition(x: number, y: number): IFoundSlot | null { + // search for inputs + const { inputs, outputs } = this + + if (inputs) { + for (const [i, input] of inputs.entries()) { + const pos = this.getInputPos(i) + if (isInRectangle(x, y, pos[0] - 10, pos[1] - 10, 20, 20)) { + return { input, slot: i, link_pos: pos } + } + } + } + + if (outputs) { + for (const [i, output] of outputs.entries()) { + const pos = this.getOutputPos(i) + if (isInRectangle(x, y, pos[0] - 10, pos[1] - 10, 20, 20)) { + return { output, slot: i, link_pos: pos } + } + } + } + + return null + } + + /** + * Gets the widget on this node at the given co-ordinates. + * @param canvasX X co-ordinate in graph space + * @param canvasY Y co-ordinate in graph space + * @returns The widget found, otherwise `null` + */ + getWidgetOnPos( + canvasX: number, + canvasY: number, + includeDisabled = false + ): IBaseWidget | undefined { + const { widgets, pos, size } = this + if (!widgets?.length) return + + const x = canvasX - pos[0] + const y = canvasY - pos[1] + const nodeWidth = size[0] + + for (const widget of widgets) { + if ( + (widget.computedDisabled && !includeDisabled) || + !this.isWidgetVisible(widget) + ) { + continue + } + + const h = + widget.computedHeight ?? + widget.computeSize?.(nodeWidth)[1] ?? + LiteGraph.NODE_WIDGET_HEIGHT + + const maybeDOMWidget = widget as { margin?: number } + const mtop = maybeDOMWidget.margin ?? -2 + const mbot = maybeDOMWidget.margin ?? 2 + const mx = maybeDOMWidget.margin ?? 6 + + const w = widget.width || nodeWidth + if ( + widget.last_y !== undefined && + isInRectangle( + x, + y, + mx, + widget.last_y + mtop, + w - 2 * mx, + h - mtop - mbot + ) + ) { + return widget + } + } + } + + /** + * Returns the input slot with a given name (used for dynamic slots), -1 if not found + * @param name the name of the slot to find + * @param returnObj if the obj itself wanted + * @returns the slot (-1 if not found) + */ + findInputSlot( + name: string, + returnObj?: TReturn + ): number + findInputSlot( + name: string, + returnObj?: TReturn + ): INodeInputSlot + findInputSlot(name: string, returnObj: boolean = false) { + const { inputs } = this + if (!inputs) return -1 + + for (const [i, input] of inputs.entries()) { + if (name == input.name) { + return !returnObj ? i : input + } + } + return -1 + } + + /** + * returns the output slot with a given name (used for dynamic slots), -1 if not found + * @param name the name of the slot to find + * @param returnObj if the obj itself wanted + * @returns the slot (-1 if not found) + */ + findOutputSlot( + name: string, + returnObj?: TReturn + ): number + findOutputSlot( + name: string, + returnObj?: TReturn + ): INodeOutputSlot + findOutputSlot(name: string, returnObj: boolean = false) { + const { outputs } = this + if (!outputs) return -1 + + for (const [i, output] of outputs.entries()) { + if (name == output.name) { + return !returnObj ? i : output + } + } + return -1 + } + + /** + * Finds the first free input slot. + * @param optsIn + * @returns The index of the first matching slot, the slot itself if returnObj is true, or -1 if not found. + */ + findInputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): number + findInputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): INodeInputSlot | -1 + findInputSlotFree(optsIn?: FindFreeSlotOptions) { + return this.#findFreeSlot(this.inputs, optsIn) + } + + /** + * Finds the first free output slot. + * @param optsIn + * @returns The index of the first matching slot, the slot itself if returnObj is true, or -1 if not found. + */ + findOutputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): number + findOutputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): INodeOutputSlot | -1 + findOutputSlotFree(optsIn?: FindFreeSlotOptions) { + return this.#findFreeSlot(this.outputs, optsIn) + } + + /** + * Finds the next free slot + * @param slots The slots to search, i.e. this.inputs or this.outputs + */ + #findFreeSlot( + slots: TSlot[], + options?: FindFreeSlotOptions + ): TSlot | number { + const defaults = { + returnObj: false, + typesNotAccepted: [] + } + const opts = Object.assign(defaults, options || {}) + const length = slots?.length + if (!(length > 0)) return -1 + + for (let i = 0; i < length; ++i) { + const slot: TSlot & IGenericLinkOrLinks = slots[i] + if (!slot || slot.link || slot.links?.length) continue + if (opts.typesNotAccepted?.includes?.(slot.type)) continue + return !opts.returnObj ? i : slot + } + return -1 + } + + /** + * findSlotByType for INPUTS + */ + findInputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number + findInputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeInputSlot + findInputSlotByType( + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ) { + return this.#findSlotByType( + this.inputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + } + + /** + * findSlotByType for OUTPUTS + */ + findOutputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number + findOutputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeOutputSlot + findOutputSlotByType( + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ) { + return this.#findSlotByType( + this.outputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + } + + /** + * returns the output (or input) slot with a given type, -1 if not found + * @param input use inputs instead of outputs + * @param type the type of the slot to find + * @param returnObj if the obj itself wanted + * @param preferFreeSlot if we want a free slot (if not found, will return the first of the type anyway) + * @returns the slot (-1 if not found) + */ + findSlotByType( + input: TSlot, + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number + findSlotByType( + input: TSlot, + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeInputSlot | -1 + findSlotByType( + input: TSlot, + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeOutputSlot | -1 + findSlotByType( + input: boolean, + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number | INodeOutputSlot | INodeInputSlot { + return input + ? this.#findSlotByType( + this.inputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + : this.#findSlotByType( + this.outputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + } + + /** + * Finds a matching slot from those provided, returning the slot itself or its index in {@link slots}. + * @param slots Slots to search (this.inputs or this.outputs) + * @param type Type of slot to look for + * @param returnObj If true, returns the slot itself. Otherwise, the index. + * @param preferFreeSlot Prefer a free slot, but if none are found, fall back to an occupied slot. + * @param doNotUseOccupied Do not fall back to occupied slots. + * @see {findSlotByType} + * @see {findOutputSlotByType} + * @see {findInputSlotByType} + * @returns If a match is found, the slot if returnObj is true, otherwise the index. If no matches are found, -1 + */ + #findSlotByType( + slots: TSlot[], + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): TSlot | number { + const length = slots?.length + if (!length) return -1 + + // Empty string and * match anything (type: 0) + if (type == '' || type == '*') type = 0 + const sourceTypes = String(type).toLowerCase().split(',') + + // Run the search + let occupiedSlot: number | TSlot | null = null + for (let i = 0; i < length; ++i) { + const slot: TSlot & IGenericLinkOrLinks = slots[i] + const destTypes = + slot.type == '0' || slot.type == '*' + ? ['0'] + : String(slot.type).toLowerCase().split(',') + + for (const sourceType of sourceTypes) { + // TODO: Remove _event_ entirely. + const source = sourceType == '_event_' ? LiteGraph.EVENT : sourceType + + for (const destType of destTypes) { + const dest = destType == '_event_' ? LiteGraph.EVENT : destType + + if (source == dest || source === '*' || dest === '*') { + if (preferFreeSlot && (slot.links?.length || slot.link != null)) { + // In case we can't find a free slot. + occupiedSlot ??= returnObj ? slot : i + continue + } + return returnObj ? slot : i + } + } + } + } + + return doNotUseOccupied ? -1 : (occupiedSlot ?? -1) + } + + /** + * Determines the slot index to connect to when attempting to connect by type. + * @param findInputs If true, searches for an input. Otherwise, an output. + * @param node The node at the other end of the connection. + * @param slotType The type of slot at the other end of the connection. + * @param options Search restrictions to adhere to. + * @see {connectByType} + * @see {connectByTypeOutput} + */ + findConnectByTypeSlot( + findInputs: boolean, + node: LGraphNode, + slotType: ISlotType, + options?: ConnectByTypeOptions + ): number | undefined { + // LEGACY: Old options names + if (options && typeof options === 'object') { + if ('firstFreeIfInputGeneralInCase' in options) + options.wildcardToTyped = !!options.firstFreeIfInputGeneralInCase + if ('firstFreeIfOutputGeneralInCase' in options) + options.wildcardToTyped = !!options.firstFreeIfOutputGeneralInCase + if ('generalTypeInCase' in options) + options.typedToWildcard = !!options.generalTypeInCase + } + const optsDef: ConnectByTypeOptions = { + createEventInCase: true, + wildcardToTyped: true, + typedToWildcard: true + } + const opts = Object.assign(optsDef, options) + + if (!this.graph) throw new NullGraphError() + + if (node && typeof node === 'number') { + const nodeById = this.graph.getNodeById(node) + if (!nodeById) return + + node = nodeById + } + const slot = node.findSlotByType(findInputs, slotType, false, true) + if (slot >= 0 && slot !== null) return slot + + // TODO: Remove or reimpl. events. WILL CREATE THE onTrigger IN SLOT + if (opts.createEventInCase && slotType == LiteGraph.EVENT) { + if (findInputs) return -1 + if (LiteGraph.do_add_triggers_slots) return node.addOnExecutedOutput() + } + + // connect to the first general output slot if not found a specific type and + if (opts.typedToWildcard) { + const generalSlot = node.findSlotByType(findInputs, 0, false, true, true) + if (generalSlot >= 0) return generalSlot + } + // connect to the first free input slot if not found a specific type and this output is general + if ( + opts.wildcardToTyped && + (slotType == 0 || slotType == '*' || slotType == '') + ) { + const opt = { typesNotAccepted: [LiteGraph.EVENT] } + const nonEventSlot = findInputs + ? node.findInputSlotFree(opt) + : node.findOutputSlotFree(opt) + if (nonEventSlot >= 0) return nonEventSlot + } + } + + /** + * Finds the first free output slot with any of the comma-delimited types in {@link type}. + * + * If no slots are free, falls back in order to: + * - The first free wildcard slot + * - The first occupied slot + * - The first occupied wildcard slot + * @param type The {@link ISlotType type} of slot to find + * @returns The index and slot if found, otherwise `undefined`. + */ + findOutputByType( + type: ISlotType + ): { index: number; slot: INodeOutputSlot } | undefined { + return findFreeSlotOfType( + this.outputs, + type, + (output) => !output.links?.length + ) + } + + /** + * Finds the first free input slot with any of the comma-delimited types in {@link type}. + * + * If no slots are free, falls back in order to: + * - The first free wildcard slot + * - The first occupied slot + * - The first occupied wildcard slot + * @param type The {@link ISlotType type} of slot to find + * @returns The index and slot if found, otherwise `undefined`. + */ + findInputByType( + type: ISlotType + ): { index: number; slot: INodeInputSlot } | undefined { + return findFreeSlotOfType( + this.inputs, + type, + (input) => + input.link == null || !!this.graph?.getLink(input.link)?._dragging + ) + } + + /** + * connect this node output to the input of another node BY TYPE + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param target_node the target node + * @param target_slotType the input slot type of the target node + * @returns the link_info is created, otherwise null + */ + connectByType( + slot: number | string, + target_node: LGraphNode, + target_slotType: ISlotType, + optsIn?: ConnectByTypeOptions + ): LLink | null { + const slotIndex = this.findConnectByTypeSlot( + true, + target_node, + target_slotType, + optsIn + ) + if (slotIndex !== undefined) + return this.connect(slot, target_node, slotIndex, optsIn?.afterRerouteId) + + // No compatible slot found - connection not possible + return null + } + + /** + * connect this node input to the output of another node BY TYPE + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param source_node the target node + * @param source_slotType the output slot type of the target node + * @returns the link_info is created, otherwise null + */ + connectByTypeOutput( + slot: number | string, + source_node: LGraphNode, + source_slotType: ISlotType, + optsIn?: ConnectByTypeOptions + ): LLink | null { + // LEGACY: Old options names + if (typeof optsIn === 'object') { + if ('firstFreeIfInputGeneralInCase' in optsIn) + optsIn.wildcardToTyped = !!optsIn.firstFreeIfInputGeneralInCase + if ('generalTypeInCase' in optsIn) + optsIn.typedToWildcard = !!optsIn.generalTypeInCase + } + const slotIndex = this.findConnectByTypeSlot( + false, + source_node, + source_slotType, + optsIn + ) + if (slotIndex !== undefined) + return source_node.connect(slotIndex, this, slot, optsIn?.afterRerouteId) + + console.error( + '[connectByType]: no way to connect type:', + source_slotType, + 'to node:', + source_node + ) + return null + } + + canConnectTo( + node: NodeLike, + toSlot: INodeInputSlot | SubgraphIO, + fromSlot: INodeOutputSlot | SubgraphIO + ) { + return ( + this.id !== node.id && + LiteGraph.isValidConnection(fromSlot.type, toSlot.type) + ) + } + + /** + * Connect an output of this node to an input of another node + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param target_node the target node + * @param target_slot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger) + * @returns the link_info is created, otherwise null + */ + connect( + slot: number | string, + target_node: LGraphNode, + target_slot: ISlotType, + afterRerouteId?: RerouteId + ): LLink | null { + // Allow legacy API support for searching target_slot by string, without mutating the input variables + let targetIndex: number | null + + const { graph, outputs } = this + if (!graph) { + // could be connected before adding it to a graph + // due to link ids being associated with graphs + console.error( + "Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them." + ) + return null + } + + // seek for the output slot + if (typeof slot === 'string') { + slot = this.findOutputSlot(slot) + if (slot == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${slot}`) + return null + } + } else if (!outputs || slot >= outputs.length) { + if (LiteGraph.debug) + console.error('Connect: Error, slot number not found') + return null + } + + if (target_node && typeof target_node === 'number') { + const nodeById = graph.getNodeById(target_node) + if (!nodeById) throw 'target node is null' + + target_node = nodeById + } + if (!target_node) throw 'target node is null' + + // avoid loopback + if (target_node == this) return null + + // you can specify the slot by name + if (typeof target_slot === 'string') { + targetIndex = target_node.findInputSlot(target_slot) + if (targetIndex == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${targetIndex}`) + return null + } + } else if (target_slot === LiteGraph.EVENT) { + // TODO: Events + if (LiteGraph.do_add_triggers_slots) { + target_node.changeMode(LGraphEventMode.ON_TRIGGER) + targetIndex = target_node.findInputSlot('onTrigger') + } else { + return null + } + } else if (typeof target_slot === 'number') { + targetIndex = target_slot + } else { + targetIndex = 0 + } + + // Allow target node to change slot + if (target_node.onBeforeConnectInput) { + // This way node can choose another slot (or make a new one?) + const requestedIndex = target_node.onBeforeConnectInput( + targetIndex, + target_slot + ) + targetIndex = typeof requestedIndex === 'number' ? requestedIndex : null + } + + if ( + targetIndex === null || + !target_node.inputs || + targetIndex >= target_node.inputs.length + ) { + if (LiteGraph.debug) + console.error('Connect: Error, slot number not found') + return null + } + + const input = target_node.inputs[targetIndex] + const output = outputs[slot] + + if (!output) return null + + if (output.links?.length) { + if ( + output.type === LiteGraph.EVENT && + !LiteGraph.allow_multi_output_for_events + ) { + graph.beforeChange() + this.disconnectOutput(slot) + } + } + + const link = this.connectSlots(output, target_node, input, afterRerouteId) + return link ?? null + } + + /** + * Connect two slots between two nodes + * @param output The output slot to connect + * @param inputNode The node that the input slot is on + * @param input The input slot to connect + * @param afterRerouteId The reroute ID to use for the link + * @returns The link that was created, or null if the connection was blocked + */ + connectSlots( + output: INodeOutputSlot, + inputNode: LGraphNode, + input: INodeInputSlot, + afterRerouteId: RerouteId | undefined + ): LLink | null | undefined { + const { graph } = this + if (!graph) throw new NullGraphError() + + const layoutMutations = useLayoutMutations() + + const outputIndex = this.outputs.indexOf(output) + if (outputIndex === -1) { + console.warn('connectSlots: output not found') + return + } + const inputIndex = inputNode.inputs.indexOf(input) + if (inputIndex === -1) { + console.warn('connectSlots: input not found') + return + } + + // check targetSlot and check connection types + if (!LiteGraph.isValidConnection(output.type, input.type)) { + this.setDirtyCanvas(false, true) + return null + } + + // Allow nodes to block connection + if ( + inputNode.onConnectInput?.( + inputIndex, + output.type, + output, + this, + outputIndex + ) === false + ) + return null + if ( + this.onConnectOutput?.( + outputIndex, + input.type, + input, + inputNode, + inputIndex + ) === false + ) + return null + + // if there is something already plugged there, disconnect + if (inputNode.inputs[inputIndex]?.link != null) { + graph.beforeChange() + inputNode.disconnectInput(inputIndex, true) + } + + const maybeCommonType = + input.type && output.type && commonType(input.type, output.type) + + const link = new LLink( + ++graph.state.lastLinkId, + maybeCommonType || input.type || output.type, + this.id, + outputIndex, + inputNode.id, + inputIndex, + afterRerouteId + ) + + // add to graph links list + graph._links.set(link.id, link) + + // Register link in Layout Store for spatial tracking + layoutMutations.setSource(LayoutSource.Canvas) + layoutMutations.createLink( + link.id, + this.id, + outputIndex, + inputNode.id, + inputIndex + ) + + // connect in output + output.links ??= [] + output.links.push(link.id) + // connect in input + const targetInput = inputNode.inputs[inputIndex] + targetInput.link = link.id + if (targetInput.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: inputNode.id, + slotType: NodeSlotType.INPUT, + slotIndex: inputIndex, + connected: true, + linkId: link.id + }) + } + + // Reroutes + const reroutes = LLink.getReroutes(graph, link) + for (const reroute of reroutes) { + reroute.linkIds.add(link.id) + if (reroute.floating) reroute.floating = undefined + reroute._dragging = undefined + } + + // If this is the terminus of a floating link, remove it + const lastReroute = reroutes.at(-1) + if (lastReroute) { + for (const linkId of lastReroute.floatingLinkIds) { + const link = graph.floatingLinks.get(linkId) + if (link?.parentId === lastReroute.id) { + graph.removeFloatingLink(link) + } + } + } + graph._version++ + + // link has been created now, so its updated + this.onConnectionsChange?.( + NodeSlotType.OUTPUT, + outputIndex, + true, + link, + output + ) + + inputNode.onConnectionsChange?.( + NodeSlotType.INPUT, + inputIndex, + true, + link, + input + ) + + this.setDirtyCanvas(false, true) + graph.afterChange() + + return link + } + + connectFloatingReroute( + pos: Point, + slot: INodeInputSlot | INodeOutputSlot, + afterRerouteId?: RerouteId + ): Reroute { + const { graph, id } = this + if (!graph) throw new NullGraphError() + + // Assertion: It's either there or it isn't. + const inputIndex = this.inputs.indexOf(slot as INodeInputSlot) + const outputIndex = this.outputs.indexOf(slot as INodeOutputSlot) + if (inputIndex === -1 && outputIndex === -1) throw new Error('Invalid slot') + + const slotType = outputIndex === -1 ? 'input' : 'output' + + const reroute = graph.setReroute({ + pos, + parentId: afterRerouteId, + linkIds: [], + floating: { slotType } + }) + + const parentReroute = graph.getReroute(afterRerouteId) + const fromLastFloatingReroute = + parentReroute?.floating?.slotType === 'output' + + // Adding from an output, or a floating reroute that is NOT the tip of an existing floating chain + if (afterRerouteId == null || !fromLastFloatingReroute) { + const link = new LLink( + -1, + slot.type, + outputIndex === -1 ? -1 : id, + outputIndex, + inputIndex === -1 ? -1 : id, + inputIndex + ) + link.parentId = reroute.id + graph.addFloatingLink(link) + return reroute + } + + // Adding a new floating reroute from the tip of a floating chain. + if (!parentReroute) + throw new Error('[connectFloatingReroute] Parent reroute not found') + + const link = parentReroute.getFloatingLinks('output')?.[0] + if (!link) + throw new Error('[connectFloatingReroute] Floating link not found') + + reroute.floatingLinkIds.add(link.id) + link.parentId = reroute.id + parentReroute.floating = undefined + return reroute + } + + /** + * disconnect one output to an specific node + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param target_node the target node to which this slot is connected [Optional, + * if not target_node is specified all nodes will be disconnected] + * @returns if it was disconnected successfully + */ + disconnectOutput(slot: string | number, target_node?: LGraphNode): boolean { + if (typeof slot === 'string') { + slot = this.findOutputSlot(slot) + if (slot == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${slot}`) + return false + } + } else if (!this.outputs || slot >= this.outputs.length) { + if (LiteGraph.debug) + console.error('Connect: Error, slot number not found') + return false + } + + // get output slot + const output = this.outputs[slot] + if (!output) return false + + if (output._floatingLinks) { + for (const link of output._floatingLinks) { + if (link.hasOrigin(this.id, slot)) { + this.graph?.removeFloatingLink(link) + } + } + } + + if (!output.links || output.links.length == 0) return false + const { links } = output + + // one of the output links in this slot + const graph = this.graph + if (!graph) throw new NullGraphError() + + if (target_node) { + const target = + typeof target_node === 'number' + ? graph.getNodeById(target_node) + : target_node + if (!target) throw 'Target Node not found' + + for (const [i, link_id] of links.entries()) { + const link_info = graph._links.get(link_id) + if (link_info?.target_id != target.id) continue + + // is the link we are searching for... + // remove here + links.splice(i, 1) + const input = target.inputs[link_info.target_slot] + // remove there + input.link = null + if (input.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: target.id, + slotType: NodeSlotType.INPUT, + slotIndex: link_info.target_slot, + connected: false, + linkId: link_info.id + }) + } + + // remove the link from the links pool + link_info.disconnect(graph, 'input') + graph._version++ + + // link_info hasn't been modified so its ok + target.onConnectionsChange?.( + NodeSlotType.INPUT, + link_info.target_slot, + false, + link_info, + input + ) + this.onConnectionsChange?.( + NodeSlotType.OUTPUT, + slot, + false, + link_info, + output + ) + + break + } + } else { + // all the links in this output slot + for (const link_id of links) { + const link_info = graph._links.get(link_id) + if (!link_info) continue + if ( + link_info.target_id === SUBGRAPH_OUTPUT_ID && + graph instanceof Subgraph + ) { + const targetSlot = graph.outputNode.slots[link_info.target_slot] + if (targetSlot) { + targetSlot.linkIds.length = 0 + } else { + console.error('Missing subgraphOutput slot when disconnecting link') + } + } + + const target = graph.getNodeById(link_info.target_id) + graph._version++ + + if (target) { + const input = target.inputs[link_info.target_slot] + // remove other side link + input.link = null + if (input.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: target.id, + slotType: NodeSlotType.INPUT, + slotIndex: link_info.target_slot, + connected: false, + linkId: link_info.id + }) + } + + // link_info hasn't been modified so its ok + target.onConnectionsChange?.( + NodeSlotType.INPUT, + link_info.target_slot, + false, + link_info, + input + ) + } + // remove the link from the links pool + link_info.disconnect(graph, 'input') + + this.onConnectionsChange?.( + NodeSlotType.OUTPUT, + slot, + false, + link_info, + output + ) + } + output.links = null + } + + this.setDirtyCanvas(false, true) + return true + } + + /** + * Disconnect one input + * @param slot Input slot index, or the name of the slot + * @param keepReroutes If `true`, reroutes will not be garbage collected. + * @returns true if disconnected successfully or already disconnected, otherwise false + */ + disconnectInput(slot: number | string, keepReroutes?: boolean): boolean { + // Allow search by string + if (typeof slot === 'string') { + slot = this.findInputSlot(slot) + if (slot == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${slot}`) + return false + } + } else if (!this.inputs || slot >= this.inputs.length) { + if (LiteGraph.debug) { + console.error('Connect: Error, slot number not found') + } + return false + } + + const input = this.inputs[slot] + if (!input) { + console.error('disconnectInput: input not found', slot, this.inputs) + return false + } + + const { graph } = this + if (!graph) throw new NullGraphError() + + // Break floating links + if (input._floatingLinks?.size) { + for (const link of input._floatingLinks) { + graph.removeFloatingLink(link) + } + } + + const link_id = this.inputs[slot].link + if (link_id != null) { + this.inputs[slot].link = null + if (input.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: this.id, + slotType: NodeSlotType.INPUT, + slotIndex: slot, + connected: false, + linkId: link_id + }) + } + + // remove other side + const link_info = graph._links.get(link_id) + if (link_info) { + // Let SubgraphInput do the disconnect. + if (link_info.origin_id === -10 && 'inputNode' in graph) { + graph.inputNode._disconnectNodeInput(this, input, link_info) + return true + } + + const target_node = graph.getNodeById(link_info.origin_id) + if (!target_node) { + console.error( + 'disconnectInput: output not found', + link_info.origin_slot + ) + return false + } + + const output = target_node.outputs[link_info.origin_slot] + if (!output?.links?.length) { + // Output not found - may have been removed + return false + } + + // search in the inputs list for this link + let i = 0 + for (const l = output.links.length; i < l; i++) { + if (output.links[i] == link_id) { + output.links.splice(i, 1) + break + } + } + + link_info.disconnect(graph, keepReroutes ? 'output' : undefined) + if (graph) graph._version++ + + this.onConnectionsChange?.( + NodeSlotType.INPUT, + slot, + false, + link_info, + input + ) + target_node.onConnectionsChange?.( + NodeSlotType.OUTPUT, + i, + false, + link_info, + output + ) + } + } + + this.setDirtyCanvas(false, true) + return true + } + + /** + * @deprecated Use {@link getInputPos} or {@link getOutputPos} instead. + * returns the center of a connection point in canvas coords + * @param is_input true if if a input slot, false if it is an output + * @param slot_number (could be the number of the slot or the string with the name of the slot) + * @param out [optional] a place to store the output, to free garbage + * @returns the position + */ + getConnectionPos(is_input: boolean, slot_number: number, out?: Point): Point { + out ||= [0, 0] + + const { + pos: [nodeX, nodeY], + inputs, + outputs + } = this + + if (this.flags.collapsed) { + const w = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH + out[0] = is_input ? nodeX : nodeX + w + out[1] = nodeY - LiteGraph.NODE_TITLE_HEIGHT * 0.5 + return out + } + + // weird feature that never got finished + if (is_input && slot_number == -1) { + out[0] = nodeX + LiteGraph.NODE_TITLE_HEIGHT * 0.5 + out[1] = nodeY + LiteGraph.NODE_TITLE_HEIGHT * 0.5 + return out + } + + // hard-coded pos + const inputPos = inputs?.[slot_number]?.pos + const outputPos = outputs?.[slot_number]?.pos + + if (is_input && inputPos) { + out[0] = nodeX + inputPos[0] + out[1] = nodeY + inputPos[1] + return out + } else if (!is_input && outputPos) { + out[0] = nodeX + outputPos[0] + out[1] = nodeY + outputPos[1] + return out + } + + // default vertical slots + const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5 + const slotIndex = is_input + ? this.#defaultVerticalInputs.indexOf(this.inputs[slot_number]) + : this.#defaultVerticalOutputs.indexOf(this.outputs[slot_number]) + + out[0] = is_input ? nodeX + offset : nodeX + this.size[0] + 1 - offset + out[1] = + nodeY + + (slotIndex + 0.7) * LiteGraph.NODE_SLOT_HEIGHT + + (this.constructor.slot_start_y || 0) + return out + } + + /** + * @internal The inputs that are not positioned with absolute coordinates. + */ + get #defaultVerticalInputs() { + return this.inputs.filter( + (slot) => !slot.pos && !(this.widgets?.length && isWidgetInputSlot(slot)) + ) + } + + /** + * @internal The outputs that are not positioned with absolute coordinates. + */ + get #defaultVerticalOutputs() { + return this.outputs.filter((slot: INodeOutputSlot) => !slot.pos) + } + + /** + * Get the context needed for slot position calculations + * @internal + */ + #getSlotPositionContext(): SlotPositionContext { + return { + nodeX: this.pos[0], + nodeY: this.pos[1], + nodeWidth: this.size[0], + nodeHeight: this.size[1], + collapsed: this.flags.collapsed ?? false, + collapsedWidth: this._collapsed_width, + slotStartY: this.constructor.slot_start_y, + inputs: this.inputs, + outputs: this.outputs, + widgets: this.widgets + } + } + + /** + * Gets the position of an input slot, in graph co-ordinates. + * + * This method is preferred over the legacy {@link getConnectionPos} method. + * @param slot Input slot index + * @returns Position of the input slot + */ + getInputPos(slot: number): Point { + return calculateInputSlotPos(this.#getSlotPositionContext(), slot) + } + + /** + * Gets the position of an input slot, in graph co-ordinates. + * @param input The actual node input object + * @returns Position of the centre of the input slot in graph co-ordinates. + */ + getInputSlotPos(input: INodeInputSlot): Point { + return calculateInputSlotPosFromSlot(this.#getSlotPositionContext(), input) + } + + /** + * Gets the position of an output slot, in graph co-ordinates. + * + * This method is preferred over the legacy {@link getConnectionPos} method. + * @param outputSlotIndex Output slot index + * @returns Position of the output slot + */ + getOutputPos(outputSlotIndex: number): Point { + return calculateOutputSlotPos( + this.#getSlotPositionContext(), + outputSlotIndex + ) + } + + /** + * Get slot position using layout tree if available, fallback to node's position * Unified implementation used by both LitegraphLinkAdapter and useLinkLayoutSync + * @param slotIndex The slot index + * @param isInput Whether this is an input slot + * @returns Position of the slot center in graph coordinates + */ + getSlotPosition(slotIndex: number, isInput: boolean): Point { + return getSlotPosition(this, slotIndex, isInput) + } + + /** @inheritdoc */ + snapToGrid(snapTo: number): boolean { + return this.pinned ? false : snapPoint(this.pos, snapTo) + } + + /** @see {@link snapToGrid} */ + alignToGrid(): void { + this.snapToGrid(LiteGraph.CANVAS_GRID_SIZE) + } + + /* Console output */ + trace(msg: string): void { + this.console ||= [] + this.console.push(msg) + // @ts-expect-error deprecated + if (this.console.length > LGraphNode.MAX_CONSOLE) this.console.shift() + } + + /* Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */ + setDirtyCanvas(dirty_foreground: boolean, dirty_background?: boolean): void { + this.graph?.canvasAction((c) => + c.setDirty(dirty_foreground, dirty_background) + ) + } + + loadImage(url: string): HTMLImageElement { + interface AsyncImageElement extends HTMLImageElement { + ready?: boolean + } + + const img: AsyncImageElement = new Image() + img.src = LiteGraph.node_images_path + url + img.ready = false + + const dirty = () => this.setDirtyCanvas(true) + img.addEventListener('load', function (this: AsyncImageElement) { + this.ready = true + dirty() + }) + return img + } + + /** + * Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus + * @deprecated Use {@link LGraphCanvas.pointer} instead. + */ + captureInput(v: boolean): void { + warnDeprecated( + '[DEPRECATED] captureInput will be removed in a future version. Please use LGraphCanvas.pointer (CanvasPointer) instead.' + ) + if (!this.graph || !this.graph.list_of_graphcanvas) return + + const list = this.graph.list_of_graphcanvas + + for (const c of list) { + // releasing somebody elses capture?! + if (!v && c.node_capturing_input != this) continue + + // change + c.node_capturing_input = v ? this : null + } + } + + get collapsed() { + return !!this.flags.collapsed + } + + get collapsible() { + return !this.pinned && this.constructor.collapsable !== false + } + + /** + * Toggle node collapse (makes it smaller on the canvas) + */ + collapse(force?: boolean): void { + if (!this.collapsible && !force) return + if (!this.graph) throw new NullGraphError() + this.graph._version++ + this.flags.collapsed = !this.flags.collapsed + this.setDirtyCanvas(true, true) + } + + /** + * Toggles advanced mode of the node, showing advanced widgets + */ + toggleAdvanced() { + if (!this.widgets?.some((w) => w.advanced)) return + if (!this.graph) throw new NullGraphError() + this.graph._version++ + this.showAdvanced = !this.showAdvanced + this.expandToFitContent() + this.setDirtyCanvas(true, true) + } + + get pinned() { + return !!this.flags.pinned + } + + /** + * Prevents the node being accidentally moved or resized by mouse interaction. + * Toggles pinned state if no value is provided. + */ + pin(v?: boolean): void { + if (!this.graph) throw new NullGraphError() + + this.graph._version++ + this.flags.pinned = v ?? !this.flags.pinned + this.resizable = !this.pinned + if (!this.pinned) this.flags.pinned = undefined + } + + unpin(): void { + this.pin(false) + } + + localToScreen(x: number, y: number, dragAndScale: DragAndScale): Point { + return [ + (x + this.pos[0]) * dragAndScale.scale + dragAndScale.offset[0], + (y + this.pos[1]) * dragAndScale.scale + dragAndScale.offset[1] + ] + } + + get width() { + return this.collapsed + ? this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH + : this.size[0] + } + + /** + * Returns the height of the node, including the title bar. + */ + get height() { + return LiteGraph.NODE_TITLE_HEIGHT + this.bodyHeight + } + + /** + * Returns the height of the node, excluding the title bar. + */ + get bodyHeight() { + return this.collapsed ? 0 : this.size[1] + } + + drawBadges(ctx: CanvasRenderingContext2D, { gap = 2 } = {}): void { + const badgeInstances = this.badges.map((badge) => + badge instanceof LGraphBadge ? badge : badge() + ) + const isLeftAligned = this.badgePosition === BadgePosition.TopLeft + + let currentX = isLeftAligned + ? 0 + : this.width - + badgeInstances.reduce( + (acc, badge) => acc + badge.getWidth(ctx) + gap, + 0 + ) + const y = -(LiteGraph.NODE_TITLE_HEIGHT + gap) + + for (const badge of badgeInstances) { + badge.draw(ctx, currentX, y - badge.height) + currentX += badge.getWidth(ctx) + gap + } + } + + /** + * Renders the node's title bar background + */ + drawTitleBarBackground( + ctx: CanvasRenderingContext2D, + { + scale, + title_height = LiteGraph.NODE_TITLE_HEIGHT, + low_quality = false + }: DrawTitleOptions + ): void { + const fgcolor = this.renderingColor + const shape = this.renderingShape + const size = this.renderingSize + + if (this.onDrawTitleBar) { + this.onDrawTitleBar(ctx, title_height, size, scale, fgcolor) + return + } + + if (this.title_mode === TitleMode.TRANSPARENT_TITLE) { + return + } + + if (this.collapsed) { + ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR + } + + ctx.fillStyle = this.constructor.title_color || fgcolor + ctx.beginPath() + + if (shape == RenderShape.BOX || low_quality) { + ctx.rect(0, -title_height, size[0], title_height) + } else if (shape == RenderShape.ROUND || shape == RenderShape.CARD) { + ctx.roundRect( + 0, + -title_height, + size[0], + title_height, + this.collapsed + ? [LiteGraph.ROUND_RADIUS] + : [LiteGraph.ROUND_RADIUS, LiteGraph.ROUND_RADIUS, 0, 0] + ) + } + ctx.fill() + ctx.shadowColor = 'transparent' + } + + /** + * Renders the node's title box, i.e. the dot in front of the title text that + * when clicked toggles the node's collapsed state. The term `title box` comes + * from the original LiteGraph implementation. + */ + drawTitleBox( + ctx: CanvasRenderingContext2D, + { + scale, + low_quality = false, + title_height = LiteGraph.NODE_TITLE_HEIGHT, + box_size = 10 + }: DrawTitleBoxOptions + ): void { + const size = this.renderingSize + const shape = this.renderingShape + + if (this.onDrawTitleBox) { + this.onDrawTitleBox(ctx, title_height, size, scale) + return + } + + if ( + [RenderShape.ROUND, RenderShape.CIRCLE, RenderShape.CARD].includes(shape) + ) { + if (low_quality) { + ctx.fillStyle = 'black' + ctx.beginPath() + ctx.arc( + title_height * 0.5, + title_height * -0.5, + box_size * 0.5 + 1, + 0, + Math.PI * 2 + ) + ctx.fill() + } + + ctx.fillStyle = this.renderingBoxColor + if (low_quality) { + ctx.fillRect( + title_height * 0.5 - box_size * 0.5, + title_height * -0.5 - box_size * 0.5, + box_size, + box_size + ) + } else { + ctx.beginPath() + ctx.arc( + title_height * 0.5, + title_height * -0.5, + box_size * 0.5, + 0, + Math.PI * 2 + ) + ctx.fill() + } + } else { + if (low_quality) { + ctx.fillStyle = 'black' + ctx.fillRect( + (title_height - box_size) * 0.5 - 1, + (title_height + box_size) * -0.5 - 1, + box_size + 2, + box_size + 2 + ) + } + ctx.fillStyle = this.renderingBoxColor + ctx.fillRect( + (title_height - box_size) * 0.5, + (title_height + box_size) * -0.5, + box_size, + box_size + ) + } + } + + /** + * Renders the node's title text. + */ + drawTitleText( + ctx: CanvasRenderingContext2D, + { + scale, + default_title_color, + low_quality = false, + title_height = LiteGraph.NODE_TITLE_HEIGHT + }: DrawTitleTextOptions + ): void { + const size = this.renderingSize + const selected = this.selected + + if (this.onDrawTitleText) { + this.onDrawTitleText( + ctx, + title_height, + size, + scale, + this.titleFontStyle, + selected + ) + return + } + + // Don't render title text if low quality + if (low_quality) { + return + } + + ctx.font = this.titleFontStyle + const rawTitle = this.getTitle() ?? `❌ ${this.type}` + const title = String(rawTitle) + (this.pinned ? '📌' : '') + if (title) { + if (selected) { + ctx.fillStyle = LiteGraph.NODE_SELECTED_TITLE_COLOR + } else { + ctx.fillStyle = this.constructor.title_text_color || default_title_color + } + + // Calculate available width for title + let availableWidth = size[0] - title_height * 2 // Basic margins + + // Subtract space for title buttons + if (this.title_buttons?.length > 0) { + let buttonsWidth = 0 + const savedFont = ctx.font // Save current font + for (const button of this.title_buttons) { + if (button.visible) { + buttonsWidth += button.getWidth(ctx) + 2 // button width + gap + } + } + ctx.font = savedFont // Restore font after button measurements + if (buttonsWidth > 0) { + buttonsWidth -= 20 // Reduce by empty padding + availableWidth -= buttonsWidth + } + } + + // Truncate title if needed + let displayTitle = title + + if (this.collapsed) { + // For collapsed nodes, limit to 20 chars as before + displayTitle = title.substr(0, 20) + } else if (availableWidth > 0) { + // For regular nodes, truncate based on available width + displayTitle = truncateText(ctx, title, availableWidth) + } + + ctx.textAlign = 'left' + ctx.fillText( + displayTitle, + title_height, + LiteGraph.NODE_TITLE_TEXT_Y - title_height + ) + } + } + + /** + * Attempts to gracefully bypass this node in all of its connections by reconnecting all links. + * + * Each input is checked against each output. This is done on a matching index basis, i.e. input 3 -> output 3. + * If there are any input links remaining, + * and {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `true`, + * each input will check for outputs that match, and take the first one that matches + * `true`: Try the index matching first, then every input to every output. + * `false`: Only matches indexes, e.g. input 3 to output 3. + * + * If {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `undefined`, it will fall back to + * the static {@link keepAllLinksOnBypass}. + * @returns `true` if any new links were established, otherwise `false`. + * @todo Decision: Change API to return array of new links instead? + */ + connectInputToOutput(): boolean | undefined { + const { inputs, outputs, graph } = this + if (!inputs || !outputs) return + if (!graph) throw new NullGraphError() + + const { _links } = graph + let madeAnyConnections = false + + // First pass: only match exactly index-to-index + for (const [index, input] of inputs.entries()) { + if (input.link == null) continue + + const output = outputs[index] + if (!output || !LiteGraph.isValidConnection(input.type, output.type)) + continue + + const inLink = _links.get(input.link) + if (!inLink) continue + const inNode = graph.getNodeById(inLink?.origin_id) + if (!inNode) continue + + bypassAllLinks(output, inNode, inLink, graph) + } + // Configured to only use index-to-index matching + if (!(this.flags.keepAllLinksOnBypass ?? LGraphNode.keepAllLinksOnBypass)) + return madeAnyConnections + + // Second pass: match any remaining links + for (const input of inputs) { + if (input.link == null) continue + + const inLink = _links.get(input.link) + if (!inLink) continue + const inNode = graph.getNodeById(inLink?.origin_id) + if (!inNode) continue + + for (const output of outputs) { + if (!LiteGraph.isValidConnection(input.type, output.type)) continue + + bypassAllLinks(output, inNode, inLink, graph) + break + } + } + return madeAnyConnections + + function bypassAllLinks( + output: INodeOutputSlot, + inNode: LGraphNode, + inLink: LLink, + graph: LGraph + ) { + const outLinks = output.links + ?.map((x) => _links.get(x)) + .filter((x) => !!x) + if (!outLinks?.length) return + + for (const outLink of outLinks) { + const outNode = graph.getNodeById(outLink.target_id) + if (!outNode) continue + + const result = inNode.connect( + inLink.origin_slot, + outNode, + outLink.target_slot, + inLink.parentId + ) + madeAnyConnections ||= !!result + } + } + } + + /** + * Returns `true` if the widget is visible, otherwise `false`. + */ + isWidgetVisible(widget: IBaseWidget): boolean { + const isHidden = + this.collapsed || widget.hidden || (widget.advanced && !this.showAdvanced) + return !isHidden + } + + updateComputedDisabled() { + if (!this.widgets) return + for (const widget of this.widgets) + widget.computedDisabled = + widget.disabled || this.getSlotFromWidget(widget)?.link != null + } + + drawWidgets( + ctx: CanvasRenderingContext2D, + { lowQuality = false, editorAlpha = 1 }: DrawWidgetsOptions + ): void { + if (!this.widgets) return + + const nodeWidth = this.size[0] + const { widgets } = this + const H = LiteGraph.NODE_WIDGET_HEIGHT + const showText = !lowQuality + ctx.save() + ctx.globalAlpha = editorAlpha + + this.updateComputedDisabled() + for (const widget of widgets) { + if (!this.isWidgetVisible(widget)) continue + + const { y } = widget + const outlineColour = widget.advanced + ? LiteGraph.WIDGET_ADVANCED_OUTLINE_COLOR + : LiteGraph.WIDGET_OUTLINE_COLOR + + widget.last_y = y + + ctx.strokeStyle = outlineColour + ctx.fillStyle = '#222' + ctx.textAlign = 'left' + if (widget.computedDisabled) ctx.globalAlpha *= 0.5 + const width = widget.width || nodeWidth + + if (typeof widget.draw === 'function') { + widget.draw(ctx, this, width, y, H, lowQuality) + } else { + toConcreteWidget(widget, this, false)?.drawWidget(ctx, { + width, + showText + }) + } + ctx.globalAlpha = editorAlpha + } + ctx.restore() + } + + /** + * When {@link LGraphNode.collapsed} is `true`, this method draws the node's collapsed slots. + */ + drawCollapsedSlots(ctx: CanvasRenderingContext2D): void { + // Render the first connected slot only. + for (const slot of this.#concreteInputs) { + if (slot.link != null) { + slot.drawCollapsed(ctx) + break + } + } + for (const slot of this.#concreteOutputs) { + if (slot.links?.length) { + slot.drawCollapsed(ctx) + break + } + } + } + + get slots(): (INodeInputSlot | INodeOutputSlot)[] { + return [...this.inputs, ...this.outputs] + } + + #measureSlot( + slot: NodeInputSlot | NodeOutputSlot, + slotIndex: number, + isInput: boolean + ): void { + const pos = isInput + ? this.getInputPos(slotIndex) + : this.getOutputPos(slotIndex) + + slot.boundingRect[0] = pos[0] - LiteGraph.NODE_SLOT_HEIGHT * 0.5 + slot.boundingRect[1] = pos[1] - LiteGraph.NODE_SLOT_HEIGHT * 0.5 + slot.boundingRect[2] = slot.isWidgetInputSlot + ? BaseWidget.margin + : LiteGraph.NODE_SLOT_HEIGHT + slot.boundingRect[3] = LiteGraph.NODE_SLOT_HEIGHT + } + + #measureSlots(): ReadOnlyRect | null { + const slots: (NodeInputSlot | NodeOutputSlot)[] = [] + + for (const [slotIndex, slot] of this.#concreteInputs.entries()) { + // Unrecognized nodes (Nodes with error) has inputs but no widgets. Treat + // converted inputs as normal inputs. + /** Widget input slots are handled in {@link layoutWidgetInputSlots} */ + if (this.widgets?.length && isWidgetInputSlot(slot)) continue + + this.#measureSlot(slot, slotIndex, true) + slots.push(slot) + } + for (const [slotIndex, slot] of this.#concreteOutputs.entries()) { + this.#measureSlot(slot, slotIndex, false) + slots.push(slot) + } + + return slots.length ? createBounds(slots, 0) : null + } + + #getMouseOverSlot(slot: INodeSlot): INodeSlot | null { + const isInput = isINodeInputSlot(slot) + const mouseOverId = this.mouseOver?.[isInput ? 'inputId' : 'outputId'] ?? -1 + if (mouseOverId === -1) { + return null + } + return isInput ? this.inputs[mouseOverId] : this.outputs[mouseOverId] + } + + #isMouseOverSlot(slot: INodeSlot): boolean { + return this.#getMouseOverSlot(slot) === slot + } + + #isMouseOverWidget(widget: IBaseWidget | undefined): boolean { + if (!widget) return false + return this.mouseOver?.overWidget === widget + } + + /** + * Returns the input slot that is associated with the given widget. + */ + getSlotFromWidget( + widget: IBaseWidget | undefined + ): INodeInputSlot | undefined { + if (widget) + return this.inputs.find( + (slot) => isWidgetInputSlot(slot) && slot.widget.name === widget.name + ) + } + + /** + * Returns the widget that is associated with the given input slot. + */ + getWidgetFromSlot(slot: INodeInputSlot): IBaseWidget | undefined { + if (!isWidgetInputSlot(slot)) return + return this.widgets?.find((w) => w.name === slot.widget.name) + } + + /** + * Draws the node's input and output slots. + */ + drawSlots( + ctx: CanvasRenderingContext2D, + { fromSlot, colorContext, editorAlpha, lowQuality }: DrawSlotsOptions + ) { + for (const slot of [...this.#concreteInputs, ...this.#concreteOutputs]) { + const isValidTarget = fromSlot && slot.isValidTarget(fromSlot) + const isMouseOverSlot = this.#isMouseOverSlot(slot) + + // change opacity of incompatible slots when dragging a connection + const isValid = !fromSlot || isValidTarget + const highlight = isValid && isMouseOverSlot + + // Show slot if it's not a widget input slot + // or if it's a widget input slot and satisfies one of the following: + // - the mouse is over the widget + // - the slot is valid during link drop + // - the slot is connected + if ( + isMouseOverSlot || + isValidTarget || + !slot.isWidgetInputSlot || + this.#isMouseOverWidget(this.getWidgetFromSlot(slot)) || + slot.isConnected || + slot.alwaysVisible + ) { + ctx.globalAlpha = isValid ? editorAlpha : 0.4 * editorAlpha + slot.draw(ctx, { + colorContext, + lowQuality, + highlight + }) + } + } + } + + /** + * Arranges the node's widgets vertically. + * Sets following properties on each widget: + * - {@link IBaseWidget.computedHeight} + * - {@link IBaseWidget.y} + * @param widgetStartY The y-coordinate of the first widget + */ + #arrangeWidgets(widgetStartY: number): void { + if (!this.widgets || !this.widgets.length) return + + const bodyHeight = this.bodyHeight + const startY = + this.widgets_start_y ?? (this.widgets_up ? 0 : widgetStartY) + 2 + + let freeSpace = bodyHeight - startY + + // Collect fixed height widgets first + let fixedWidgetHeight = 0 + const growableWidgets: { + minHeight: number + prefHeight?: number + w: IBaseWidget + }[] = [] + + const visibleWidgets = this.widgets.filter((w) => !w.hidden) + + for (const w of visibleWidgets) { + if (w.computeSize) { + const height = w.computeSize()[1] + 4 + w.computedHeight = height + fixedWidgetHeight += height + } else if (w.computeLayoutSize) { + const { minHeight, maxHeight } = w.computeLayoutSize(this) + growableWidgets.push({ + minHeight, + prefHeight: maxHeight, + w + }) + } else { + const height = LiteGraph.NODE_WIDGET_HEIGHT + 4 + w.computedHeight = height + fixedWidgetHeight += height + } + } + + // Calculate remaining space for DOM widgets + freeSpace -= fixedWidgetHeight + this.freeWidgetSpace = freeSpace + + // Prepare space requests for distribution + const spaceRequests = growableWidgets.map((d) => ({ + minSize: d.minHeight, + maxSize: d.prefHeight + })) + + // Distribute space among DOM widgets + const allocations = distributeSpace(Math.max(0, freeSpace), spaceRequests) + + // Apply computed heights + for (const [i, d] of growableWidgets.entries()) { + d.w.computedHeight = allocations[i] + } + + // Position widgets + let y = startY + for (const w of visibleWidgets) { + w.y = y + y += w.computedHeight ?? 0 + } + + if (!this.graph) throw new NullGraphError() + + // Grow the node if necessary. + // Ref: https://github.com/Comfy-Org/ComfyUI_frontend/issues/2652 + // TODO: Move the layout logic before drawing of the node shape, so we don't + // need to trigger extra round of rendering. + if (y > bodyHeight) { + this.setSize([this.size[0], y]) + this.graph.setDirtyCanvas(false, true) + } + } + + /** + * Arranges the layout of the node's widget input slots. + */ + #arrangeWidgetInputSlots(): void { + if (!this.widgets) return + + const slotByWidgetName = new Map< + string, + INodeInputSlot & { index: number } + >() + + for (const [i, slot] of this.inputs.entries()) { + if (!isWidgetInputSlot(slot)) continue + + slotByWidgetName.set(slot.widget.name, { ...slot, index: i }) + } + if (!slotByWidgetName.size) return + + // Only set custom pos if not using Vue positioning + // Vue positioning calculates widget slot positions dynamically + if (!LiteGraph.vueNodesMode) { + for (const widget of this.widgets) { + const slot = slotByWidgetName.get(widget.name) + if (!slot) continue + + const actualSlot = this.#concreteInputs[slot.index] + const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5 + actualSlot.pos = [offset, widget.y + offset] + this.#measureSlot(actualSlot, slot.index, true) + } + } else { + // For Vue positioning, just measure the slots without setting pos + for (const widget of this.widgets) { + const slot = slotByWidgetName.get(widget.name) + if (!slot) continue + + this.#measureSlot(this.#concreteInputs[slot.index], slot.index, true) + } + } + } + + /** + * @internal Sets the internal concrete slot arrays, ensuring they are instances of + * {@link NodeInputSlot} or {@link NodeOutputSlot}. + * + * A temporary workaround until duck-typed inputs and outputs + * have been removed from the ecosystem. + */ + _setConcreteSlots(): void { + this.#concreteInputs = this.inputs.map((slot) => + toClass(NodeInputSlot, slot, this) + ) + this.#concreteOutputs = this.outputs.map((slot) => + toClass(NodeOutputSlot, slot, this) + ) + } + + /** + * Arranges node elements in preparation for rendering (slots & widgets). + */ + arrange(): void { + const slotsBounds = this.#measureSlots() + const widgetStartY = slotsBounds + ? slotsBounds[1] + slotsBounds[3] - this.pos[1] + : 0 + this.#arrangeWidgets(widgetStartY) + this.#arrangeWidgetInputSlots() + } + + /** + * Draws a progress bar on the node. + * @param ctx The canvas context to draw on + */ + drawProgressBar(ctx: CanvasRenderingContext2D): void { + if (!this.progress) return + + const originalFillStyle = ctx.fillStyle + ctx.fillStyle = 'green' + ctx.fillRect(0, 0, this.width * this.progress, 6) + ctx.fillStyle = originalFillStyle + } +} diff --git a/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts b/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts new file mode 100644 index 00000000..9e9454a8 --- /dev/null +++ b/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts @@ -0,0 +1,408 @@ +import type { LGraph } from '@/lib/litegraph/src/LGraph' +import type { LGraphNode, NodeId } from '@/lib/litegraph/src/LGraphNode' +import { InvalidLinkError } from '@/lib/litegraph/src/infrastructure/InvalidLinkError' +import { NullGraphError } from '@/lib/litegraph/src/infrastructure/NullGraphError' +import { RecursionError } from '@/lib/litegraph/src/infrastructure/RecursionError' +import { SlotIndexError } from '@/lib/litegraph/src/infrastructure/SlotIndexError' +import type { + CallbackParams, + CallbackReturn, + ISlotType +} from '@/lib/litegraph/src/interfaces' +import { LGraphEventMode, LiteGraph } from '@/lib/litegraph/src/litegraph' + +import type { Subgraph } from './Subgraph' +import type { SubgraphNode } from './SubgraphNode' + +export type ExecutionId = string + +/** + * Interface describing the data transfer objects used when compiling a graph for execution. + */ +export type ExecutableLGraphNode = Omit< + ExecutableNodeDTO, + 'graph' | 'node' | 'subgraphNode' +> + +/** + * The end result of resolving a DTO input. + * When a widget value is returned, {@link widgetInfo} is present and {@link origin_slot} is `-1`. + */ +type ResolvedInput = { + /** DTO for the node that the link originates from. */ + node: ExecutableLGraphNode + /** Full unique execution ID of the node that the link originates from. In the case of a widget value, this is the ID of the subgraph node. */ + origin_id: ExecutionId + /** The slot index of the output on the node that the link originates from. `-1` when widget value is set. */ + origin_slot: number + /** Boxed widget value (e.g. for widgets). If this box is `undefined`, then an input link is connected, and widget values from the subgraph node are ignored. */ + widgetInfo?: { value: unknown } +} + +/** + * Concrete implementation of {@link ExecutableLGraphNode}. + * @remarks This is the class that is used to create the data transfer objects for executable nodes. + */ +export class ExecutableNodeDTO implements ExecutableLGraphNode { + applyToGraph?( + ...args: CallbackParams + ): CallbackReturn + + /** The graph that this node is a part of. */ + readonly graph: LGraph | Subgraph + + inputs: { linkId: number | null; name: string; type: ISlotType }[] + + /** Backing field for {@link id}. */ + #id: ExecutionId + + /** + * The path to the actual node through subgraph instances, represented as a list of all subgraph node IDs (instances), + * followed by the actual original node ID within the subgraph. Each segment is separated by `:`. + * + * e.g. `1:2:3`: + * - `1` is the node ID of the first subgraph node in the parent workflow + * - `2` is the node ID of the second subgraph node in the first subgraph + * - `3` is the node ID of the actual node in the subgraph definition + */ + get id() { + return this.#id + } + + get type() { + return this.node.type + } + + get title() { + return this.node.title + } + + get mode() { + return this.node.mode + } + + get comfyClass() { + return this.node.comfyClass + } + + get isVirtualNode() { + return this.node.isVirtualNode + } + + get widgets() { + return this.node.widgets + } + + get subgraphId() { + return this.subgraphNode?.subgraph.id + } + + constructor( + /** The actual node that this DTO wraps. */ + readonly node: LGraphNode | SubgraphNode, + /** A list of subgraph instance node IDs from the root graph to the containing instance. @see {@link id} */ + readonly subgraphNodePath: readonly NodeId[], + /** A flattened map of all DTOs in this node network. Subgraph instances have been expanded into their inner nodes. */ + readonly nodesByExecutionId: Map, + /** The actual subgraph instance that contains this node, otherwise undefined. */ + readonly subgraphNode?: SubgraphNode + ) { + if (!node.graph) throw new NullGraphError() + + // Set the internal ID of the DTO + this.#id = [...this.subgraphNodePath, this.node.id].join(':') + this.graph = node.graph + this.inputs = this.node.inputs.map((x) => ({ + linkId: x.link, + name: x.name, + type: x.type + })) + + // Only create a wrapper if the node has an applyToGraph method + if (this.node.applyToGraph) { + this.applyToGraph = (...args) => this.node.applyToGraph?.(...args) + } + } + + /** Returns either the DTO itself, or the DTOs of the inner nodes of the subgraph. */ + getInnerNodes(): ExecutableLGraphNode[] { + return this.node.isSubgraphNode() + ? this.node.getInnerNodes(this.nodesByExecutionId, this.subgraphNodePath) + : [this] + } + + /** + * Resolves the executable node & link IDs for a given input slot. + * @param slot The slot index of the input. + * @param visited Leave empty unless overriding this method. + * A set of unique IDs, used to guard against infinite recursion. + * If overriding, ensure that the set is passed on all recursive calls. + * @returns The node and the origin ID / slot index of the output. + */ + resolveInput( + slot: number, + visited = new Set(), + type?: ISlotType + ): ResolvedInput | undefined { + const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[I]${slot}` + if (visited.has(uniqueId)) { + const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}` + const pathInfo = + this.subgraphNodePath.length > 0 + ? ` at path ${this.subgraphNodePath.join(':')}` + : '' + throw new RecursionError( + `Circular reference detected while resolving input ${slot} of node ${nodeInfo}${pathInfo}. ` + + `This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]` + ) + } + visited.add(uniqueId) + + const input = this.inputs.at(slot) + if (!input) + throw new SlotIndexError( + `No input found for flattened id [${this.id}] slot [${slot}]` + ) + + // Nothing connected + if (input.linkId == null) return + + const link = this.graph.getLink(input.linkId) + if (!link) + throw new InvalidLinkError( + `No link found in parent graph for id [${this.id}] slot [${slot}] ${input.name}` + ) + + const { subgraphNode } = this + + // Link goes up and out of this subgraph + if (subgraphNode && link.originIsIoNode) { + const subgraphNodeInput = subgraphNode.inputs.at(link.origin_slot) + if (!subgraphNodeInput) + throw new SlotIndexError( + `No input found for slot [${link.origin_slot}] ${input.name}` + ) + + // Nothing connected + const linkId = subgraphNodeInput.link + if (linkId == null) { + const widget = subgraphNode.getWidgetFromSlot(subgraphNodeInput) + if (!widget) return + + // Special case: SubgraphNode widget. + return { + node: this, + origin_id: this.id, + origin_slot: -1, + widgetInfo: { value: widget.value } + } + } + + const outerLink = subgraphNode.graph.getLink(linkId) + if (!outerLink) + throw new InvalidLinkError( + `No outer link found for slot [${link.origin_slot}] ${input.name}` + ) + + const subgraphNodeExecutionId = this.subgraphNodePath.join(':') + const subgraphNodeDto = this.nodesByExecutionId.get( + subgraphNodeExecutionId + ) + if (!subgraphNodeDto) + throw new Error( + `No subgraph node DTO found for id [${subgraphNodeExecutionId}]` + ) + + return subgraphNodeDto.resolveInput(outerLink.target_slot, visited) + } + + // Not part of a subgraph; use the original link + const outputNode = this.graph.getNodeById(link.origin_id) + if (!outputNode) + throw new InvalidLinkError( + `No input node found for id [${this.id}] slot [${slot}] ${input.name}` + ) + + const outputNodeExecutionId = [ + ...this.subgraphNodePath, + outputNode.id + ].join(':') + const outputNodeDto = this.nodesByExecutionId.get(outputNodeExecutionId) + if (!outputNodeDto) + throw new Error( + `No output node DTO found for id [${outputNodeExecutionId}]` + ) + + return outputNodeDto.resolveOutput( + link.origin_slot, + type ?? input.type, + visited + ) + } + + /** + * Determines whether this output is a valid endpoint for a link (non-virtual, non-bypass). + * @param slot The slot index of the output. + * @param type The type of the input + * @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}. + * @returns The node and the origin ID / slot index of the output. + */ + resolveOutput( + slot: number, + type: ISlotType, + visited: Set + ): ResolvedInput | undefined { + const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[O]${slot}` + if (visited.has(uniqueId)) { + const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}` + const pathInfo = + this.subgraphNodePath.length > 0 + ? ` at path ${this.subgraphNodePath.join(':')}` + : '' + throw new RecursionError( + `Circular reference detected while resolving output ${slot} of node ${nodeInfo}${pathInfo}. ` + + `This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]` + ) + } + visited.add(uniqueId) + + // Upstreamed: Bypass nodes are bypassed using the first input with matching type + if (this.mode === LGraphEventMode.BYPASS) { + // Bypass nodes by finding first input with matching type + const matchingIndex = this.#getBypassSlotIndex(slot, type) + + // No input types match - bypass not possible + if (matchingIndex === -1) { + console.warn( + `[ExecutableNodeDTO.resolveOutput] No input types match type [${type}] for id [${this.id}] slot [${slot}]`, + this + ) + return + } + + return this.resolveInput(matchingIndex, visited) + } + + const { node } = this + if (node.isSubgraphNode()) + return this.#resolveSubgraphOutput(slot, type, visited) + + if (node.isVirtualNode) { + const virtualLink = this.node.getInputLink(slot) + if (virtualLink) { + const { inputNode } = virtualLink.resolve(this.graph) + if (!inputNode) + throw new InvalidLinkError( + `Virtual node failed to resolve parent [${this.id}] slot [${slot}]` + ) + + const inputNodeExecutionId = [ + ...this.subgraphNodePath, + inputNode.id + ].join(':') + const inputNodeDto = this.nodesByExecutionId.get(inputNodeExecutionId) + if (!inputNodeDto) + throw new Error(`No input node DTO found for id [${inputNode.id}]`) + + return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type) + } + + // Virtual nodes without a matching input should be discarded. + return + } + + return { + node: this, + origin_id: this.id, + origin_slot: slot + } + } + + /** + * Finds the index of the input slot on this node that matches the given output {@link slot} index. + * Used when bypassing nodes. + * @param slot The output slot index on this node + * @param type The type of the final target input (so type list matches are accurate) + * @returns The index of the input slot on this node, otherwise `-1`. + */ + #getBypassSlotIndex(slot: number, type: ISlotType) { + const { inputs } = this + const oppositeInput = inputs[slot] + const outputType = this.node.outputs[slot].type + + // Any type short circuit - match slot ID, fallback to first slot + if (type === '*' || type === '') { + return inputs.length > slot ? slot : 0 + } + + // Prefer input with the same slot ID + if ( + oppositeInput && + LiteGraph.isValidConnection(oppositeInput.type, outputType) && + LiteGraph.isValidConnection(oppositeInput.type, type) + ) { + return slot + } + + // Preserve legacy behaviour; use exact match first. + const exactMatch = inputs.findIndex((input) => input.type === type) + if (exactMatch !== -1) return exactMatch + + // Find first matching slot - prefer exact type + return inputs.findIndex( + (input) => + LiteGraph.isValidConnection(input.type, outputType) && + LiteGraph.isValidConnection(input.type, type) + ) + } + + /** + * Resolves the link inside a subgraph node, from the subgraph IO node to the node inside the subgraph. + * @param slot The slot index of the output on the subgraph node. + * @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}. + * @returns A DTO for the node, and the origin ID / slot index of the output. + */ + #resolveSubgraphOutput( + slot: number, + type: ISlotType, + visited: Set + ): ResolvedInput | undefined { + const { node } = this + const output = node.outputs.at(slot) + + if (!output) + throw new SlotIndexError( + `No output found for flattened id [${this.id}] slot [${slot}]` + ) + if (!node.isSubgraphNode()) + throw new TypeError(`Node is not a subgraph node: ${node.id}`) + + // Link inside the subgraph + const innerResolved = node.resolveSubgraphOutputLink(slot) + if (!innerResolved) return + + const innerNode = innerResolved.outputNode + if (!innerNode) + throw new Error( + `No output node found for id [${this.id}] slot [${slot}] ${output.name}` + ) + + // Recurse into the subgraph + const innerNodeExecutionId = [ + ...this.subgraphNodePath, + node.id, + innerNode.id + ].join(':') + const innerNodeDto = this.nodesByExecutionId.get(innerNodeExecutionId) + if (!innerNodeDto) + throw new Error( + `No inner node DTO found for id [${innerNodeExecutionId}]` + ) + + return innerNodeDto.resolveOutput( + innerResolved.link.origin_slot, + type, + visited + ) + } +} diff --git a/docs/hel-892/setget-reference/1.37.11__src__scripts__app.ts b/docs/hel-892/setget-reference/1.37.11__src__scripts__app.ts new file mode 100644 index 00000000..edcc6451 --- /dev/null +++ b/docs/hel-892/setget-reference/1.37.11__src__scripts__app.ts @@ -0,0 +1,1744 @@ +import { useEventListener, useResizeObserver } from '@vueuse/core' +import _ from 'es-toolkit/compat' +import type { ToastMessageOptions } from 'primevue/toast' +import { reactive, unref } from 'vue' +import { shallowRef } from 'vue' + +import { useCanvasPositionConversion } from '@/composables/element/useCanvasPositionConversion' +import { registerProxyWidgets } from '@/core/graph/subgraph/proxyWidget' +import { st, t } from '@/i18n' +import type { IContextMenuValue } from '@/lib/litegraph/src/interfaces' +import { + LGraph, + LGraphCanvas, + LGraphNode, + LiteGraph +} from '@/lib/litegraph/src/litegraph' +import type { Vector2 } from '@/lib/litegraph/src/litegraph' +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { isCloud } from '@/platform/distribution/types' +import { useSettingStore } from '@/platform/settings/settingStore' +import { useTelemetry } from '@/platform/telemetry' +import type { WorkflowOpenSource } from '@/platform/telemetry/types' +import { useToastStore } from '@/platform/updates/common/toastStore' +import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' +import { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore' +import { useWorkflowValidation } from '@/platform/workflow/validation/composables/useWorkflowValidation' +import { + type ComfyApiWorkflow, + type ComfyWorkflowJSON, + type ModelFile, + type NodeId, + isSubgraphDefinition +} from '@/platform/workflow/validation/schemas/workflowSchema' +import type { + ExecutionErrorWsMessage, + NodeError, + NodeExecutionOutput, + ResultItem +} from '@/schemas/apiSchema' +import { + type ComfyNodeDef as ComfyNodeDefV1, + isComboInputSpecV1, + isComboInputSpecV2 +} from '@/schemas/nodeDefSchema' +import { + type BaseDOMWidget, + ComponentWidgetImpl, + DOMWidgetImpl +} from '@/scripts/domWidget' +import { useDialogService } from '@/services/dialogService' +import { useSubscription } from '@/platform/cloud/subscription/composables/useSubscription' +import { useExtensionService } from '@/services/extensionService' +import { useLitegraphService } from '@/services/litegraphService' +import { useSubgraphService } from '@/services/subgraphService' +import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' +import { useCommandStore } from '@/stores/commandStore' +import { useDomWidgetStore } from '@/stores/domWidgetStore' +import { useExecutionStore } from '@/stores/executionStore' +import { useExtensionStore } from '@/stores/extensionStore' +import { useFirebaseAuthStore } from '@/stores/firebaseAuthStore' +import { useNodeOutputStore } from '@/stores/imagePreviewStore' +import { KeyComboImpl, useKeybindingStore } from '@/stores/keybindingStore' +import { useModelStore } from '@/stores/modelStore' +import { SYSTEM_NODE_DEFS, useNodeDefStore } from '@/stores/nodeDefStore' +import { useSubgraphStore } from '@/stores/subgraphStore' +import { useWidgetStore } from '@/stores/widgetStore' +import { useWorkspaceStore } from '@/stores/workspaceStore' +import type { ComfyExtension, MissingNodeType } from '@/types/comfy' +import { type ExtensionManager } from '@/types/extensionTypes' +import type { NodeExecutionId } from '@/types/nodeIdentification' +import { graphToPrompt } from '@/utils/executionUtil' +import { anyItemOverlapsRect } from '@/utils/mathUtil' +import { collectAllNodes, forEachNode } from '@/utils/graphTraversalUtil' +import { + getNodeByExecutionId, + triggerCallbackOnAllNodes +} from '@/utils/graphTraversalUtil' +import { + executeWidgetsCallback, + fixLinkInputSlots, + isImageNode +} from '@/utils/litegraphUtil' +import { + findLegacyRerouteNodes, + noNativeReroutes +} from '@/utils/migration/migrateReroute' +import { getSelectedModelsMetadata } from '@/workbench/utils/modelMetadataUtil' +import { deserialiseAndCreate } from '@/utils/vintageClipboard' + +import { type ComfyApi, PromptExecutionError, api } from './api' +import { defaultGraph } from './defaultGraph' +import { importA1111 } from './pnginfo' +import { $el, ComfyUI } from './ui' +import { ComfyAppMenu } from './ui/menu/index' +import { clone } from './utils' +import { type ComfyWidgetConstructor } from './widgets' +import { ensureCorrectLayoutScale } from '@/renderer/extensions/vueNodes/layout/ensureCorrectLayoutScale' +import { extractFileFromDragEvent } from '@/utils/eventUtils' +import { getWorkflowDataFromFile } from '@/scripts/metadata/parser' +import { pasteImageNode } from '@/composables/usePaste' + +export const ANIM_PREVIEW_WIDGET = '$$comfy_animation_preview' + +function sanitizeNodeName(string: string) { + let entityMap = { + '&': '', + '<': '', + '>': '', + '"': '', + "'": '', + '`': '', + '=': '' + } + return String(string).replace(/[&<>"'`=]/g, function fromEntityMap(s) { + return entityMap[s as keyof typeof entityMap] + }) +} + +type Clipspace = { + widgets?: Pick[] | null + imgs?: HTMLImageElement[] | null + original_imgs?: HTMLImageElement[] | null + images?: any[] | null + selectedIndex: number + img_paste_mode: string + paintedIndex: number + combinedIndex: number +} + +export class ComfyApp { + /** + * List of entries to queue + */ + private queueItems: { + number: number + batchCount: number + queueNodeIds?: NodeExecutionId[] + }[] = [] + /** + * If the queue is currently being processed + */ + private processingQueue: boolean = false + + /** + * Content Clipboard + * @type {serialized node object} + */ + static clipspace: Clipspace | null = null + static clipspace_invalidate_handler: (() => void) | null = null + static open_maskeditor: (() => void) | null = null + static maskeditor_is_opended: (() => void) | null = null + static clipspace_return_node = null + + vueAppReady: boolean + api: ComfyApi + ui: ComfyUI + extensionManager!: ExtensionManager + private _nodeOutputs!: Record + nodePreviewImages: Record + + private rootGraphInternal: LGraph | undefined + + // TODO: Migrate internal usage to the + /** @deprecated Use {@link rootGraph} instead */ + get graph(): unknown { + return this.rootGraphInternal! + } + + get rootGraph(): LGraph { + if (!this.rootGraphInternal) { + console.error('ComfyApp graph accessed before initialization') + } + return this.rootGraphInternal! + } + + canvas!: LGraphCanvas + dragOverNode: LGraphNode | null = null + readonly canvasElRef = shallowRef() + get canvasEl() { + // TODO: Fix possibly undefined reference + return unref(this.canvasElRef)! + } + + private configuringGraphLevel: number = 0 + get configuringGraph() { + return this.configuringGraphLevel > 0 + } + ctx!: CanvasRenderingContext2D + bodyTop: HTMLElement + bodyLeft: HTMLElement + bodyRight: HTMLElement + bodyBottom: HTMLElement + canvasContainer: HTMLElement + menu: ComfyAppMenu + // Set by Comfy.Clipspace extension + openClipspace: () => void = () => {} + + private positionConversion?: { + clientPosToCanvasPos: (pos: Vector2) => Vector2 + canvasPosToClientPos: (pos: Vector2) => Vector2 + } + + /** + * The node errors from the previous execution. + * @deprecated Use useExecutionStore().lastNodeErrors instead + */ + get lastNodeErrors(): Record | null { + return useExecutionStore().lastNodeErrors + } + + /** + * The error from the previous execution. + * @deprecated Use useExecutionStore().lastExecutionError instead + */ + get lastExecutionError(): ExecutionErrorWsMessage | null { + return useExecutionStore().lastExecutionError + } + + /** + * @deprecated Use useExecutionStore().executingNodeId instead + * TODO: Update to support multiple executing nodes. This getter returns only the first executing node. + * Consider updating consumers to handle multiple nodes or use executingNodeIds array. + */ + get runningNodeId(): NodeId | null { + return useExecutionStore().executingNodeId + } + + /** + * @deprecated Use useWorkspaceStore().shiftDown instead + */ + get shiftDown(): boolean { + return useWorkspaceStore().shiftDown + } + + /** + * @deprecated Use useWidgetStore().widgets instead + */ + get widgets(): Record { + return Object.fromEntries(useWidgetStore().widgets.entries()) + } + + /** + * @deprecated storageLocation is always 'server' since + * https://github.com/comfyanonymous/ComfyUI/commit/53c8a99e6c00b5e20425100f6680cd9ea2652218 + */ + get storageLocation() { + return 'server' + } + + /** + * @deprecated storage migration is no longer needed. + */ + get isNewUserSession() { + return false + } + + /** + * @deprecated Use useExtensionStore().extensions instead + */ + get extensions(): ComfyExtension[] { + return useExtensionStore().extensions + } + + /** + * The progress on the current executing node, if the node reports any. + * @deprecated Use useExecutionStore().executingNodeProgress instead + */ + get progress() { + return useExecutionStore()._executingNodeProgress + } + + /** + * @deprecated Use {@link isImageNode} from @/utils/litegraphUtil instead + */ + static isImageNode(node: LGraphNode) { + return isImageNode(node) + } + + /** + * Resets the canvas view to the default + * @deprecated Use {@link useLitegraphService().resetView} instead + */ + resetView() { + useLitegraphService().resetView() + } + + constructor() { + this.vueAppReady = false + this.ui = new ComfyUI(this) + this.api = api + // Dummy placeholder elements before GraphCanvas is mounted. + this.bodyTop = $el('div.comfyui-body-top') + this.bodyLeft = $el('div.comfyui-body-left') + this.bodyRight = $el('div.comfyui-body-right') + this.bodyBottom = $el('div.comfyui-body-bottom') + this.canvasContainer = $el('div.graph-canvas-container') + + this.menu = new ComfyAppMenu(this) + + /** + * Stores the execution output data for each node + * @type {Record} + */ + this.nodeOutputs = {} + + /** + * Stores the preview image data for each node + * @type {Record} + */ + this.nodePreviewImages = {} + } + + get nodeOutputs() { + return this._nodeOutputs + } + + set nodeOutputs(value) { + this._nodeOutputs = value + if (this.vueAppReady) + useExtensionService().invokeExtensions('onNodeOutputsUpdated', value) + } + + /** + * If the user has specified a preferred format to receive preview images in, + * this function will return that format as a url query param. + * If the node's outputs are not images, this param should not be used, as it will + * force the server to load the output file as an image. + */ + getPreviewFormatParam() { + let preview_format = useSettingStore().get('Comfy.PreviewFormat') + if (preview_format) return `&preview=${preview_format}` + else return '' + } + + getRandParam() { + if (isCloud) return '' + return '&rand=' + Math.random() + } + + static onClipspaceEditorSave() { + if (ComfyApp.clipspace_return_node) { + ComfyApp.pasteFromClipspace(ComfyApp.clipspace_return_node) + } + } + + static onClipspaceEditorClosed() { + ComfyApp.clipspace_return_node = null + } + + static copyToClipspace(node: LGraphNode) { + var widgets = null + if (node.widgets) { + widgets = node.widgets.map(({ type, name, value }) => ({ + type, + name, + value + })) + } + + var imgs = undefined + var orig_imgs = undefined + if (node.imgs != undefined) { + imgs = [] + orig_imgs = [] + + for (let i = 0; i < node.imgs.length; i++) { + imgs[i] = new Image() + imgs[i].src = node.imgs[i].src + orig_imgs[i] = imgs[i] + } + } + + var selectedIndex = 0 + if (node.imageIndex) { + selectedIndex = node.imageIndex + } + + const paintedIndex = imgs ? imgs.length + 1 : 1 + const combinedIndex = imgs ? imgs.length + 2 : 2 + + // for vueNodes mode + const images = + node.images ?? useNodeOutputStore().getNodeOutputs(node)?.images + + ComfyApp.clipspace = { + widgets: widgets, + imgs: imgs, + original_imgs: orig_imgs, + images: images, + selectedIndex: selectedIndex, + img_paste_mode: 'selected', // reset to default im_paste_mode state on copy action + paintedIndex: paintedIndex, + combinedIndex: combinedIndex + } + + ComfyApp.clipspace_return_node = null + + if (ComfyApp.clipspace_invalidate_handler) { + ComfyApp.clipspace_invalidate_handler() + } + } + + static pasteFromClipspace(node: LGraphNode) { + if (ComfyApp.clipspace) { + // image paste + let combinedImgSrc: string | undefined + if ( + ComfyApp.clipspace.combinedIndex !== undefined && + ComfyApp.clipspace.imgs && + ComfyApp.clipspace.combinedIndex < ComfyApp.clipspace.imgs.length + ) { + combinedImgSrc = + ComfyApp.clipspace.imgs[ComfyApp.clipspace.combinedIndex].src + } + if (ComfyApp.clipspace.imgs && node.imgs) { + // Update node.images even if it's initially undefined (vueNodes mode) + if (ComfyApp.clipspace.images) { + if (ComfyApp.clipspace['img_paste_mode'] == 'selected') { + node.images = [ + ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']] + ] + } else { + node.images = ComfyApp.clipspace.images + } + + if (app.nodeOutputs[node.id + '']) + app.nodeOutputs[node.id + ''].images = node.images + } + + if (ComfyApp.clipspace.imgs) { + // deep-copy to cut link with clipspace + if (ComfyApp.clipspace['img_paste_mode'] == 'selected') { + const img = new Image() + img.src = + ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src + node.imgs = [img] + node.imageIndex = 0 + } else { + const imgs = [] + for (let i = 0; i < ComfyApp.clipspace.imgs.length; i++) { + imgs[i] = new Image() + imgs[i].src = ComfyApp.clipspace.imgs[i].src + node.imgs = imgs + } + } + } + } + + // Paste the RGB canvas if paintedindex exists + if ( + ComfyApp.clipspace.imgs?.[ComfyApp.clipspace.paintedIndex] && + node.imgs + ) { + const paintedImg = new Image() + paintedImg.src = + ComfyApp.clipspace.imgs[ComfyApp.clipspace.paintedIndex].src + node.imgs.push(paintedImg) // Add the RGB canvas to the node's images + } + + // Store only combined image inside the node if it exists + if ( + ComfyApp.clipspace.imgs?.[ComfyApp.clipspace.combinedIndex] && + node.imgs && + combinedImgSrc + ) { + const combinedImg = new Image() + combinedImg.src = combinedImgSrc + node.imgs = [combinedImg] + } + + if (node.widgets) { + if (ComfyApp.clipspace.images) { + const clip_image = + ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']] + const index = node.widgets.findIndex((obj) => obj.name === 'image') + if (index >= 0) { + if ( + node.widgets[index].type != 'image' && + typeof node.widgets[index].value == 'string' && + clip_image.filename + ) { + node.widgets[index].value = + (clip_image.subfolder ? clip_image.subfolder + '/' : '') + + clip_image.filename + + (clip_image.type ? ` [${clip_image.type}]` : '') + } else { + node.widgets[index].value = clip_image + } + } + } + if (ComfyApp.clipspace.widgets && node.widgets) { + ComfyApp.clipspace.widgets.forEach(({ type, name, value }) => { + const prop = node.widgets?.find( + (obj) => obj.type === type && obj.name === name + ) + if (prop && prop.type != 'button') { + const valueObj = value as Record | undefined + if ( + prop.type != 'image' && + typeof prop.value == 'string' && + valueObj?.filename + ) { + const resultItem = value as ResultItem + prop.value = + (resultItem.subfolder ? resultItem.subfolder + '/' : '') + + resultItem.filename + + (resultItem.type ? ` [${resultItem.type}]` : '') + } else { + prop.value = value + prop.callback?.(value) + } + } + }) + } + } + + app.canvas.setDirty(true) + + useNodeOutputStore().updateNodeImages(node) + } + } + + /** + * Adds a handler allowing drag+drop of files onto the window to load workflows + */ + private addDropHandler() { + // Get prompt from dropped PNG or json + useEventListener(document, 'drop', async (event: DragEvent) => { + try { + event.preventDefault() + event.stopPropagation() + + const n = this.dragOverNode + this.dragOverNode = null + // Node handles file drop, we dont use the built in onDropFile handler as its buggy + // If you drag multiple files it will call it multiple times with the same file + if (await n?.onDragDrop?.(event)) return + + const fileMaybe = await extractFileFromDragEvent(event) + if (!fileMaybe) return + + const workspace = useWorkspaceStore() + try { + workspace.spinner = true + await this.handleFile(fileMaybe, 'file_drop') + } finally { + workspace.spinner = false + } + } catch (error: unknown) { + useToastStore().addAlert(t('toastMessages.dropFileError', { error })) + } + }) + + // Always clear over node on drag leave + useEventListener(this.canvasElRef, 'dragleave', async () => { + if (!this.dragOverNode) return + this.dragOverNode = null + this.canvas.setDirty(false, true) + }) + + // Add handler for dropping onto a specific node + useEventListener( + this.canvasElRef, + 'dragover', + (event: DragEvent) => { + this.canvas.adjustMouseEvent(event) + const node = this.canvas.graph?.getNodeOnPos( + event.canvasX, + event.canvasY + ) + + if (!node?.onDragOver?.(event)) { + this.dragOverNode = null + return + } + + this.dragOverNode = node + + // dragover event is fired very frequently, run this on an animation frame + requestAnimationFrame(() => { + this.canvas.setDirty(false, true) + }) + }, + false + ) + } + + /** + * Handle keypress + */ + private addProcessKeyHandler() { + const origProcessKey = LGraphCanvas.prototype.processKey + LGraphCanvas.prototype.processKey = function (e: KeyboardEvent) { + if (!this.graph) return + + if (e.target instanceof Element && e.target.localName == 'input') { + return + } + + if (e.type == 'keydown' && !e.repeat) { + const keyCombo = KeyComboImpl.fromEvent(e) + const keybindingStore = useKeybindingStore() + const keybinding = keybindingStore.getKeybinding(keyCombo) + + if ( + keybinding && + keybinding.targetElementId === 'graph-canvas-container' + ) { + useCommandStore().execute(keybinding.commandId) + + this.graph.change() + e.preventDefault() + e.stopImmediatePropagation() + return + } + + // Ctrl+C Copy + if (e.key === 'c' && (e.metaKey || e.ctrlKey)) { + return + } + + // Ctrl+V Paste + if ( + (e.key === 'v' || e.key == 'V') && + (e.metaKey || e.ctrlKey) && + !e.shiftKey + ) { + return + } + } + + // Fall through to Litegraph defaults + return origProcessKey.apply(this, [e]) + } + } + + /** + * Handles updates from the API socket + */ + private addApiUpdateHandlers() { + api.addEventListener('status', ({ detail }) => { + this.ui.setStatus(detail) + }) + + api.addEventListener('progress', () => { + this.canvas.setDirty(true, false) + }) + + api.addEventListener('executing', () => { + this.canvas.setDirty(true, false) + }) + + api.addEventListener('executed', ({ detail }) => { + const nodeOutputStore = useNodeOutputStore() + const executionId = String(detail.display_node || detail.node) + + nodeOutputStore.setNodeOutputsByExecutionId(executionId, detail.output, { + merge: detail.merge + }) + + const node = getNodeByExecutionId(this.rootGraph, executionId) + if (node && node.onExecuted) { + node.onExecuted(detail.output) + } + }) + + api.addEventListener('execution_start', () => { + triggerCallbackOnAllNodes(this.rootGraph, 'onExecutionStart') + }) + + api.addEventListener('execution_error', ({ detail }) => { + // Check if this is an auth-related error or credits-related error + if ( + detail.exception_message?.includes( + 'Unauthorized: Please login first to use this node.' + ) + ) { + useDialogService().showApiNodesSignInDialog([detail.node_type]) + } else if ( + detail.exception_message?.includes( + 'Payment Required: Please add credits to your account to use this node.' + ) + ) { + const { isActiveSubscription } = useSubscription() + if (isActiveSubscription.value) { + useDialogService().showTopUpCreditsDialog({ + isInsufficientCredits: true + }) + } + } else { + useDialogService().showExecutionErrorDialog(detail) + } + this.canvas.draw(true, true) + }) + + api.addEventListener('b_preview_with_metadata', ({ detail }) => { + // Enhanced preview with explicit node context + const { blob, displayNodeId } = detail + const { setNodePreviewsByExecutionId, revokePreviewsByExecutionId } = + useNodeOutputStore() + // Ensure clean up if `executing` event is missed. + revokePreviewsByExecutionId(displayNodeId) + const blobUrl = URL.createObjectURL(blob) + // Preview cleanup is handled in progress_state event to support multiple concurrent previews + const nodeParents = displayNodeId.split(':') + for (let i = 1; i <= nodeParents.length; i++) { + setNodePreviewsByExecutionId(nodeParents.slice(0, i).join(':'), [ + blobUrl + ]) + } + }) + + api.init() + } + + /** Flag that the graph is configuring to prevent nodes from running checks while its still loading */ + private addConfigureHandler() { + const app = this + const configure = LGraph.prototype.configure + LGraph.prototype.configure = function (...args) { + app.configuringGraphLevel++ + try { + return configure.apply(this, args) + } finally { + app.configuringGraphLevel-- + } + } + } + + private addAfterConfigureHandler(graph: LGraph) { + const { onConfigure } = graph + graph.onConfigure = function (...args) { + fixLinkInputSlots(this) + + // Fire callbacks before the onConfigure, this is used by widget inputs to setup the config + triggerCallbackOnAllNodes(this, 'onGraphConfigured') + + const r = onConfigure?.apply(this, args) + + // Fire after onConfigure, used by primitives to generate widget using input nodes config + triggerCallbackOnAllNodes(this, 'onAfterGraphConfigured') + + return r + } + } + + /** + * Set up the app on the page + */ + async setup(canvasEl: HTMLCanvasElement) { + this.bodyTop = document.getElementById('comfyui-body-top')! + this.bodyLeft = document.getElementById('comfyui-body-left')! + this.bodyRight = document.getElementById('comfyui-body-right')! + this.bodyBottom = document.getElementById('comfyui-body-bottom')! + this.canvasContainer = document.getElementById('graph-canvas-container')! + + this.canvasElRef.value = canvasEl + + await useWorkspaceStore().workflow.syncWorkflows() + //Doesn't need to block. Blueprints will load async + void useSubgraphStore().fetchSubgraphs() + await useExtensionService().loadExtensions() + + this.addProcessKeyHandler() + this.addConfigureHandler() + this.addApiUpdateHandlers() + + const graph = new LGraph() + + // Register the subgraph - adds type wrapper for Litegraph's `createNode` factory + graph.events.addEventListener('subgraph-created', (e) => { + try { + const { subgraph, data } = e.detail + useSubgraphService().registerNewSubgraph(subgraph, data) + } catch (err) { + console.error('Failed to register subgraph', err) + useToastStore().add({ + severity: 'error', + summary: 'Failed to register subgraph', + detail: err instanceof Error ? err.message : String(err) + }) + } + }) + + this.addAfterConfigureHandler(graph) + + this.rootGraphInternal = graph + this.canvas = new LGraphCanvas(canvasEl, graph) + // Make canvas states reactive so we can observe changes on them. + this.canvas.state = reactive(this.canvas.state) + + this.ctx = canvasEl.getContext('2d')! + + LiteGraph.alt_drag_do_clone_nodes = true + LiteGraph.macGesturesRequireMac = false + + this.canvas.canvas.addEventListener<'litegraph:set-graph'>( + 'litegraph:set-graph', + (e) => { + const { newGraph } = e.detail + + const widgetStore = useDomWidgetStore() + + const activeWidgets: Record< + string, + BaseDOMWidget + > = Object.fromEntries( + newGraph.nodes + .flatMap((node) => node.widgets ?? []) + .filter( + (w) => + w instanceof DOMWidgetImpl || w instanceof ComponentWidgetImpl + ) + .map((w) => [w.id, w]) + ) + + for (const [ + widgetId, + widgetState + ] of widgetStore.widgetStates.entries()) { + if (widgetId in activeWidgets) { + widgetState.active = true + widgetState.widget = activeWidgets[widgetId] + } else { + widgetState.active = false + } + } + } + ) + + // Ensure subgraphs are scaled when entering them + this.canvas.canvas.addEventListener<'litegraph:set-graph'>( + 'litegraph:set-graph', + (e) => { + const { newGraph, oldGraph } = e.detail + // Only scale when switching between graphs (not during initial setup) + // oldGraph is null/undefined during initial setup, so skip scaling then + if (oldGraph) { + ensureCorrectLayoutScale( + newGraph.extra.workflowRendererVersion, + newGraph + ) + } + } + ) + + registerProxyWidgets(this.canvas) + + this.rootGraph.start() + + // Ensure the canvas fills the window + useResizeObserver(this.canvasElRef, ([canvasEl]) => { + if (canvasEl.target instanceof HTMLCanvasElement) { + this.resizeCanvas(canvasEl.target) + } + }) + + await useExtensionService().invokeExtensionsAsync('init') + await this.registerNodes() + + this.addDropHandler() + + await useExtensionService().invokeExtensionsAsync('setup') + + this.positionConversion = useCanvasPositionConversion( + this.canvasContainer, + this.canvas + ) + } + + private resizeCanvas(canvas: HTMLCanvasElement) { + // Limit minimal scale to 1, see https://github.com/comfyanonymous/ComfyUI/pull/845 + const scale = Math.max(window.devicePixelRatio, 1) + + // Clear fixed width and height while calculating rect so it uses 100% instead + canvas.height = canvas.width = NaN + const { width, height } = canvas.getBoundingClientRect() + canvas.width = Math.round(width * scale) + canvas.height = Math.round(height * scale) + canvas.getContext('2d')?.scale(scale, scale) + this.canvas?.draw(true, true) + } + + private updateVueAppNodeDefs(defs: Record) { + // Frontend only nodes registered by custom nodes. + // Example: https://github.com/rgthree/rgthree-comfy/blob/dd534e5384be8cf0c0fa35865afe2126ba75ac55/src_web/comfyui/fast_groups_bypasser.ts#L10 + + // Only create frontend_only definitions for nodes that don't have backend definitions + const frontendOnlyDefs: Record = {} + for (const [name, node] of Object.entries( + LiteGraph.registered_node_types + )) { + // Skip if we already have a backend definition or system definition + if (name in defs || name in SYSTEM_NODE_DEFS || node.skip_list) { + continue + } + + frontendOnlyDefs[name] = { + name, + display_name: name, + category: node.category || '__frontend_only__', + input: { required: {}, optional: {} }, + output: [], + output_name: [], + output_is_list: [], + output_node: false, + python_module: 'custom_nodes.frontend_only', + description: node.description ?? `Frontend only node for ${name}` + } as ComfyNodeDefV1 + } + + const allNodeDefs = { + ...frontendOnlyDefs, + ...defs, + ...SYSTEM_NODE_DEFS + } + + const nodeDefStore = useNodeDefStore() + const nodeDefArray: ComfyNodeDefV1[] = Object.values(allNodeDefs) + useExtensionService().invokeExtensions( + 'beforeRegisterVueAppNodeDefs', + nodeDefArray, + this + ) + nodeDefStore.updateNodeDefs(nodeDefArray) + } + + async getNodeDefs(): Promise> { + const translateNodeDef = (def: ComfyNodeDefV1): ComfyNodeDefV1 => ({ + ...def, + display_name: st( + `nodeDefs.${def.name}.display_name`, + def.display_name ?? def.name + ), + description: def.description + ? st(`nodeDefs.${def.name}.description`, def.description) + : '', + category: def.category + .split('/') + .map((category: string) => st(`nodeCategories.${category}`, category)) + .join('/') + }) + + return _.mapValues(await api.getNodeDefs(), (def) => translateNodeDef(def)) + } + + /** + * Registers nodes with the graph + */ + async registerNodes() { + // Load node definitions from the backend + const defs = await this.getNodeDefs() + await this.registerNodesFromDefs(defs) + await useExtensionService().invokeExtensionsAsync('registerCustomNodes') + if (this.vueAppReady) { + this.updateVueAppNodeDefs(defs) + } + } + + async registerNodeDef(nodeId: string, nodeDef: ComfyNodeDefV1) { + return await useLitegraphService().registerNodeDef(nodeId, nodeDef) + } + + async registerNodesFromDefs(defs: Record) { + await useExtensionService().invokeExtensionsAsync('addCustomNodeDefs', defs) + + // Register a node for each definition + for (const nodeId in defs) { + this.registerNodeDef(nodeId, defs[nodeId]) + } + } + + loadTemplateData(templateData: { + templates?: { name?: string; data?: string }[] + }): void { + if (!templateData?.templates) { + return + } + + const old = localStorage.getItem('litegrapheditor_clipboard') + + for (const template of templateData.templates) { + if (!template?.data) { + continue + } + + // Check for old clipboard format + const data = JSON.parse(template.data) + if (!data.reroutes) { + deserialiseAndCreate(template.data, app.canvas) + } else { + localStorage.setItem('litegrapheditor_clipboard', template.data) + app.canvas.pasteFromClipboard() + } + + // Move mouse position down to paste the next template below + let maxY: number | undefined + + for (const i in app.canvas.selected_nodes) { + const node = app.canvas.selected_nodes[i] + const nodeBottom = node.pos[1] + node.size[1] + if (maxY === undefined || nodeBottom > maxY) { + maxY = nodeBottom + } + } + + if (maxY !== undefined) { + app.canvas.graph_mouse[1] = maxY + 50 + } + } + + if (old !== null) { + localStorage.setItem('litegrapheditor_clipboard', old) + } + } + + private showMissingNodesError(missingNodeTypes: MissingNodeType[]) { + if (useSettingStore().get('Comfy.Workflow.ShowMissingNodesWarning')) { + useDialogService().showLoadWorkflowWarning({ missingNodeTypes }) + } + } + + private showMissingModelsError( + missingModels: ModelFile[], + paths: Record + ): void { + if (useSettingStore().get('Comfy.Workflow.ShowMissingModelsWarning')) { + useDialogService().showMissingModelsWarning({ + missingModels, + paths + }) + } + } + + async loadGraphData( + graphData?: ComfyWorkflowJSON, + clean: boolean = true, + restore_view: boolean = true, + workflow: string | null | ComfyWorkflow = null, + options: { + showMissingNodesDialog?: boolean + showMissingModelsDialog?: boolean + checkForRerouteMigration?: boolean + openSource?: WorkflowOpenSource + } = {} + ) { + const { + showMissingNodesDialog = true, + showMissingModelsDialog = true, + checkForRerouteMigration = false, + openSource + } = options + useWorkflowService().beforeLoadNewGraph() + + if (clean !== false) { + this.clean() + } + + let reset_invalid_values = false + // Use explicit validation instead of falsy check to avoid replacing + // valid but falsy values (empty objects, 0, false, etc.) + if ( + !graphData || + typeof graphData !== 'object' || + Array.isArray(graphData) + ) { + graphData = defaultGraph + reset_invalid_values = true + } + + graphData = clone(graphData) + + if (useSettingStore().get('Comfy.Validation.Workflows')) { + const { graphData: validatedGraphData } = + await useWorkflowValidation().validateWorkflow(graphData) + + // If the validation failed, use the original graph data. + // Ideally we should not block users from loading the workflow. + graphData = validatedGraphData ?? graphData + } + // Only show the reroute migration warning if the workflow does not have native + // reroutes. Merging reroute network has great complexity, and it is not supported + // for now. + // See: https://github.com/Comfy-Org/ComfyUI_frontend/issues/3317 + if ( + checkForRerouteMigration && + graphData.version === 0.4 && + findLegacyRerouteNodes(graphData).length && + noNativeReroutes(graphData) + ) { + useToastStore().add({ + group: 'reroute-migration', + severity: 'warn' + }) + } + useSubgraphService().loadSubgraphs(graphData) + + const missingNodeTypes: MissingNodeType[] = [] + const missingModels: ModelFile[] = [] + await useExtensionService().invokeExtensionsAsync( + 'beforeConfigureGraph', + graphData, + missingNodeTypes + ) + + const embeddedModels: ModelFile[] = [] + + const collectMissingNodesAndModels = ( + nodes: ComfyWorkflowJSON['nodes'], + path: string = '' + ) => { + if (!Array.isArray(nodes)) { + console.warn( + 'Workflow nodes data is missing or invalid, skipping node processing', + { nodes, path } + ) + return + } + for (let n of nodes) { + // Patch T2IAdapterLoader to ControlNetLoader since they are the same node now + if (n.type == 'T2IAdapterLoader') n.type = 'ControlNetLoader' + if (n.type == 'ConditioningAverage ') n.type = 'ConditioningAverage' //typo fix + if (n.type == 'SDV_img2vid_Conditioning') + n.type = 'SVD_img2vid_Conditioning' //typo fix + if (n.type == 'Load3DAnimation') n.type = 'Load3D' // Animation node merged into Load3D + if (n.type == 'Preview3DAnimation') n.type = 'Preview3D' // Animation node merged into Load3D + + // Find missing node types + if (!(n.type in LiteGraph.registered_node_types)) { + // Include context about subgraph location if applicable + if (path) { + missingNodeTypes.push({ + type: n.type, + hint: `in subgraph '${path}'` + }) + } else { + missingNodeTypes.push(n.type) + } + n.type = sanitizeNodeName(n.type) + } + + // Collect models metadata from node + const selectedModels = getSelectedModelsMetadata(n) + if (selectedModels?.length) { + embeddedModels.push(...selectedModels) + } + } + } + + // Process nodes at the top level + collectMissingNodesAndModels(graphData.nodes) + + // Process nodes in subgraphs + if (graphData.definitions?.subgraphs) { + for (const subgraph of graphData.definitions.subgraphs) { + if (isSubgraphDefinition(subgraph)) { + collectMissingNodesAndModels( + subgraph.nodes, + subgraph.name || subgraph.id + ) + } + } + } + + // Merge models from the workflow's root-level 'models' field + const workflowSchemaV1Models = graphData.models + if (workflowSchemaV1Models?.length) + embeddedModels.push(...workflowSchemaV1Models) + + const getModelKey = (model: ModelFile) => model.url || model.hash + const validModels = embeddedModels.filter(getModelKey) + const uniqueModels = _.uniqBy(validModels, getModelKey) + + if ( + uniqueModels.length && + useSettingStore().get('Comfy.Workflow.ShowMissingModelsWarning') + ) { + const modelStore = useModelStore() + await modelStore.loadModelFolders() + for (const m of uniqueModels) { + const modelFolder = await modelStore.getLoadedModelFolder(m.directory) + if (!modelFolder) + (m as ModelFile & { directory_invalid?: boolean }).directory_invalid = + true + + const modelsAvailable = modelFolder?.models + const modelExists = + modelsAvailable && + Object.values(modelsAvailable).some( + (model) => model.file_name === m.name + ) + if (!modelExists) missingModels.push(m) + } + } + + try { + // @ts-expect-error Discrepancies between zod and litegraph - in progress + this.rootGraph.configure(graphData) + + // Save original renderer version before scaling (it gets modified during scaling) + const originalMainGraphRenderer = + this.rootGraph.extra.workflowRendererVersion + + // Scale main graph + ensureCorrectLayoutScale(originalMainGraphRenderer) + + // Scale all subgraphs that were loaded with the workflow + // Use original main graph renderer as fallback (not the modified one) + for (const subgraph of this.rootGraph.subgraphs.values()) { + ensureCorrectLayoutScale( + subgraph.extra.workflowRendererVersion || originalMainGraphRenderer, + subgraph + ) + } + + if ( + restore_view && + useSettingStore().get('Comfy.EnableWorkflowViewRestore') + ) { + if (graphData.extra?.ds) { + this.canvas.ds.offset = graphData.extra.ds.offset + this.canvas.ds.scale = graphData.extra.ds.scale + + // Fit view if no nodes visible in restored viewport + this.canvas.ds.computeVisibleArea(this.canvas.viewport) + if ( + !anyItemOverlapsRect( + this.rootGraph._nodes, + this.canvas.visible_area + ) + ) { + requestAnimationFrame(() => useLitegraphService().fitView()) + } + } else { + useLitegraphService().fitView() + } + } + } catch (error) { + useDialogService().showErrorDialog(error, { + title: t('errorDialog.loadWorkflowTitle'), + reportType: 'loadWorkflowError' + }) + console.error(error) + return + } + forEachNode(this.rootGraph, (node) => { + const size = node.computeSize() + size[0] = Math.max(node.size[0], size[0]) + size[1] = Math.max(node.size[1], size[1]) + node.setSize(size) + if (node.widgets) { + // If you break something in the backend and want to patch workflows in the frontend + // This is the place to do this + for (let widget of node.widgets) { + if (node.type == 'KSampler' || node.type == 'KSamplerAdvanced') { + if (widget.name == 'sampler_name') { + if ( + typeof widget.value === 'string' && + widget.value.startsWith('sample_') + ) { + widget.value = widget.value.slice(7) + } + } + } + if ( + node.type == 'KSampler' || + node.type == 'KSamplerAdvanced' || + node.type == 'PrimitiveNode' + ) { + if (widget.name == 'control_after_generate') { + if (widget.value === true) { + widget.value = 'randomize' + } else if (widget.value === false) { + widget.value = 'fixed' + } + } + } + if (reset_invalid_values) { + if (widget.type == 'combo') { + const values = widget.options.values as + | (string | number | boolean)[] + | undefined + if ( + values && + values.length > 0 && + !values.includes(widget.value as string | number | boolean) + ) { + widget.value = values[0] + } + } + } + } + } + + useExtensionService().invokeExtensions('loadedGraphNode', node) + }) + + if (missingNodeTypes.length && showMissingNodesDialog) { + this.showMissingNodesError(missingNodeTypes) + } + if (missingModels.length && showMissingModelsDialog) { + const paths = await api.getFolderPaths() + this.showMissingModelsError(missingModels, paths) + } + await useExtensionService().invokeExtensionsAsync( + 'afterConfigureGraph', + missingNodeTypes + ) + + const telemetryPayload = { + missing_node_count: missingNodeTypes.length, + missing_node_types: missingNodeTypes.map((node) => + typeof node === 'string' ? node : node.type + ), + open_source: openSource ?? 'unknown' + } + useTelemetry()?.trackWorkflowOpened(telemetryPayload) + useTelemetry()?.trackWorkflowImported(telemetryPayload) + await useWorkflowService().afterLoadNewGraph( + workflow, + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON + ) + requestAnimationFrame(() => { + this.canvas.setDirty(true, true) + }) + } + + async graphToPrompt(graph = this.rootGraph) { + return graphToPrompt(graph, { + sortNodes: useSettingStore().get('Comfy.Workflow.SortNodeIdOnSave') + }) + } + + async queuePrompt( + number: number, + batchCount: number = 1, + queueNodeIds?: NodeExecutionId[] + ): Promise { + this.queueItems.push({ number, batchCount, queueNodeIds }) + + // Only have one action process the items so each one gets a unique seed correctly + if (this.processingQueue) { + return false + } + + this.processingQueue = true + const executionStore = useExecutionStore() + executionStore.lastNodeErrors = null + + let comfyOrgAuthToken = await useFirebaseAuthStore().getIdToken() + let comfyOrgApiKey = useApiKeyAuthStore().getApiKey() + + try { + while (this.queueItems.length) { + const { number, batchCount, queueNodeIds } = this.queueItems.pop()! + const previewMethod = useSettingStore().get( + 'Comfy.Execution.PreviewMethod' + ) + + for (let i = 0; i < batchCount; i++) { + // Allow widgets to run callbacks before a prompt has been queued + // e.g. random seed before every gen + forEachNode(this.rootGraph, (node) => { + for (const widget of node.widgets ?? []) widget.beforeQueued?.() + }) + + const p = await this.graphToPrompt(this.rootGraph) + const queuedNodes = collectAllNodes(this.rootGraph) + try { + api.authToken = comfyOrgAuthToken + api.apiKey = comfyOrgApiKey ?? undefined + const res = await api.queuePrompt(number, p, { + partialExecutionTargets: queueNodeIds, + previewMethod + }) + delete api.authToken + delete api.apiKey + executionStore.lastNodeErrors = res.node_errors ?? null + if (executionStore.lastNodeErrors?.length) { + this.canvas.draw(true, true) + } else { + try { + if (res.prompt_id) { + executionStore.storePrompt({ + id: res.prompt_id, + nodes: Object.keys(p.output), + workflow: useWorkspaceStore().workflow + .activeWorkflow as ComfyWorkflow + }) + } + } catch (error) {} + } + } catch (error: unknown) { + useDialogService().showErrorDialog(error, { + title: t('errorDialog.promptExecutionError'), + reportType: 'promptExecutionError' + }) + console.error(error) + + if (error instanceof PromptExecutionError) { + executionStore.lastNodeErrors = error.response.node_errors ?? null + this.canvas.draw(true, true) + } + break + } + + // Allow widgets to run callbacks after a prompt has been queued + // e.g. random seed after every gen + executeWidgetsCallback(queuedNodes, 'afterQueued') + this.canvas.draw(true, true) + await this.ui.queue.update() + } + } + } finally { + this.processingQueue = false + } + api.dispatchCustomEvent('promptQueued', { number, batchCount }) + return !executionStore.lastNodeErrors + } + + showErrorOnFileLoad(file: File) { + useToastStore().addAlert( + t('toastMessages.fileLoadError', { fileName: file.name }) + ) + } + + /** + * Loads workflow data from the specified file + * @param {File} file + */ + async handleFile(file: File, openSource?: WorkflowOpenSource) { + const fileName = file.name.replace(/\.\w+$/, '') // Strip file extension + const workflowData = await getWorkflowDataFromFile(file) + if (!workflowData) { + if (file.type.startsWith('image')) { + const transfer = new DataTransfer() + transfer.items.add(file) + pasteImageNode(this.canvas, transfer.items) + return + } + + this.showErrorOnFileLoad(file) + return + } + + const { workflow, prompt, parameters, templates } = workflowData + + if ( + templates && + typeof templates === 'object' && + Array.isArray(templates) + ) { + this.loadTemplateData({ + templates: templates as { name?: string; data?: string }[] + }) + } + + // Check workflow first - it should take priority over parameters + // when both are present (e.g., in ComfyUI-generated PNGs) + if (workflow) { + let workflowObj: ComfyWorkflowJSON | undefined = undefined + try { + workflowObj = + typeof workflow === 'string' ? JSON.parse(workflow) : workflow + + // Only load workflow if parsing succeeded AND validation passed + if ( + workflowObj && + typeof workflowObj === 'object' && + !Array.isArray(workflowObj) + ) { + await this.loadGraphData(workflowObj, true, true, fileName, { + openSource + }) + return + } else { + console.error( + 'Invalid workflow structure, trying parameters fallback' + ) + this.showErrorOnFileLoad(file) + } + } catch (err) { + console.error('Failed to parse workflow:', err) + this.showErrorOnFileLoad(file) + // Fall through to check parameters as fallback + } + } + + if (prompt) { + try { + const promptObj = + typeof prompt === 'string' ? JSON.parse(prompt) : prompt + if (this.isApiJson(promptObj)) { + this.loadApiJson(promptObj, fileName) + return + } + } catch (err) { + console.error('Failed to parse prompt:', err) + } + // Fall through to parameters as a last resort + } + + // Use parameters strictly as the final fallback + if (parameters && typeof parameters === 'string') { + useWorkflowService().beforeLoadNewGraph() + importA1111(this.rootGraph, parameters) + useWorkflowService().afterLoadNewGraph( + fileName, + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON + ) + return + } + + this.showErrorOnFileLoad(file) + } + + // @deprecated + isApiJson(data: unknown): data is ComfyApiWorkflow { + if (!_.isObject(data) || Array.isArray(data)) { + return false + } + if (Object.keys(data).length === 0) return false + + return Object.values(data).every((node) => { + if (!node || typeof node !== 'object' || Array.isArray(node)) { + return false + } + + const { class_type: classType, inputs } = node as Record + const inputsIsRecord = _.isObject(inputs) && !Array.isArray(inputs) + return typeof classType === 'string' && inputsIsRecord + }) + } + + loadApiJson(apiData: ComfyApiWorkflow, fileName: string) { + useWorkflowService().beforeLoadNewGraph() + + const missingNodeTypes = Object.values(apiData).filter( + (n) => !LiteGraph.registered_node_types[n.class_type] + ) + if (missingNodeTypes.length) { + this.showMissingNodesError(missingNodeTypes.map((t) => t.class_type)) + return + } + + const ids = Object.keys(apiData) + app.rootGraph.clear() + for (const id of ids) { + const data = apiData[id] + const node = LiteGraph.createNode(data.class_type) + if (!node) continue + node.id = isNaN(+id) ? id : +id + node.title = data._meta?.title ?? node.title + app.rootGraph.add(node) + } + + const processNodeInputs = (id: string) => { + const data = apiData[id] + const node = app.rootGraph.getNodeById(id) + if (!node) return + + for (const input in data.inputs ?? {}) { + const value = data.inputs[input] + if (value instanceof Array) { + const [fromId, fromSlot] = value + const fromNode = app.rootGraph.getNodeById(fromId) + if (!fromNode) continue + + let toSlot = node.inputs?.findIndex((inp) => inp.name === input) ?? -1 + if (toSlot === -1) { + try { + const widget = node.widgets?.find((w) => w.name === input) + const convertFn = ( + node as LGraphNode & { + convertWidgetToInput?: (w: IBaseWidget) => boolean + } + ).convertWidgetToInput + if (widget && convertFn?.(widget)) { + // Re-find the target slot by name after conversion + toSlot = + node.inputs?.findIndex((inp) => inp.name === input) ?? -1 + } + } catch (_error) { + // Ignore conversion errors + } + } + if (toSlot !== -1) { + fromNode.connect(fromSlot, node, toSlot) + } + } else { + const widget = node.widgets?.find((w) => w.name === input) + if (widget) { + widget.value = value + widget.callback?.(value) + } + } + } + } + + for (const id of ids) processNodeInputs(id) + app.rootGraph.arrange() + for (const id of ids) processNodeInputs(id) + app.rootGraph.arrange() + + useWorkflowService().afterLoadNewGraph( + fileName, + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON + ) + } + + /** + * Registers a Comfy web extension with the app + * @param {ComfyExtension} extension + */ + registerExtension(extension: ComfyExtension) { + useExtensionService().registerExtension(extension) + } + + /** + * Collects context menu items from all extensions for canvas menus + * @param canvas The canvas instance + * @returns Array of context menu items from all extensions + */ + collectCanvasMenuItems(canvas: LGraphCanvas): IContextMenuValue[] { + return useExtensionService() + .invokeExtensions('getCanvasMenuItems', canvas) + .flat() as IContextMenuValue[] + } + + /** + * Collects context menu items from all extensions for node menus + * @param node The node being right-clicked + * @returns Array of context menu items from all extensions + */ + collectNodeMenuItems(node: LGraphNode): IContextMenuValue[] { + return useExtensionService() + .invokeExtensions('getNodeMenuItems', node) + .flat() as IContextMenuValue[] + } + + /** + * Refresh combo list on whole nodes + */ + async refreshComboInNodes() { + const requestToastMessage: ToastMessageOptions = { + severity: 'info', + summary: t('g.update'), + detail: t('toastMessages.updateRequested') + } + if (this.vueAppReady) { + useToastStore().add(requestToastMessage) + } + + const defs = await this.getNodeDefs() + for (const nodeId in defs) { + this.registerNodeDef(nodeId, defs[nodeId]) + } + // Refresh combo widgets in all nodes including those in subgraphs + forEachNode(this.rootGraph, (node) => { + const def = defs[node.type] + // Allow primitive nodes to handle refresh + node.refreshComboInNode?.(defs) + + if (!def?.input) return + + if (node.widgets) { + const nodeInputs = def.input + for (const widget of node.widgets) { + if (widget.type === 'combo') { + let inputType: 'required' | 'optional' | undefined + if (nodeInputs.required?.[widget.name] !== undefined) { + inputType = 'required' + } else if (nodeInputs.optional?.[widget.name] !== undefined) { + inputType = 'optional' + } + if (inputType !== undefined) { + // Get the input spec associated with the widget + const inputSpec = nodeInputs[inputType]?.[widget.name] + if (inputSpec) { + // Refresh the combo widget's options with the values from the input spec + if (isComboInputSpecV2(inputSpec)) { + widget.options.values = inputSpec[1]?.options + } else if (isComboInputSpecV1(inputSpec)) { + widget.options.values = inputSpec[0] + } + } + } + } + } + } + }) + + await useExtensionService().invokeExtensionsAsync( + 'refreshComboInNodes', + defs + ) + + if (this.vueAppReady) { + this.updateVueAppNodeDefs(defs) + useToastStore().remove(requestToastMessage) + useToastStore().add({ + severity: 'success', + summary: t('g.updated'), + detail: t('toastMessages.nodeDefinitionsUpdated'), + life: 1000 + }) + } + } + + /** + * Clean current state + */ + clean() { + const nodeOutputStore = useNodeOutputStore() + nodeOutputStore.resetAllOutputsAndPreviews() + const executionStore = useExecutionStore() + executionStore.lastNodeErrors = null + executionStore.lastExecutionError = null + + useDomWidgetStore().clear() + + // Subgraph does not properly implement `clear` and the parent class's + // (`LGraph`) `clear` breaks the subgraph structure. + if (this.rootGraph && !this.canvas.subgraph) { + this.rootGraph.clear() + } + } + + clientPosToCanvasPos(pos: Vector2): Vector2 { + if (!this.positionConversion) { + throw new Error('clientPosToCanvasPos called before setup') + } + return this.positionConversion.clientPosToCanvasPos(pos) + } + + canvasPosToClientPos(pos: Vector2): Vector2 { + if (!this.positionConversion) { + throw new Error('canvasPosToClientPos called before setup') + } + return this.positionConversion.canvasPosToClientPos(pos) + } +} + +export const app = new ComfyApp() diff --git a/docs/hel-892/setget-reference/1.37.11__src__utils__executionUtil.ts b/docs/hel-892/setget-reference/1.37.11__src__utils__executionUtil.ts new file mode 100644 index 00000000..3f7f982c --- /dev/null +++ b/docs/hel-892/setget-reference/1.37.11__src__utils__executionUtil.ts @@ -0,0 +1,150 @@ +import type { + ExecutableLGraphNode, + ExecutionId, + LGraph +} from '@/lib/litegraph/src/litegraph' +import { + ExecutableNodeDTO, + LGraphEventMode +} from '@/lib/litegraph/src/litegraph' +import type { + ComfyApiWorkflow, + ComfyWorkflowJSON +} from '@/platform/workflow/validation/schemas/workflowSchema' + +import { ExecutableGroupNodeDTO, isGroupNode } from './executableGroupNodeDto' +import { compressWidgetInputSlots } from './litegraphUtil' + +/** + * Converts the current graph workflow for sending to the API. + * @note Node widgets are updated before serialization to prepare queueing. + * + * @param graph The graph to convert. + * @param options The options for the conversion. + * - `sortNodes`: Whether to sort the nodes by execution order. + * @returns The workflow and node links + */ +export const graphToPrompt = async ( + graph: LGraph, + options: { sortNodes?: boolean } = {} +): Promise<{ workflow: ComfyWorkflowJSON; output: ComfyApiWorkflow }> => { + const { sortNodes = false } = options + + for (const node of graph.computeExecutionOrder(false)) { + const innerNodes = node.getInnerNodes + ? node.getInnerNodes(new Map()) + : [node] + for (const innerNode of innerNodes) { + if (innerNode.isVirtualNode) { + innerNode.applyToGraph?.() + } + } + } + + const workflow = graph.serialize({ sortNodes }) + + // Remove localized_name from the workflow + for (const node of workflow.nodes) { + for (const slot of node.inputs ?? []) { + delete slot.localized_name + } + for (const slot of node.outputs ?? []) { + delete slot.localized_name + } + } + + compressWidgetInputSlots(workflow) + workflow.extra ??= {} + workflow.extra.frontendVersion = __COMFYUI_FRONTEND_VERSION__ + + const nodeDtoMap = new Map() + for (const node of graph.computeExecutionOrder(false)) { + const dto: ExecutableLGraphNode = isGroupNode(node) + ? new ExecutableGroupNodeDTO(node, [], nodeDtoMap) + : new ExecutableNodeDTO(node, [], nodeDtoMap) + + for (const innerNode of dto.getInnerNodes()) { + nodeDtoMap.set(innerNode.id, innerNode) + } + + nodeDtoMap.set(dto.id, dto) + } + + const output: ComfyApiWorkflow = {} + // Process nodes in order of execution + for (const node of nodeDtoMap.values()) { + // Don't serialize muted nodes + if ( + node.isVirtualNode || + node.mode === LGraphEventMode.NEVER || + node.mode === LGraphEventMode.BYPASS + ) { + continue + } + + const inputs: ComfyApiWorkflow[string]['inputs'] = {} + const { widgets } = node + + // Store all widget values + if (widgets) { + for (const [i, widget] of widgets.entries()) { + if (!widget.name || widget.options?.serialize === false) continue + + const widgetValue = widget.serializeValue + ? await widget.serializeValue(node, i) + : widget.value + // By default, Array values are reserved to represent node connections. + // We need to wrap the array as an object to avoid the misinterpretation + // of the array as a node connection. + // The backend automatically unwraps the object to an array during + // execution. + inputs[widget.name] = Array.isArray(widgetValue) + ? { + __value__: widgetValue + } + : widgetValue + } + } + + // Store all node links + for (const [i, input] of node.inputs.entries()) { + const resolvedInput = node.resolveInput(i) + if (!resolvedInput) continue + + // Resolved to an actual widget value rather than a node connection + if (resolvedInput.widgetInfo) { + const { value } = resolvedInput.widgetInfo + inputs[input.name] = Array.isArray(value) ? { __value__: value } : value + continue + } + + inputs[input.name] = [ + String(resolvedInput.origin_id), + // @ts-expect-error link.origin_slot is already number. + parseInt(resolvedInput.origin_slot) + ] + } + + output[String(node.id)] = { + inputs, + // TODO(huchenlei): Filter out all nodes that cannot be mapped to a + // comfyClass. + class_type: node.comfyClass!, + // Ignored by the backend. + _meta: { + title: node.title + } + } + } + + // Remove inputs connected to removed nodes + for (const { inputs } of Object.values(output)) { + for (const [i, input] of Object.entries(inputs)) { + if (Array.isArray(input) && input.length === 2 && !output[input[0]]) { + delete inputs[i] + } + } + } + + return { workflow: workflow as ComfyWorkflowJSON, output } +} diff --git a/docs/hel-892/setget-reference/1.48.6__LICENSE b/docs/hel-892/setget-reference/1.48.6__LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/docs/hel-892/setget-reference/1.48.6__LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/docs/hel-892/setget-reference/1.48.6__build__plugins__comfyAPIPlugin.ts b/docs/hel-892/setget-reference/1.48.6__build__plugins__comfyAPIPlugin.ts new file mode 100644 index 00000000..16135cbd --- /dev/null +++ b/docs/hel-892/setget-reference/1.48.6__build__plugins__comfyAPIPlugin.ts @@ -0,0 +1,123 @@ +import path from 'path' +import type { Plugin } from 'vite' + +interface ShimResult { + code: string + exports: string[] +} + +const SKIP_WARNING_FILES = new Set(['scripts/app', 'scripts/api']) + +/** Files that will be removed in v1.34 */ +const DEPRECATED_FILES = [ + 'scripts/ui', + 'extensions/core/groupNode', + 'extensions/core/nodeTemplates' +] as const + +function getWarningMessage( + fileKey: string, + shimFileName: string +): string | null { + if (SKIP_WARNING_FILES.has(fileKey)) { + return null + } + + const isDeprecated = DEPRECATED_FILES.some((deprecatedPath) => + fileKey.startsWith(deprecatedPath) + ) + + if (isDeprecated) { + return `[ComfyUI Deprecated] Importing from "${shimFileName}" is deprecated and will be removed in v1.34.` + } + + return `[ComfyUI Notice] "${shimFileName}" is an internal module, not part of the public API. Future updates may break this import.` +} + +function isLegacyFile(id: string): boolean { + return ( + id.endsWith('.ts') && + (id.includes('src/extensions/core') || id.includes('src/scripts')) + ) +} + +function transformExports(code: string, id: string): ShimResult { + const moduleName = getModuleName(id) + const exports: string[] = [] + let newCode = code + + // Regex to match different types of exports + const regex = + /export\s+(const|let|var|function|class|async function)\s+([a-zA-Z$_][a-zA-Z\d$_]*)(\s|\()/g + let match + + while ((match = regex.exec(code)) !== null) { + const name = match[2] + // All exports should be bind to the window object as new API endpoint. + if (exports.length == 0) { + newCode += `\nwindow.comfyAPI = window.comfyAPI || {};` + newCode += `\nwindow.comfyAPI.${moduleName} = window.comfyAPI.${moduleName} || {};` + } + newCode += `\nwindow.comfyAPI.${moduleName}.${name} = ${name};` + exports.push( + `export const ${name} = window.comfyAPI.${moduleName}.${name};\n` + ) + } + + return { + code: newCode, + exports + } +} + +function getModuleName(id: string): string { + // Simple example to derive a module name from the file path + const parts = id.split('/') + const fileName = parts[parts.length - 1] + return fileName.replace(/\.\w+$/, '') // Remove file extension +} + +export function comfyAPIPlugin(isDev: boolean): Plugin { + return { + name: 'comfy-api-plugin', + apply: 'build', + transform(code: string, id: string) { + if (isDev) return null + + if (isLegacyFile(id)) { + const result = transformExports(code, id) + + if (result.exports.length > 0) { + const projectRoot = process.cwd() + const relativePath = path + .relative(path.join(projectRoot, 'src'), id) + .replace(/\\/g, '/') + const shimFileName = relativePath.replace(/\.ts$/, '.js') + + let shimContent = `// Shim for ${relativePath}\n` + + const fileKey = relativePath.replace(/\.ts$/, '') + const warningMessage = getWarningMessage(fileKey, shimFileName) + + if (warningMessage) { + // It will only display once because it is at the root of the file. + shimContent += `console.warn('${warningMessage}');\n` + } + + shimContent += result.exports.join('') + + this.emitFile({ + type: 'asset', + fileName: shimFileName, + source: shimContent + }) + } + + return { + code: result.code, + map: null // If you're not modifying the source map, return null + } + } + } + } +} diff --git a/docs/hel-892/setget-reference/1.48.6__src__config__comfyApi.ts b/docs/hel-892/setget-reference/1.48.6__src__config__comfyApi.ts new file mode 100644 index 00000000..86e3c5ce --- /dev/null +++ b/docs/hel-892/setget-reference/1.48.6__src__config__comfyApi.ts @@ -0,0 +1,35 @@ +import { + configValueOrDefault, + remoteConfig +} from '@/platform/remoteConfig/remoteConfig' + +const PROD_API_BASE_URL = 'https://api.comfy.org' +const STAGING_API_BASE_URL = 'https://stagingapi.comfy.org' + +const PROD_PLATFORM_BASE_URL = 'https://platform.comfy.org' +const STAGING_PLATFORM_BASE_URL = 'https://stagingplatform.comfy.org' + +const BUILD_TIME_API_BASE_URL = __USE_PROD_CONFIG__ + ? PROD_API_BASE_URL + : (import.meta.env.VITE_STAGING_API_BASE_URL ?? STAGING_API_BASE_URL) + +const BUILD_TIME_PLATFORM_BASE_URL = __USE_PROD_CONFIG__ + ? PROD_PLATFORM_BASE_URL + : (import.meta.env.VITE_STAGING_PLATFORM_BASE_URL ?? + STAGING_PLATFORM_BASE_URL) + +export function getComfyApiBaseUrl(): string { + return configValueOrDefault( + remoteConfig.value, + 'comfy_api_base_url', + BUILD_TIME_API_BASE_URL + ) +} + +export function getComfyPlatformBaseUrl(): string { + return configValueOrDefault( + remoteConfig.value, + 'comfy_platform_base_url', + BUILD_TIME_PLATFORM_BASE_URL + ) +} diff --git a/docs/hel-892/setget-reference/1.48.6__src__lib__litegraph__src__LGraphNode.ts b/docs/hel-892/setget-reference/1.48.6__src__lib__litegraph__src__LGraphNode.ts new file mode 100644 index 00000000..a928d939 --- /dev/null +++ b/docs/hel-892/setget-reference/1.48.6__src__lib__litegraph__src__LGraphNode.ts @@ -0,0 +1,4360 @@ +import { toValue } from 'vue' + +import { LGraphNodeProperties } from '@/lib/litegraph/src/LGraphNodeProperties' +import { + calculateInputSlotPosFromSlot, + getSlotPosition +} from '@/renderer/core/canvas/litegraph/slotCalculations' +import type { SlotPositionContext } from '@/renderer/core/canvas/litegraph/slotCalculations' +import { useLayoutMutations } from '@/renderer/core/layout/operations/layoutMutations' +import { layoutStore } from '@/renderer/core/layout/store/layoutStore' +import { LayoutSource } from '@/renderer/core/layout/types' +import { isSizeEqual } from '@/renderer/core/layout/utils/geometry' +import { toLinkId } from '@/types/linkId' +import { UNASSIGNED_NODE_ID, toNodeId, serializeNodeId } from '@/types/nodeId' +import type { NodeId } from '@/types/nodeId' +import { adjustColor } from '@/utils/colorUtil' +import type { ColorAdjustOptions } from '@/utils/colorUtil' +import { + commonType, + isNodeBindable, + toClass +} from '@/lib/litegraph/src/utils/type' + +import { + SUBGRAPH_INPUT_ID, + SUBGRAPH_OUTPUT_ID +} from '@/lib/litegraph/src/constants' +import { cachedMeasureText } from '@/lib/litegraph/src/utils/textMeasureCache' +import type { DragAndScale } from './DragAndScale' +import type { LGraph } from './LGraph' +import { BadgePosition, LGraphBadge } from './LGraphBadge' +import { LGraphButton } from './LGraphButton' +import type { LGraphButtonOptions } from './LGraphButton' +import { LGraphCanvas } from './LGraphCanvas' +import { LLink } from './LLink' +import type { Reroute, RerouteId } from './Reroute' +import { getNodeInputOnPos, getNodeOutputOnPos } from './canvas/measureSlots' +import type { IDrawBoundingOptions } from './draw' +import { NullGraphError } from './infrastructure/NullGraphError' +import type { ReadOnlyRectangle } from './infrastructure/Rectangle' +import { Rectangle } from './infrastructure/Rectangle' +import type { + ColorOption, + CompassCorners, + DefaultConnectionColors, + Dictionary, + IColorable, + IContextMenuValue, + IFoundSlot, + INodeFlags, + INodeInputSlot, + INodeOutputSlot, + INodeSlot, + INodeSlotContextItem, + IPinnable, + ISlotType, + Panel, + Point, + Positionable, + ReadOnlyRect, + Rect, + Size, + SlotIndex +} from './interfaces' +import { LiteGraph, Subgraph } from './litegraph' +import type { LGraphNodeConstructor, SubgraphNode } from './litegraph' +import { + createBounds, + isInRect, + isInRectangle, + isPointInRect, + snapPoint +} from './measure' +import { NodeInputSlot } from './node/NodeInputSlot' +import { NodeOutputSlot } from './node/NodeOutputSlot' +import { + inputAsSerialisable, + isINodeInputSlot, + isWidgetInputSlot, + outputAsSerialisable +} from './node/slotUtils' +import type { SubgraphInputNode } from './subgraph/SubgraphInputNode' +import type { SubgraphOutputNode } from './subgraph/SubgraphOutputNode' +import type { NodeLike } from './types/NodeLike' +import type { CanvasPointerEvent } from './types/events' +import { + LGraphEventMode, + NodeSlotType, + RenderShape, + TitleMode +} from './types/globalEnums' +import type { ISerialisedNode, SubgraphIO } from './types/serialisation' +import type { + IBaseWidget, + IWidgetOptions, + TWidgetType, + TWidgetValue +} from './types/widgets' +import { findFreeSlotOfType } from './utils/collections' +import { warnDeprecated } from './utils/feedback' +import { distributeSpace } from './utils/spaceDistribution' +import { truncateText } from './utils/textUtils' +import { BaseWidget } from './widgets/BaseWidget' +import { toConcreteWidget } from './widgets/widgetMap' +import type { WidgetTypeMap } from './widgets/widgetMap' + +// #region Types + +export type NodeProperty = string | number | boolean | object + +/** TypedArray methods that mutate in place, so must trigger a layout commit. */ +const MUTATING_SIZE_METHODS = new Set([ + 'set', + 'fill', + 'copyWithin', + 'reverse', + 'sort' +]) + +/** Captures only the {@link layoutStore} singleton, so shared across nodes. */ +const layoutMutations = useLayoutMutations() + +interface INodePropertyInfo { + name?: string + type?: string + default_value?: NodeProperty + widget?: string + label?: string + values?: TWidgetValue[] +} + +interface IMouseOverData { + inputId?: number + outputId?: number + overWidget?: IBaseWidget +} + +interface ConnectByTypeOptions { + /** @deprecated Events */ + createEventInCase?: boolean + /** Allow our wildcard slot to connect to typed slots on remote node. Default: true */ + wildcardToTyped?: boolean + /** Allow our typed slot to connect to wildcard slots on remote node. Default: true */ + typedToWildcard?: boolean + /** The {@link Reroute.id} that the connection is being dragged from. */ + afterRerouteId?: RerouteId +} + +/** Internal type used for type safety when implementing generic checks for inputs & outputs */ +interface IGenericLinkOrLinks { + links?: INodeOutputSlot['links'] + link?: INodeInputSlot['link'] +} + +interface FindFreeSlotOptions { + /** Slots matching these types will be ignored. Default: [] */ + typesNotAccepted?: ISlotType[] + /** If true, the slot itself is returned instead of the index. Default: false */ + returnObj?: boolean +} + +interface DrawSlotsOptions { + fromSlot?: INodeInputSlot | INodeOutputSlot + colorContext: DefaultConnectionColors + editorAlpha: number + lowQuality: boolean +} + +interface DrawWidgetsOptions { + lowQuality?: boolean + editorAlpha?: number +} + +interface DrawTitleOptions { + scale: number + title_height?: number + low_quality?: boolean +} + +interface DrawTitleTextOptions extends DrawTitleOptions { + default_title_color: string +} + +export interface DrawTitleBoxOptions extends DrawTitleOptions { + box_size?: number +} + +/* +title: string +pos: [x,y] +size: [x,y] + +input|output: every connection + + { name:string, type:string, pos: [x,y]=Optional, direction: "input"|"output", links: Array }); + +general properties: + + clip_area: if you render outside the node, it will be clipped + + unsafe_execution: not allowed for safe execution + + skip_repeated_outputs: when adding new outputs, it won't show if there is one already connected + + resizable: if set to false it won't be resizable with the mouse + + widgets_start_y: widgets start at y distance from the top of the node + +flags object: + + collapsed: if it is collapsed + +supported callbacks: + + onAdded: when added to graph (warning: this is called BEFORE the node is configured when loading) + + onRemoved: when removed from graph + + onStart: when the graph starts playing + + onStop: when the graph stops playing + + onDrawForeground: render the inside widgets inside the node + + onDrawBackground: render the background area inside the node (only in edit mode) + + onMouseDown + + onMouseMove + + onMouseUp + + onMouseEnter + + onMouseLeave + + onExecute: execute the node + + onPropertyChanged: when a property is changed in the panel (return true to skip default behaviour) + + onGetInputs: returns an array of possible inputs + + onGetOutputs: returns an array of possible outputs + + onBounding: in case this node has a bigger bounding than the node itself (the callback receives the bounding as [x,y,w,h]) + + onDblClick: double clicked in the node + + onNodeTitleDblClick: double clicked in the node title + + onInputDblClick: input slot double clicked (can be used to automatically create a node connected) + + onOutputDblClick: output slot double clicked (can be used to automatically create a node connected) + + onConfigure: called after the node has been configured + + onSerialize: to add extra info when serializing (the callback receives the object that should be filled with the data) + + onSelected + + onDeselected + + onDropItem : DOM item dropped over the node + + onDropFile : file dropped over the node + + onConnectInput : if returns false the incoming connection will be canceled + + onConnectionsChange : a connection changed (new one or removed) (NodeSlotType.INPUT or NodeSlotType.OUTPUT, slot, true if connected, link_info, input_info ) + + onAction: action slot triggered + + getExtraMenuOptions: to add option to context menu +*/ + +export interface LGraphNode { + constructor: LGraphNodeConstructor +} + +// #endregion Types + +/** + * Base class for all nodes + * @param title a name for the node + * @param type a type for the node + */ + +export class LGraphNode + implements NodeLike, Positionable, IPinnable, IColorable +{ + // Static properties used by dynamic child classes + static title?: string + static MAX_CONSOLE?: number + static type?: string + static category?: string + static description?: string + static filter?: string + static skip_list?: boolean + static nodeData?: { + dev_only?: boolean + deprecated?: boolean + experimental?: boolean + output_node?: boolean + api_node?: boolean + name?: string + } + + static resizeHandleSize = 15 + static resizeEdgeSize = 5 + + /** Default setting for {@link LGraphNode.connectInputToOutput}. @see {@link INodeFlags.keepAllLinksOnBypass} */ + static keepAllLinksOnBypass: boolean = false + + /** The title text of the node. */ + title: string + /** + * The font style used to render the node's title text. + */ + get titleFontStyle(): string { + return `${LiteGraph.NODE_TEXT_SIZE}px ${LiteGraph.NODE_FONT}` + } + + get innerFontStyle(): string { + return `normal ${LiteGraph.NODE_SUBTEXT_SIZE}px ${LiteGraph.NODE_FONT}` + } + + get displayType(): string { + return this.type + } + + graph: LGraph | Subgraph | null = null + id: NodeId + type: string = '' + inputs: INodeInputSlot[] = [] + outputs: INodeOutputSlot[] = [] + + private _concreteInputs: NodeInputSlot[] = [] + private _concreteOutputs: NodeOutputSlot[] = [] + + properties: Dictionary = {} + properties_info: INodePropertyInfo[] = [] + flags: INodeFlags = {} + widgets?: IBaseWidget[] + + /** Property manager for this node */ + changeTracker: LGraphNodeProperties + + /** + * The amount of space available for widgets to grow into. + * @see {@link layoutWidgets} + */ + freeWidgetSpace?: number + + /** + * Set to true when widget-backed input slot positions need recalculation. + * Cleared after arrange() runs. Avoids per-frame O(N) scans in drawConnections. + */ + _widgetSlotsDirty = false + + locked?: boolean + + /** Execution order, automatically computed during run @see {@link LGraph.computeExecutionOrder} */ + order: number = 0 + mode: LGraphEventMode = LGraphEventMode.ALWAYS + last_serialization?: ISerialisedNode + serialize_widgets?: boolean + /** + * The overridden fg color used to render the node. + * @see {@link renderingColor} + */ + color?: string + /** + * The overridden bg color used to render the node. + * @see {@link renderingBgColor} + */ + bgcolor?: string + /** + * The overridden box color used to render the node. + * @see {@link renderingBoxColor} + */ + boxcolor?: string + + /** The fg color used to render the node. */ + get renderingColor(): string { + const baseColor = + this.color || this.constructor.color || LiteGraph.NODE_DEFAULT_COLOR + return adjustColor(baseColor, { lightness: LiteGraph.nodeLightness }) + } + + /** The bg color used to render the node. */ + get renderingBgColor(): string { + const baseBgColor = + this.bgcolor || this.constructor.bgcolor || LiteGraph.NODE_DEFAULT_BGCOLOR + const adjustments: ColorAdjustOptions = { + opacity: LiteGraph.nodeOpacity, + lightness: LiteGraph.nodeLightness + } + + return adjustColor( + this.mode === LGraphEventMode.BYPASS + ? LiteGraph.NODE_DEFAULT_BYPASS_COLOR + : baseBgColor, + adjustments + ) + } + + /** The box color used to render the node. */ + get renderingBoxColor(): string { + if (this.boxcolor) return this.boxcolor + + if (LiteGraph.node_box_coloured_when_on) { + if (this.action_triggered) return '#FFF' + if (this.execute_triggered) return '#AAA' + } + + if (LiteGraph.node_box_coloured_by_mode) { + const modeColour = + LiteGraph.NODE_MODES_COLORS[this.mode ?? LGraphEventMode.ALWAYS] + if (modeColour) return modeColour + } + return LiteGraph.NODE_DEFAULT_BOXCOLOR + } + + /** @inheritdoc {@link IColorable.setColorOption} */ + setColorOption(colorOption: ColorOption | null): void { + if (colorOption == null) { + this.color = undefined + this.bgcolor = undefined + } else { + this.color = colorOption.color + this.bgcolor = colorOption.bgcolor + } + } + + /** @inheritdoc {@link IColorable.getColorOption} */ + getColorOption(): ColorOption | null { + return ( + Object.values(LGraphCanvas.node_colors).find( + (colorOption) => + colorOption.color === this.color && + colorOption.bgcolor === this.bgcolor + ) ?? null + ) + } + + /** + * The stroke styles that should be applied to the node. + */ + strokeStyles: Record< + string, + (this: LGraphNode) => IDrawBoundingOptions | undefined + > + + /** + * The progress of node execution. Used to render a progress bar. Value between 0 and 1. + */ + progress?: number + + exec_version?: number + action_call?: string + execute_triggered?: number + action_triggered?: number + /** + * @deprecated This property is unsupported and will be removed in a future release. + * Use `widgets_start_y` or a custom `arrange()` override instead. + */ + widgets_up?: boolean + widgets_start_y?: number + lostFocusAt?: number + gotFocusAt?: number + badges: (LGraphBadge | (() => LGraphBadge))[] = [] + title_buttons: LGraphButton[] = [] + badgePosition: BadgePosition = BadgePosition.TopLeft + onOutputRemoved?(this: LGraphNode, slot: number): void + onInputRemoved?(this: LGraphNode, slot: number, input: INodeInputSlot): void + /** + * The width of the node when collapsed. + * Updated by {@link LGraphCanvas.drawNode} + */ + _collapsed_width?: number + /** + * Called once at the start of every frame. Caller may change the values in {@link out}, which will be reflected in {@link boundingRect}. + * WARNING: Making changes to boundingRect via onBounding is poorly supported, and will likely result in strange behaviour. + */ + onBounding?(this: LGraphNode, out: Rect): void + console?: string[] + _level?: number + _shape?: RenderShape + mouseOver?: IMouseOverData + redraw_on_mouse?: boolean + resizable?: boolean + clonable?: boolean + _relative_id?: number + clip_area?: boolean + ignore_remove?: boolean + has_errors?: boolean + removable?: boolean + block_delete?: boolean + selected?: boolean + showAdvanced?: boolean + + declare comfyDynamic?: Record + declare comfyClass?: string + declare isVirtualNode?: boolean + applyToGraph?(extraLinks?: LLink[]): void + + isSubgraphNode(): this is SubgraphNode { + return false + } + + /** @inheritdoc {@link renderArea} */ + private _renderArea = new Rectangle() + /** + * Rect describing the node area, including shadows and any protrusions. + * Determines if the node is visible. Calculated once at the start of every frame. + */ + get renderArea(): ReadOnlyRect { + return this._renderArea + } + + /** @inheritdoc {@link boundingRect} */ + private _boundingRect: Rectangle = new Rectangle() + /** + * Cached node position & area as `x, y, width, height`. Includes changes made by {@link onBounding}, if present. + * + * Determines the node hitbox and other rendering effects. Calculated once at the start of every frame. + */ + get boundingRect(): ReadOnlyRectangle { + return this._boundingRect + } + + /** The offset from {@link pos} to the top-left of {@link boundingRect}. */ + get boundingOffset(): Readonly { + const { + pos: [posX, posY], + boundingRect: [bX, bY] + } = this + return [posX - bX, posY - bY] + } + + /** {@link pos} and {@link size} values are backed by this {@link Rectangle}. */ + _posSize = new Rectangle() + _pos: Point = this._posSize.pos + _size: Size = this._posSize.size + + public get pos() { + return this._pos + } + + /** Node position does not necessarily correlate to the top-left corner. */ + public set pos(value) { + if (!value || value.length < 2) return + + this._pos[0] = value[0] + this._pos[1] = value[1] + if (this.id === UNASSIGNED_NODE_ID || !this.graph) return + + layoutMutations.setSource(LayoutSource.Canvas) + layoutMutations.moveNode(this.id, { x: value[0], y: value[1] }) + } + + /** + * Set the node position to an absolute location. + */ + setPos(x: number, y: number): void { + this.pos = [x, y] + } + + private _sizeProxy?: Size + + /** + * A Proxy over {@link _size} so that element mutations (`node.size[1] = h`) — + * the idiom many custom nodes use to grow a node at runtime — commit to the + * layout store, exactly like assigning `node.size = [w, h]`. Without this a + * bare element write bypasses the setter and a Vue node keeps its stale + * height until a manual resize. + * + * The Proxy is created once and reused; index writes pass straight through to + * the backing `Float64Array`, and function/length access is forwarded to the + * real typed array so spread, iteration and `.length` keep working. In-place + * mutating methods ({@link MUTATING_SIZE_METHODS}) also commit, so growing the + * node via `node.size.set(...)` reflows just like a bare element write. + * + * TODO(litegraph-stable-resize-api): interim shim — remove once a stable resize + * API replaces direct typed-array size access. + */ + public get size(): Size { + return (this._sizeProxy ??= new Proxy(this._size, { + get: (target, prop, receiver) => { + const value = Reflect.get(target, prop, target) + if (typeof value !== 'function') return value + if (typeof prop !== 'string' || !MUTATING_SIZE_METHODS.has(prop)) + return value.bind(target) + + // `set`/`fill`/etc. mutate the backing array without hitting the set + // trap, so commit through the same path a bare element write would. + // `fill`/`copyWithin`/`reverse`/`sort` return the backing array; hand + // back the Proxy so a chained index write still routes through the trap. + return (...args: unknown[]) => { + const result = Reflect.apply(value, target, args) + this._sizeUpdated() + return result === target ? receiver : result + } + }, + set: (target, prop, value) => { + const result = Reflect.set(target, prop, value) + if (prop === '0' || prop === '1') this._sizeUpdated() + return result + } + })) + } + + public set size(value) { + if (!value || value.length < 2) return + + this._size[0] = value[0] + this._size[1] = value[1] + this._sizeUpdated() + } + + /** Mirror the current {@link _size} into the layout store for Vue nodes. */ + private _sizeUpdated(): void { + if (this.id === UNASSIGNED_NODE_ID || !this.graph) return + + const size = { width: this._size[0], height: this._size[1] } + const layout = layoutStore.getNodeLayoutRef(this.id).value + if (layout && isSizeEqual(layout.size, size)) return + + layoutMutations.setSource(LayoutSource.Canvas) + layoutMutations.resizeNode(this.id, size) + } + + /** + * The size of the node used for rendering. + */ + get renderingSize(): Size { + return this.flags.collapsed ? [this._collapsed_width ?? 0, 0] : this._size + } + + get shape(): RenderShape | undefined { + return this._shape + } + + set shape(v: RenderShape | 'default' | 'box' | 'round' | 'circle' | 'card') { + const oldValue = this._shape + switch (v) { + case 'default': + this._shape = undefined + break + case 'box': + this._shape = RenderShape.BOX + break + case 'round': + this._shape = RenderShape.ROUND + break + case 'circle': + this._shape = RenderShape.CIRCLE + break + case 'card': + this._shape = RenderShape.CARD + break + default: + this._shape = v + } + if (oldValue !== this._shape) { + this.graph?.trigger('node:property:changed', { + nodeId: this.id, + property: 'shape', + oldValue, + newValue: this._shape + }) + } + } + + /** + * The shape of the node used for rendering. @see {@link RenderShape} + */ + get renderingShape(): RenderShape { + return this._shape || this.constructor.shape || LiteGraph.NODE_DEFAULT_SHAPE + } + + public get is_selected(): boolean | undefined { + return this.selected + } + + public set is_selected(value: boolean) { + this.selected = value + } + + public get title_mode(): TitleMode { + return this.constructor.title_mode ?? TitleMode.NORMAL_TITLE + } + + onConnectInput?( + this: LGraphNode, + target_slot: number, + type: unknown, + output: INodeOutputSlot | SubgraphIO, + node: LGraphNode | SubgraphInputNode, + slot: number + ): boolean + onConnectOutput?( + this: LGraphNode, + slot: number, + type: unknown, + input: INodeInputSlot | SubgraphIO, + target_node: number | LGraphNode | SubgraphOutputNode, + target_slot: number + ): boolean + onResize?(this: LGraphNode, size: Size): void + onPropertyChanged?( + this: LGraphNode, + name: string, + value: unknown, + prev_value?: unknown + ): boolean + /** Called for each connection that is created, updated, or removed. This includes "restored" connections when deserialising. */ + onConnectionsChange?( + this: LGraphNode, + type: ISlotType, + index: number, + isConnected: boolean, + link_info: LLink | null | undefined, + inputOrOutput: INodeInputSlot | INodeOutputSlot | SubgraphIO + ): void + onInputAdded?(this: LGraphNode, input: INodeInputSlot): void + onOutputAdded?(this: LGraphNode, output: INodeOutputSlot): void + onConfigure?(this: LGraphNode, serialisedNode: ISerialisedNode): void + onSerialize?(this: LGraphNode, serialised: ISerialisedNode): void + onExecute?( + this: LGraphNode, + param?: unknown, + options?: { action_call?: string } + ): void + onAction?( + this: LGraphNode, + action: string, + param: unknown, + options: { action_call?: string } + ): void + onDrawBackground?(this: LGraphNode, ctx: CanvasRenderingContext2D): void + onNodeCreated?(this: LGraphNode): void + /** + * Callback invoked by {@link connect} to override the target slot index. + * Its return value overrides the target index selection. + * @param target_slot The current input slot index + * @param requested_slot The originally requested slot index - could be negative, or if using (deprecated) name search, a string + * @returns {number | null} If a number is returned, the connection will be made to that input index. + * If an invalid index or non-number (false, null, NaN etc) is returned, the connection will be cancelled. + */ + onBeforeConnectInput?( + this: LGraphNode, + target_slot: number, + requested_slot?: number | string + ): number | false | null + onShowCustomPanelInfo?(this: LGraphNode, panel: Panel): void + onAddPropertyToPanel?(this: LGraphNode, pName: string, panel: Panel): boolean + onWidgetChanged?( + this: LGraphNode, + name: string, + value: unknown, + old_value: unknown, + w: IBaseWidget + ): void + onDeselected?(this: LGraphNode): void + onKeyUp?(this: LGraphNode, e: KeyboardEvent): void + onKeyDown?(this: LGraphNode, e: KeyboardEvent): void + onSelected?(this: LGraphNode): void + getExtraMenuOptions?( + this: LGraphNode, + canvas: LGraphCanvas, + options: (IContextMenuValue | null)[] + ): (IContextMenuValue | null)[] + getMenuOptions?(this: LGraphNode, canvas: LGraphCanvas): IContextMenuValue[] + onAdded?(this: LGraphNode, graph: LGraph): void + onDrawCollapsed?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + cavnas: LGraphCanvas + ): boolean + onDrawForeground?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + canvas: LGraphCanvas, + canvasElement: HTMLCanvasElement + ): void + onMouseLeave?(this: LGraphNode, e: CanvasPointerEvent): void + /** + * Override the default slot menu options. + */ + getSlotMenuOptions?(this: LGraphNode, slot: IFoundSlot): IContextMenuValue[] + /** + * Add extra menu options to the slot context menu. + */ + getExtraSlotMenuOptions?( + this: LGraphNode, + slot: IFoundSlot + ): IContextMenuValue[] + + // FIXME: Re-typing + onDropItem?(this: LGraphNode, event: Event): boolean + onDropData?( + this: LGraphNode, + data: string | ArrayBuffer, + filename: string, + file: File + ): void + onDropFile?(this: LGraphNode, file: File): void + onInputClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void + onInputDblClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void + onOutputClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void + onOutputDblClick?( + this: LGraphNode, + index: number, + e: CanvasPointerEvent + ): void + onGetPropertyInfo?(this: LGraphNode, property: string): INodePropertyInfo + onNodeOutputAdd?(this: LGraphNode, value: unknown): void + onNodeInputAdd?(this: LGraphNode, value: unknown): void + onMenuNodeInputs?( + this: LGraphNode, + entries: (IContextMenuValue | null)[] + ): (IContextMenuValue | null)[] + onMenuNodeOutputs?( + this: LGraphNode, + entries: (IContextMenuValue | null)[] + ): (IContextMenuValue | null)[] + onMouseUp?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): void + onMouseEnter?(this: LGraphNode, e: CanvasPointerEvent): void + /** Blocks drag if return value is truthy. @param pos Offset from {@link LGraphNode.pos}. */ + onMouseDown?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): boolean + /** @param pos Offset from {@link LGraphNode.pos}. */ + onDblClick?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): void + /** @param pos Offset from {@link LGraphNode.pos}. */ + onNodeTitleDblClick?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + canvas: LGraphCanvas + ): void + onDrawTitle?(this: LGraphNode, ctx: CanvasRenderingContext2D): void + onDrawTitleText?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + title_height: number, + size: Size, + scale: number, + title_text_font: string, + selected?: boolean + ): void + onDrawTitleBox?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + title_height: number, + size: Size, + scale: number + ): void + onDrawTitleBar?( + this: LGraphNode, + ctx: CanvasRenderingContext2D, + title_height: number, + size: Size, + scale: number, + fgcolor: string + ): void + onRemoved?(this: LGraphNode): void + onMouseMove?( + this: LGraphNode, + e: CanvasPointerEvent, + pos: Point, + arg2: LGraphCanvas + ): void + onPropertyChange?(this: LGraphNode): void + updateOutputData?(this: LGraphNode, origin_slot: number): void + + private _getErrorStrokeStyle( + this: LGraphNode + ): IDrawBoundingOptions | undefined { + if (this.has_errors) { + return { + padding: 12, + lineWidth: 10, + color: LiteGraph.NODE_ERROR_COLOUR + } + } + } + + private _getSelectedStrokeStyle( + this: LGraphNode + ): IDrawBoundingOptions | undefined { + if (this.selected) { + return { + padding: this.has_errors ? 20 : undefined + } + } + } + + constructor(title: string, type?: string) { + this.id = UNASSIGNED_NODE_ID + this.title = title || 'Unnamed' + this.type = type ?? '' + this.size = [LiteGraph.NODE_WIDTH, 60] + this.pos = [10, 10] + this.strokeStyles = { + error: this._getErrorStrokeStyle, + selected: this._getSelectedStrokeStyle + } + // Initialize property manager with tracked properties + this.changeTracker = new LGraphNodeProperties(this) + } + + /** Internal callback for subgraph nodes. Do not implement externally. */ + _internalConfigureAfterSlots?(): void + + /** + * configure a node from an object containing the serialized info + */ + configure(info: ISerialisedNode): void { + if (this.graph) { + this.graph.incrementVersion() + } + for (const j in info) { + if (j == 'properties') { + // i don't want to clone properties, I want to reuse the old container + for (const k in info.properties) { + this.properties[k] = info.properties[k] + this.onPropertyChanged?.(k, info.properties[k]) + } + continue + } + + if (j === 'id') { + const id = toNodeId(info.id) + if (id !== UNASSIGNED_NODE_ID) this.id = id + continue + } + + // @ts-expect-error #594 + if (info[j] == null) { + continue + // @ts-expect-error #594 + } else if (typeof info[j] == 'object') { + // @ts-expect-error #594 + if (this[j]?.configure) { + // @ts-expect-error #594 + this[j]?.configure(info[j]) + } else { + // @ts-expect-error #594 + this[j] = LiteGraph.cloneObject(info[j], this[j]) + } + } else { + // value + // @ts-expect-error #594 + this[j] = info[j] + } + } + + if (!info.title) { + this.title = this.constructor.title + } + + this.inputs ??= [] + this.inputs = this.inputs.map((input) => + toClass(NodeInputSlot, input, this) + ) + for (const [i, input] of this.inputs.entries()) { + const link = + this.graph && input.link != null + ? this.graph._links.get(input.link) + : null + this.onConnectionsChange?.(NodeSlotType.INPUT, i, true, link, input) + this.onInputAdded?.(input) + } + + this.outputs ??= [] + this.outputs = this.outputs.map((output) => + toClass(NodeOutputSlot, output, this) + ) + for (const [i, output] of this.outputs.entries()) { + if (!output.links) continue + + for (const linkId of output.links) { + const link = this.graph ? this.graph._links.get(linkId) : null + this.onConnectionsChange?.(NodeSlotType.OUTPUT, i, true, link, output) + } + this.onOutputAdded?.(output) + } + + // SubgraphNode callback. + this._internalConfigureAfterSlots?.() + + if (this.widgets) { + for (const w of this.widgets) { + if (!w) continue + + const input = this.inputs.find((i) => i.widget?.name === w.name) + if (input?.label) w.label = input.label + + if ( + w.options?.property && + this.properties[w.options.property] != undefined + ) + w.value = JSON.parse( + JSON.stringify(this.properties[w.options.property]) + ) + } + + if (info.widgets_values) { + let i = 0 + for (const widget of this.widgets ?? []) { + if (widget.serialize === false) continue + if (i >= info.widgets_values.length) break + widget.value = info.widgets_values[i++] + } + } + } + + // Sync the state of this.resizable. + if (this.pinned) this.resizable = false + + if (this.widgets_up) { + console.warn( + `[LiteGraph] Node type "${this.type}" uses deprecated property "widgets_up". ` + + 'This property is unsupported and will be removed. ' + + 'Use "widgets_start_y" or a custom arrange() override instead.' + ) + } + + this.onConfigure?.(info) + } + + /** + * serialize the content + */ + serialize(): ISerialisedNode { + // create serialization object + const o: ISerialisedNode = { + id: serializeNodeId(this.id), + type: this.type, + pos: [this.pos[0], this.pos[1]], + size: [this.size[0], this.size[1]], + flags: LiteGraph.cloneObject(this.flags), + order: this.order, + mode: this.mode, + showAdvanced: this.showAdvanced + } + + // special case for when there were errors + if (this.constructor === LGraphNode && this.last_serialization) + return { ...this.last_serialization, mode: o.mode, pos: o.pos } + + if (this.inputs) + o.inputs = this.inputs.map((input) => inputAsSerialisable(input)) + if (this.outputs) + // @ts-expect-error - Output serialization type mismatch + o.outputs = this.outputs.map((output) => outputAsSerialisable(output)) + + if (this.title && this.title != this.constructor.title) o.title = this.title + + if (this.properties) o.properties = LiteGraph.cloneObject(this.properties) + + const { widgets } = this + if (widgets && this.serialize_widgets) { + o.widgets_values = [] + for (const [i, widget] of widgets.entries()) { + if (widget.serialize === false) continue + const val = widget?.value + // Ensure object values are plain (not reactive proxies) for structuredClone compatibility. + o.widgets_values[i] = + val != null && typeof val === 'object' + ? JSON.parse(JSON.stringify(val)) + : (val ?? null) + } + } + + if (!o.type && this.constructor.type) o.type = this.constructor.type + + if (this.color) o.color = this.color + if (this.bgcolor) o.bgcolor = this.bgcolor + if (this.boxcolor) o.boxcolor = this.boxcolor + if (this.shape) o.shape = this.shape + + if (this.onSerialize?.(o)) + console.warn( + "node onSerialize shouldn't return anything, data should be stored in the object pass in the first parameter" + ) + + return o + } + + clone(): LGraphNode | null { + if (this.type == null) return null + const node = LiteGraph.createNode(this.type) + if (!node) return null + + // we clone it because serialize returns shared containers + const data = LiteGraph.cloneObject(this.serialize()) + const { inputs, outputs } = data + + // remove links + if (inputs) { + for (const input of inputs) { + input.link = null + } + } + + if (outputs) { + for (const { links } of outputs) { + if (links) links.length = 0 + } + } + + // @ts-expect-error Exceptional case: id is removed so that the graph can assign a new one on add. + data.id = undefined + + node.id = this.id + node.configure(data) + + return node + } + + /** + * serialize and stringify + */ + toString(): string { + return JSON.stringify(this.serialize()) + } + + /** + * get the title string + */ + getTitle(): string { + return this.title || this.constructor.title + } + + /** + * sets the value of a property + * @param name + * @param value + */ + setProperty(name: string, value: TWidgetValue): void { + this.properties ||= {} + if (value === this.properties[name]) return + + const prev_value = this.properties[name] + this.properties[name] = value + // abort change + if (this.onPropertyChanged?.(name, value, prev_value) === false) + this.properties[name] = prev_value + + if (this.widgets) { + for (const w of this.widgets) { + if (!w) continue + + if (w.options.property == name) { + w.value = value + break + } + } + } + } + + /** + * sets the output data + * @param slot + * @param data + */ + setOutputData( + slot: number, + data: number | string | boolean | { toToolTip?(): string } + ): void { + const { outputs } = this + if (!outputs) return + + // this maybe slow and a niche case + if (slot == -1 || slot >= outputs.length) return + + const output_info = outputs[slot] + if (!output_info) return + + // store data in the output itself in case we want to debug + output_info._data = data + + if (!this.graph) throw new NullGraphError() + + // if there are connections, pass the data to the connections + const { links } = outputs[slot] + if (links) { + for (const id of links) { + const link = this.graph._links.get(id) + if (link) link.data = data + } + } + } + + /** + * sets the output data type, useful when you want to be able to overwrite the data type + */ + setOutputDataType(slot: SlotIndex, type: ISlotType): void { + const { outputs } = this + if (!outputs || slot == -1 || slot >= outputs.length) return + + const output_info = outputs[slot] + if (!output_info) return + // store data in the output itself in case we want to debug + output_info.type = type + + if (!this.graph) throw new NullGraphError() + + // if there are connections, pass the data to the connections + const { links } = outputs[slot] + if (links) { + for (const id of links) { + const link = this.graph._links.get(id) + if (link) link.type = type + } + } + } + + /** + * Retrieves the input data (data traveling through the connection) from one slot + * @param slot + * @param force_update if set to true it will force the connected node of this slot to output data into this link + * @returns data or if it is not connected returns undefined + */ + getInputData(slot: number, force_update?: boolean): unknown { + if (!this.inputs) return + + if (slot >= this.inputs.length || this.inputs[slot].link == null) return + if (!this.graph) throw new NullGraphError() + + const link_id = this.inputs[slot].link + const link = this.graph._links.get(link_id) + // bug: weird case but it happens sometimes + if (!link) return null + + if (!force_update) return link.data + + // special case: used to extract data from the incoming connection before the graph has been executed + const node = this.graph.getNodeById(link.origin_id) + if (!node) return link.data + + if (node.updateOutputData) { + node.updateOutputData(link.origin_slot) + } else { + node.onExecute?.() + } + + return link.data + } + + /** + * Retrieves the input data type (in case this supports multiple input types) + * @param slot + * @returns datatype in string format + */ + getInputDataType(slot: SlotIndex): ISlotType | null { + if (!this.inputs) return null + if (slot >= this.inputs.length || this.inputs[slot].link == null) + return null + if (!this.graph) throw new NullGraphError() + + const link_id = this.inputs[slot].link + const link = this.graph._links.get(link_id) + // bug: weird case but it happens sometimes + if (!link) return null + + const node = this.graph.getNodeById(link.origin_id) + if (!node) return link.type + + const output_info = node.outputs[link.origin_slot] + return output_info ? output_info.type : null + } + + /** + * Retrieves the input data from one slot using its name instead of slot number + * @param slot_name + * @param force_update if set to true it will force the connected node of this slot to output data into this link + * @returns data or if it is not connected returns null + */ + getInputDataByName(slot_name: string, force_update: boolean): unknown { + const slot = this.findInputSlot(slot_name) + return slot == -1 ? null : this.getInputData(slot, force_update) + } + + /** + * tells you if there is a connection in one input slot + * @param slot The 0-based index of the input to check + * @returns `true` if the input slot has a link ID (does not perform validation) + */ + isInputConnected(slot: number): boolean { + if (!this.inputs) return false + return slot < this.inputs.length && this.inputs[slot].link != null + } + + /** + * tells you info about an input connection (which node, type, etc) + * @returns object or null { link: id, name: string, type: string or 0 } + */ + getInputInfo(slot: number): INodeInputSlot | null { + return !this.inputs || !(slot < this.inputs.length) + ? null + : this.inputs[slot] + } + + /** + * Resolves the output source for cross-graph virtual nodes (e.g. Set/Get), + * bypassing {@link getInputLink} when the source lives in a different graph. + */ + resolveVirtualOutput?( + slot: number + ): { node: LGraphNode; slot: number } | undefined + + /** + * Returns the link info in the connection of an input slot + * @returns object or null + */ + getInputLink(slot: number): LLink | null { + if (!this.inputs) return null + + if (slot < this.inputs.length) { + if (!this.graph) throw new NullGraphError() + + const input = this.inputs[slot] + if (input.link != null) { + return this.graph._links.get(input.link) ?? null + } + } + return null + } + + /** + * returns the node connected in the input slot + * @returns node or null + */ + getInputNode(slot: number): LGraphNode | null { + if (!this.inputs) return null + if (slot >= this.inputs.length) return null + + const input = this.inputs[slot] + if (!input || input.link === null) return null + if (!this.graph) throw new NullGraphError() + + const link_info = this.graph._links.get(input.link) + if (!link_info) return null + + return this.graph.getNodeById(link_info.origin_id) + } + + /** + * returns the value of an input with this name, otherwise checks if there is a property with that name + * @returns value + */ + getInputOrProperty(name: string): unknown { + const { inputs } = this + if (!inputs?.length) { + return this.properties ? this.properties[name] : null + } + if (!this.graph) throw new NullGraphError() + + for (const input of inputs) { + if (name == input.name && input.link != null) { + const link = this.graph._links.get(input.link) + if (link) return link.data + } + } + return this.properties[name] + } + + /** + * tells you the last output data that went in that slot + * @returns object or null + */ + getOutputData(slot: number): unknown { + if (!this.outputs) return null + if (slot >= this.outputs.length) return null + + const info = this.outputs[slot] + return info._data + } + + /** + * tells you info about an output connection (which node, type, etc) + * @returns object or null { name: string, type: string, links: [ ids of links in number ] } + */ + getOutputInfo(slot: number): INodeOutputSlot | null { + return !this.outputs || !(slot < this.outputs.length) + ? null + : this.outputs[slot] + } + + /** + * tells you if there is a connection in one output slot + */ + isOutputConnected(slot: number): boolean { + if (!this.outputs) return false + return ( + slot < this.outputs.length && Number(this.outputs[slot].links?.length) > 0 + ) + } + + /** + * tells you if there is any connection in the output slots + */ + isAnyOutputConnected(): boolean { + const { outputs } = this + if (!outputs) return false + + for (const output of outputs) { + if (output.links?.length) return true + } + return false + } + + /** + * retrieves all the nodes connected to this output slot + */ + getOutputNodes(slot: number): LGraphNode[] | null { + const { outputs } = this + if (!outputs || outputs.length == 0) return null + + if (slot >= outputs.length) return null + + const { links } = outputs[slot] + if (!links || links.length == 0) return null + if (!this.graph) throw new NullGraphError() + + const r: LGraphNode[] = [] + for (const id of links) { + const link = this.graph._links.get(id) + if (link) { + const target_node = this.graph.getNodeById(link.target_id) + if (target_node) { + r.push(target_node) + } + } + } + return r + } + + addOnTriggerInput(): number { + const trigS = this.findInputSlot('onTrigger') + if (trigS == -1) { + this.addInput('onTrigger', LiteGraph.EVENT, { + nameLocked: true + }) + return this.findInputSlot('onTrigger') + } + return trigS + } + + addOnExecutedOutput(): number { + const trigS = this.findOutputSlot('onExecuted') + if (trigS == -1) { + this.addOutput('onExecuted', LiteGraph.ACTION, { + nameLocked: true + }) + return this.findOutputSlot('onExecuted') + } + return trigS + } + + onAfterExecuteNode(param: unknown, options?: { action_call?: string }) { + const trigS = this.findOutputSlot('onExecuted') + if (trigS != -1) { + this.triggerSlot(trigS, param, null, options) + } + } + + changeMode(modeTo: number): boolean { + switch (modeTo) { + case LGraphEventMode.ON_EVENT: + break + + case LGraphEventMode.ON_TRIGGER: + this.addOnTriggerInput() + this.addOnExecutedOutput() + break + + case LGraphEventMode.NEVER: + break + + case LGraphEventMode.ALWAYS: + break + + // @ts-expect-error Not impl. + case LiteGraph.ON_REQUEST: + break + + default: + return false + } + this.mode = modeTo + return true + } + + /** + * Triggers the node code execution, place a boolean/counter to mark the node as being executed + */ + doExecute(param?: unknown, options?: { action_call?: string }): void { + options = options || {} + if (this.onExecute) { + // enable this to give the event an ID + options.action_call ||= `${this.id}_exec_${Math.floor(Math.random() * 9999)}` + if (!this.graph) throw new NullGraphError() + + // @ts-expect-error Technically it works when id is a string. Array gets props. + this.graph.nodes_executing[this.id] = true + this.onExecute(param, options) + // @ts-expect-error deprecated + this.graph.nodes_executing[this.id] = false + + // save execution/action ref + this.exec_version = this.graph.iteration + if (options?.action_call) { + this.action_call = options.action_call + // @ts-expect-error deprecated + this.graph.nodes_executedAction[this.id] = options.action_call + } + } + // the nFrames it will be used (-- each step), means "how old" is the event + this.execute_triggered = 2 + this.onAfterExecuteNode?.(param, options) + } + + /** + * Triggers an action, wrapped by logics to control execution flow + * @param action name + */ + actionDo( + action: string, + param: unknown, + options: { action_call?: string } + ): void { + options = options || {} + if (this.onAction) { + // enable this to give the event an ID + options.action_call ||= `${this.id}_${action || 'action'}_${Math.floor(Math.random() * 9999)}` + if (!this.graph) throw new NullGraphError() + + // @ts-expect-error deprecated + this.graph.nodes_actioning[this.id] = action || 'actioning' + this.onAction(action, param, options) + // @ts-expect-error deprecated + this.graph.nodes_actioning[this.id] = false + + // save execution/action ref + if (options?.action_call) { + this.action_call = options.action_call + // @ts-expect-error deprecated + this.graph.nodes_executedAction[this.id] = options.action_call + } + } + // the nFrames it will be used (-- each step), means "how old" is the event + this.action_triggered = 2 + this.onAfterExecuteNode?.(param, options) + } + + /** + * Triggers an event in this node, this will trigger any output with the same name + * @param action name ( "on_play", ... ) if action is equivalent to false then the event is send to all + */ + trigger( + action: string, + param: unknown, + options: { action_call?: string } + ): void { + const { outputs } = this + if (!outputs || !outputs.length) { + return + } + + if (this.graph) this.graph._last_trigger_time = LiteGraph.getTime() + + for (const [i, output] of outputs.entries()) { + if ( + !output || + output.type !== LiteGraph.EVENT || + (action && output.name != action) + ) { + continue + } + this.triggerSlot(i, param, null, options) + } + } + + /** + * Triggers a slot event in this node: cycle output slots and launch execute/action on connected nodes + * @param slot the index of the output slot + * @param link_id [optional] in case you want to trigger and specific output link in a slot + */ + triggerSlot( + slot: number, + param: unknown, + link_id: number | null, + options?: { action_call?: string } + ): void { + options = options || {} + if (!this.outputs) return + + if (slot == null) { + console.error('slot must be a number') + return + } + + if (typeof slot !== 'number') + console.warn( + "slot must be a number, use node.trigger('name') if you want to use a string" + ) + + const output = this.outputs[slot] + if (!output) return + + const links = output.links + if (!links || !links.length) return + + if (!this.graph) throw new NullGraphError() + this.graph._last_trigger_time = LiteGraph.getTime() + + // for every link attached here + for (const id of links) { + // to skip links + if (link_id != null && link_id != id) continue + + const link_info = this.graph._links.get(id) + // not connected + if (!link_info) continue + + link_info._last_time = LiteGraph.getTime() + const node = this.graph.getNodeById(link_info.target_id) + // node not found? + if (!node) continue + + if (node.mode === LGraphEventMode.ON_TRIGGER) { + // generate unique trigger ID if not present + if (!options.action_call) + options.action_call = `${this.id}_trigg_${Math.floor(Math.random() * 9999)}` + // -- wrapping node.onExecute(param); -- + node.doExecute?.(param, options) + } else if (node.onAction) { + // generate unique action ID if not present + if (!options.action_call) + options.action_call = `${this.id}_act_${Math.floor(Math.random() * 9999)}` + // pass the action name + const target_connection = node.inputs[link_info.target_slot] + node.actionDo(target_connection.name, param, options) + } + } + } + + /** + * clears the trigger slot animation + * @param slot the index of the output slot + * @param link_id [optional] in case you want to trigger and specific output link in a slot + */ + clearTriggeredSlot(slot: number, link_id: number): void { + if (!this.outputs) return + + const output = this.outputs[slot] + if (!output) return + + const links = output.links + if (!links || !links.length) return + + if (!this.graph) throw new NullGraphError() + + // for every link attached here + for (const id of links) { + // to skip links + if (link_id != null && link_id != id) continue + + const link_info = this.graph._links.get(id) + // not connected + if (!link_info) continue + + link_info._last_time = 0 + } + } + + /** + * changes node size and triggers callback + */ + setSize(size: Size): void { + this.size = size + this.onResize?.(this.size) + } + + /** + * Expands the node size to fit its content. + */ + expandToFitContent(): void { + const newSize = this.computeSize() + this.setSize([ + Math.max(this.size[0], newSize[0]), + Math.max(this.size[1], newSize[1]) + ]) + } + + /** + * add a new property to this node + * @param type string defining the output type ("vec3","number",...) + * @param extra_info this can be used to have special properties of the property (like values, etc) + */ + addProperty( + name: string, + default_value: NodeProperty | undefined, + type?: string, + extra_info?: Partial + ): INodePropertyInfo { + const o: INodePropertyInfo = { name, type, default_value } + if (extra_info) Object.assign(o, extra_info) + + this.properties_info ||= [] + this.properties_info.push(o) + this.properties ||= {} + this.properties[name] = default_value + return o + } + + /** + * add a new output slot to use in this node + * @param type string defining the output type ("vec3","number",...) + * @param extra_info this can be used to have special properties of an output (label, special color, position, etc) + */ + addOutput>( + name: string, + type: ISlotType, + extra_info?: TProperties + ): INodeOutputSlot & TProperties { + const output = Object.assign( + new NodeOutputSlot({ name, type, links: null }, this), + extra_info + ) + + this.outputs ||= [] + this.outputs.push(output) + this.onOutputAdded?.(output) + + if (LiteGraph.auto_load_slot_types) + LiteGraph.registerNodeAndSlotType(this, type, true) + + this.expandToFitContent() + this.setDirtyCanvas(true, true) + return output + } + + /** + * remove an existing output slot + */ + removeOutput(slot: number): void { + // Only disconnect if node is part of a graph + if (this.graph) { + this.disconnectOutput(slot) + } + const { outputs } = this + outputs.splice(slot, 1) + + for (let i = slot; i < outputs.length; ++i) { + const output = outputs[i] + if (!output || !output.links) continue + + // Only update link indices if node is part of a graph + if (this.graph) { + for (const linkId of output.links) { + const link = this.graph._links.get(linkId) + if (link) link.origin_slot-- + } + } + } + + this.onOutputRemoved?.(slot) + this.setDirtyCanvas(true, true) + } + + /** + * add a new input slot to use in this node + * @param type string defining the input type ("vec3","number",...), it its a generic one use 0 + * @param extra_info this can be used to have special properties of an input (label, color, position, etc) + */ + addInput>( + name: string, + type: ISlotType, + extra_info?: TProperties + ): INodeInputSlot & TProperties { + type ||= 0 + + const input = Object.assign( + new NodeInputSlot({ name, type, link: null }, this), + extra_info + ) + + this.inputs ||= [] + this.inputs.push(input) + this.expandToFitContent() + + this.onInputAdded?.(input) + LiteGraph.registerNodeAndSlotType(this, type) + + this.setDirtyCanvas(true, true) + return input + } + + /** + * remove an existing input slot + */ + removeInput(slot: number): void { + // Only disconnect if node is part of a graph + if (this.graph) { + this.disconnectInput(slot, true) + } + const { inputs } = this + const slot_info = inputs.splice(slot, 1) + + for (let i = slot; i < inputs.length; ++i) { + const input = inputs[i] + if (!input?.link) continue + + // Only update link indices if node is part of a graph + if (this.graph) { + const link = this.graph._links.get(input.link) + if (link) link.target_slot-- + } + } + this.onInputRemoved?.(slot, slot_info[0]) + this.setDirtyCanvas(true, true) + } + + /** + * computes the minimum size of a node according to its inputs and output slots + * @returns the total size + */ + computeSize(out?: Size): Size { + const ctorSize = this.constructor.size + if (ctorSize) return [ctorSize[0], ctorSize[1]] + + const { inputs, outputs, widgets } = this + let rows = Math.max( + inputs ? inputs.filter((input) => !isWidgetInputSlot(input)).length : 1, + outputs ? outputs.length : 1 + ) + const size = out ?? [0, 0] + rows = Math.max(rows, 1) + // although it should be graphcanvas.inner_text_font size + const font_size = LiteGraph.NODE_TEXT_SIZE + + const padLeft = LiteGraph.NODE_TITLE_HEIGHT + const padRight = padLeft * 0.33 + const title_width = + padLeft + compute_text_size(this.title, this.titleFontStyle) + padRight + let input_width = 0 + let widgetWidth = 0 + let output_width = 0 + + if (inputs) { + for (const input of inputs) { + const text = input.label || input.localized_name || input.name || '' + const text_width = compute_text_size(text, this.innerFontStyle) + if (isWidgetInputSlot(input)) { + const widget = this.getWidgetFromSlot(input) + if (widget && !this.isWidgetVisible(widget)) continue + + if (text_width > widgetWidth) widgetWidth = text_width + } else { + if (text_width > input_width) input_width = text_width + } + } + } + + if (outputs) { + for (const output of outputs) { + const text = output.label || output.localized_name || output.name || '' + const text_width = compute_text_size(text, this.innerFontStyle) + if (output_width < text_width) output_width = text_width + } + } + + const minWidth = LiteGraph.NODE_WIDTH * (widgets?.length ? 1.5 : 1) + // Text + slot width + centre padding + const centrePadding = input_width && output_width ? 5 : 0 + const slotsWidth = + input_width + + output_width + + 2 * LiteGraph.NODE_SLOT_HEIGHT + + centrePadding + + // Total distance from edge of node to the inner edge of the widget 'previous' arrow button + const widgetMargin = + BaseWidget.margin + BaseWidget.arrowMargin + BaseWidget.arrowWidth + const widgetPadding = BaseWidget.minValueWidth + 2 * widgetMargin + if (widgetWidth) widgetWidth += widgetPadding + + size[0] = Math.max(slotsWidth, widgetWidth, title_width, minWidth) + size[1] = + (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT + + // Get widget height & expand size if necessary + let widgets_height = 0 + if (widgets?.length) { + for (const widget of widgets) { + if (!this.isWidgetVisible(widget)) continue + + let widget_height = 0 + if (widget.computeSize) { + widget_height += widget.computeSize(size[0])[1] + } else if (widget.computeLayoutSize) { + // Expand widget width if necessary + const { minHeight, minWidth } = widget.computeLayoutSize(this) + const widgetWidth = minWidth + widgetPadding + if (widgetWidth > size[0]) size[0] = widgetWidth + + widget_height += minHeight + } else { + widget_height += LiteGraph.NODE_WIDGET_HEIGHT + } + widgets_height += widget_height + 4 + } + widgets_height += 8 + } + + // compute height using widgets height + if (this.widgets_up) size[1] = Math.max(size[1], widgets_height) + else if (this.widgets_start_y != null) + size[1] = Math.max(size[1], widgets_height + this.widgets_start_y) + else size[1] += widgets_height + + function compute_text_size(text: string, fontStyle: string) { + return ( + LGraphCanvas._measureText?.(text, fontStyle) ?? + font_size * (text?.length ?? 0) * 0.6 + ) + } + + if (this.constructor.min_height && size[1] < this.constructor.min_height) { + size[1] = this.constructor.min_height + } + + // margin + size[1] += 6 + + return size + } + + inResizeCorner(canvasX: number, canvasY: number): boolean { + const rows = this.outputs ? this.outputs.length : 1 + const outputs_offset = + (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT + return isInRectangle( + canvasX, + canvasY, + this.pos[0] + this.size[0] - 15, + this.pos[1] + Math.max(this.size[1] - 15, outputs_offset), + 20, + 20 + ) + } + + /** + * Returns which resize corner the point is over, if any. + * @param canvasX X position in canvas coordinates + * @param canvasY Y position in canvas coordinates + * @returns The compass corner the point is in, otherwise `undefined`. + */ + findResizeDirection( + canvasX: number, + canvasY: number + ): CompassCorners | undefined { + if (this.resizable === false) return + + const { boundingRect } = this + if (!boundingRect.containsXy(canvasX, canvasY)) return + + // Check corners first (they take priority over edges) + return boundingRect.findContainingCorner( + canvasX, + canvasY, + LGraphNode.resizeHandleSize + ) + } + + /** + * returns all the info available about a property of this node. + * @param property name of the property + * @returns the object with all the available info + */ + getPropertyInfo(property: string) { + let info = null + + // there are several ways to define info about a property + // legacy mode + const { properties_info } = this + if (properties_info) { + for (const propInfo of properties_info) { + if (propInfo.name == property) { + info = propInfo + break + } + } + } + // litescene mode using the constructor + // @ts-expect-error deprecated https://github.com/Comfy-Org/litegraph.js/issues/639 + if (this.constructor[`@${property}`]) + // @ts-expect-error deprecated https://github.com/Comfy-Org/litegraph.js/issues/639 + info = this.constructor[`@${property}`] + + if (this.constructor.widgets_info?.[property]) + info = this.constructor.widgets_info[property] + + // litescene mode using the constructor + if (!info && this.onGetPropertyInfo) { + info = this.onGetPropertyInfo(property) + } + + info ||= {} + info.type ||= typeof this.properties[property] + if (info.widget == 'combo') info.type = 'enum' + + return info + } + + /** + * Defines a widget inside the node, it will be rendered on top of the node, you can control lots of properties + * @param type the widget type + * @param name the text to show on the widget + * @param value the default value + * @param callback function to call when it changes (optionally, it can be the name of the property to modify) + * @param options the object that contains special properties of this widget + * @returns the created widget object + */ + addWidget< + Type extends TWidgetType, + TValue extends WidgetTypeMap[Type]['value'] + >( + type: Type, + name: string, + value: TValue, + callback: IBaseWidget['callback'] | string | null, + options?: IWidgetOptions | string + ): WidgetTypeMap[Type] | IBaseWidget { + this.widgets ||= [] + + if (!options && callback && typeof callback === 'object') { + options = callback + callback = null + } + + // options can be the property name + options ||= {} + if (typeof options === 'string') options = { property: options } + + // callback can be the property name + if (callback && typeof callback === 'string') { + options.property = callback + callback = null + } + + const w: IBaseWidget & { type: Type } = { + // @ts-expect-error - Type casting for widget type property + type: type.toLowerCase(), + name: name, + value: value, + callback: typeof callback !== 'function' ? undefined : callback, + options, + y: 0 + } + + if (w.options.y !== undefined) { + w.y = w.options.y + } + + if (!callback && !w.options.callback && !w.options.property) { + console.warn( + 'LiteGraph addWidget(...) without a callback or property assigned' + ) + } + if (type == 'combo' && !w.options.values) { + throw "LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }" + } + + const widget = this.addCustomWidget(w) + this.expandToFitContent() + return widget + } + + addCustomWidget( + custom_widget: TPlainWidget + ): TPlainWidget | WidgetTypeMap[TPlainWidget['type']] { + this.widgets ||= [] + const widget = toConcreteWidget(custom_widget, this, false) ?? custom_widget + this.widgets.push(widget) + this._widgetSlotsDirty = true + + // Only register with store if node has a valid ID (is already in a graph). + // If the node isn't in a graph yet (id === -1), registration happens + // when the node is added via LGraph.add() -> node.onAdded. + if (this.id !== UNASSIGNED_NODE_ID && isNodeBindable(widget)) { + widget.setNodeId(this.id) + } + + return widget + } + + addTitleButton(options: LGraphButtonOptions): LGraphButton { + this.title_buttons ||= [] + const button = new LGraphButton(options) + this.title_buttons.push(button) + return button + } + + onTitleButtonClick(button: LGraphButton, canvas: LGraphCanvas): void { + // Dispatch event for button click + canvas.dispatch('litegraph:node-title-button-clicked', { + node: this, + button: button + }) + } + + removeWidget(widget: IBaseWidget): void { + if (!this.widgets) + throw new Error('removeWidget called on node without widgets') + + const widgetIndex = this.widgets.indexOf(widget) + if (widgetIndex === -1) throw new Error('Widget not found on this node') + + // Clean up slot references to prevent memory leaks + if (this.inputs) { + for (const input of this.inputs) { + if (input._widget === widget) { + input._widget = undefined + input.widget = undefined + input.pos = undefined + } + } + } + this._widgetSlotsDirty = true + + widget.onRemove?.() + this.widgets.splice(widgetIndex, 1) + } + + ensureWidgetRemoved(widget: IBaseWidget): void { + try { + this.removeWidget(widget) + } catch (error) { + console.error('Failed to remove widget', error) + } + } + + move(deltaX: number, deltaY: number): void { + if (this.pinned) return + + // If Vue nodes mode is enabled, skip LiteGraph's direct position update + // The layout store will handle the movement and sync back to LiteGraph + if (LiteGraph.vueNodesMode) { + // Vue nodes handle their own dragging through the layout store + // This prevents the snap-back issue from conflicting position updates + return + } + + this.pos = [this._pos[0] + deltaX, this._pos[1] + deltaY] + } + + /** + * Internal method to measure the node for rendering. Prefer {@link boundingRect} where possible. + * + * Populates {@link out} with the results in graph space. + * Populates {@link _collapsed_width} with the collapsed width if the node is collapsed. + * Adjusts for title and collapsed status, but does not call {@link onBounding}. + * @param out `x, y, width, height` are written to this array. + * @param ctx The canvas context to use for measuring text. + */ + measure(out: Rect, ctx?: CanvasRenderingContext2D): void { + const titleMode = this.title_mode + const renderTitle = + titleMode != TitleMode.TRANSPARENT_TITLE && + titleMode != TitleMode.NO_TITLE + const titleHeight = renderTitle ? LiteGraph.NODE_TITLE_HEIGHT : 0 + + out[0] = this.pos[0] + out[1] = this.pos[1] + -titleHeight + // In Vue mode, `this.size` is kept in sync with the DOM-measured + // collapsed dimensions via ResizeObserver → layoutStore → useLayoutSync, + // so the expanded branch produces correct bounds for collapsed nodes too. + if (!this.flags?.collapsed || LiteGraph.vueNodesMode) { + out[2] = this.size[0] + out[3] = this.size[1] + titleHeight + } else { + if (ctx) ctx.font = this.innerFontStyle + this._collapsed_width = Math.min( + this.size[0], + ctx + ? cachedMeasureText(ctx, this.getTitle() ?? '') + + LiteGraph.NODE_TITLE_HEIGHT * 2 + : 0 + ) + out[2] = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH + out[3] = LiteGraph.NODE_TITLE_HEIGHT + } + } + + /** + * returns the bounding of the object, used for rendering purposes + * @param out {Rect?} [optional] a place to store the output, to free garbage + * @param includeExternal {boolean?} [optional] set to true to + * include the shadow and connection points in the bounding calculation + * @returns the bounding box in format of [topleft_cornerx, topleft_cornery, width, height] + */ + getBounding(out?: Rect, includeExternal?: boolean): Rect { + out ||= [0, 0, 0, 0] + + const rect = includeExternal ? this.renderArea : this.boundingRect + out[0] = rect[0] + out[1] = rect[1] + out[2] = rect[2] + out[3] = rect[3] + + return out + } + + /** + * Calculates the render area of this node, populating both {@link boundingRect} and {@link renderArea}. + * Called automatically at the start of every frame. + */ + updateArea(ctx?: CanvasRenderingContext2D): void { + const bounds = this._boundingRect + this.measure(bounds, ctx) + this.onBounding?.(bounds) + + const renderArea = this._renderArea + renderArea.set(bounds) + // 4 offset for collapsed node connection points + renderArea[0] -= 4 + renderArea[1] -= 4 + // Add shadow & left offset + renderArea[2] += 6 + 4 + // Add shadow & top offsets + renderArea[3] += 5 + 4 + } + + /** + * checks if a point is inside the shape of a node + */ + isPointInside(x: number, y: number): boolean { + if (isInRect(x, y, this.boundingRect)) return true + + for (const badge of this.badges.map(toValue).filter((b) => b.onClick)) { + if (isInRect(x - this.pos[0], y - this.pos[1], badge.boundingRect)) + return true + } + return false + } + + /** + * Checks if the provided point is inside this node's collapse button area. + * @param x X co-ordinate to check + * @param y Y co-ordinate to check + * @returns true if the x,y point is in the collapse button area, otherwise false + */ + isPointInCollapse(x: number, y: number): boolean { + const squareLength = LiteGraph.NODE_TITLE_HEIGHT + return isInRectangle( + x, + y, + this.pos[0], + this.pos[1] - squareLength, + squareLength, + squareLength + ) + } + + /** + * Returns the input slot at the given position. Uses full 20 height, and approximates the label length. + * @param pos The graph co-ordinates to check + * @returns The input slot at the given position if found, otherwise `undefined`. + */ + getInputOnPos(pos: Point): INodeInputSlot | undefined { + return getNodeInputOnPos(this, pos[0], pos[1])?.input + } + + /** + * Returns the output slot at the given position. Uses full 20x20 box for the slot. + * @param pos The graph co-ordinates to check + * @returns The output slot at the given position if found, otherwise `undefined`. + */ + getOutputOnPos(pos: Point): INodeOutputSlot | undefined { + return getNodeOutputOnPos(this, pos[0], pos[1])?.output + } + + /** + * Returns the input or output slot at the given position. + * + * Tries {@link getNodeInputOnPos} first, then {@link getNodeOutputOnPos}. + * @param pos The graph co-ordinates to check + * @returns The input or output slot at the given position if found, otherwise `undefined`. + */ + getSlotOnPos(pos: Point): INodeInputSlot | INodeOutputSlot | undefined { + if (!isPointInRect(pos, this.boundingRect)) return + + return this.getInputOnPos(pos) ?? this.getOutputOnPos(pos) + } + + /** + * @deprecated Use {@link getSlotOnPos} instead. + * checks if a point is inside a node slot, and returns info about which slot + * @param x + * @param y + * @returns if found the object contains { input|output: slot object, slot: number, link_pos: [x,y] } + */ + getSlotInPosition(x: number, y: number): IFoundSlot | null { + // search for inputs + const { inputs, outputs } = this + + if (inputs) { + for (const [i, input] of inputs.entries()) { + const pos = this.getInputPos(i) + if (isInRectangle(x, y, pos[0] - 10, pos[1] - 10, 20, 20)) { + return { input, slot: i, link_pos: pos } + } + } + } + + if (outputs) { + for (const [i, output] of outputs.entries()) { + const pos = this.getOutputPos(i) + if (isInRectangle(x, y, pos[0] - 10, pos[1] - 10, 20, 20)) { + return { output, slot: i, link_pos: pos } + } + } + } + + return null + } + + /** + * Gets the widget on this node at the given co-ordinates. + * @param canvasX X co-ordinate in graph space + * @param canvasY Y co-ordinate in graph space + * @returns The widget found, otherwise `null` + */ + getWidgetOnPos( + canvasX: number, + canvasY: number, + includeDisabled = false + ): IBaseWidget | undefined { + const { widgets, pos, size } = this + if (!widgets?.length) return + + const x = canvasX - pos[0] + const y = canvasY - pos[1] + const nodeWidth = size[0] + + for (const widget of widgets) { + if ( + (widget.computedDisabled && !includeDisabled) || + !this.isWidgetVisible(widget) + ) { + continue + } + + const h = + widget.computedHeight ?? + widget.computeSize?.(nodeWidth)[1] ?? + LiteGraph.NODE_WIDGET_HEIGHT + + const maybeDOMWidget = widget as { margin?: number } + const mtop = maybeDOMWidget.margin ?? -2 + const mbot = maybeDOMWidget.margin ?? 2 + const mx = maybeDOMWidget.margin ?? 6 + + const w = widget.width || nodeWidth + if ( + widget.last_y !== undefined && + isInRectangle( + x, + y, + mx, + widget.last_y + mtop, + w - 2 * mx, + h - mtop - mbot + ) + ) { + return widget + } + } + } + + /** + * Returns the input slot with a given name (used for dynamic slots), -1 if not found + * @param name the name of the slot to find + * @param returnObj if the obj itself wanted + * @returns the slot (-1 if not found) + */ + findInputSlot( + name: string, + returnObj?: TReturn + ): number + findInputSlot( + name: string, + returnObj?: TReturn + ): INodeInputSlot + findInputSlot(name: string, returnObj: boolean = false) { + const { inputs } = this + if (!inputs) return -1 + + for (const [i, input] of inputs.entries()) { + if (name == input.name) { + return !returnObj ? i : input + } + } + return -1 + } + + /** + * returns the output slot with a given name (used for dynamic slots), -1 if not found + * @param name the name of the slot to find + * @param returnObj if the obj itself wanted + * @returns the slot (-1 if not found) + */ + findOutputSlot( + name: string, + returnObj?: TReturn + ): number + findOutputSlot( + name: string, + returnObj?: TReturn + ): INodeOutputSlot + findOutputSlot(name: string, returnObj: boolean = false) { + const { outputs } = this + if (!outputs) return -1 + + for (const [i, output] of outputs.entries()) { + if (name == output.name) { + return !returnObj ? i : output + } + } + return -1 + } + + /** + * Finds the first free input slot. + * @param optsIn + * @returns The index of the first matching slot, the slot itself if returnObj is true, or -1 if not found. + */ + findInputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): number + findInputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): INodeInputSlot | -1 + findInputSlotFree(optsIn?: FindFreeSlotOptions) { + return this._findFreeSlot(this.inputs, optsIn) + } + + /** + * Finds the first free output slot. + * @param optsIn + * @returns The index of the first matching slot, the slot itself if returnObj is true, or -1 if not found. + */ + findOutputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): number + findOutputSlotFree( + optsIn?: FindFreeSlotOptions & { returnObj?: TReturn } + ): INodeOutputSlot | -1 + findOutputSlotFree(optsIn?: FindFreeSlotOptions) { + return this._findFreeSlot(this.outputs, optsIn) + } + + /** + * Finds the next free slot + * @param slots The slots to search, i.e. this.inputs or this.outputs + */ + private _findFreeSlot( + slots: TSlot[], + options?: FindFreeSlotOptions + ): TSlot | number { + const defaults = { + returnObj: false, + typesNotAccepted: [] + } + const opts = Object.assign(defaults, options || {}) + const length = slots?.length + if (!(length > 0)) return -1 + + for (let i = 0; i < length; ++i) { + const slot: TSlot & IGenericLinkOrLinks = slots[i] + if (!slot || slot.link || slot.links?.length) continue + if (opts.typesNotAccepted?.includes?.(slot.type)) continue + return !opts.returnObj ? i : slot + } + return -1 + } + + /** + * findSlotByType for INPUTS + */ + findInputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number + findInputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeInputSlot + findInputSlotByType( + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ) { + return this._findSlotByType( + this.inputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + } + + /** + * findSlotByType for OUTPUTS + */ + findOutputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number + findOutputSlotByType( + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeOutputSlot + findOutputSlotByType( + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ) { + return this._findSlotByType( + this.outputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + } + + /** + * returns the output (or input) slot with a given type, -1 if not found + * @param input use inputs instead of outputs + * @param type the type of the slot to find + * @param returnObj if the obj itself wanted + * @param preferFreeSlot if we want a free slot (if not found, will return the first of the type anyway) + * @returns the slot (-1 if not found) + */ + findSlotByType( + input: TSlot, + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number + findSlotByType( + input: TSlot, + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeInputSlot | -1 + findSlotByType( + input: TSlot, + type: ISlotType, + returnObj?: TReturn, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): INodeOutputSlot | -1 + findSlotByType( + input: boolean, + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): number | INodeOutputSlot | INodeInputSlot { + return input + ? this._findSlotByType( + this.inputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + : this._findSlotByType( + this.outputs, + type, + returnObj, + preferFreeSlot, + doNotUseOccupied + ) + } + + /** + * Finds a matching slot from those provided, returning the slot itself or its index in {@link slots}. + * @param slots Slots to search (this.inputs or this.outputs) + * @param type Type of slot to look for + * @param returnObj If true, returns the slot itself. Otherwise, the index. + * @param preferFreeSlot Prefer a free slot, but if none are found, fall back to an occupied slot. + * @param doNotUseOccupied Do not fall back to occupied slots. + * @see {findSlotByType} + * @see {findOutputSlotByType} + * @see {findInputSlotByType} + * @returns If a match is found, the slot if returnObj is true, otherwise the index. If no matches are found, -1 + */ + private _findSlotByType( + slots: TSlot[], + type: ISlotType, + returnObj?: boolean, + preferFreeSlot?: boolean, + doNotUseOccupied?: boolean + ): TSlot | number { + const length = slots?.length + if (!length) return -1 + + // Empty string and * match anything (type: 0) + if (type == '' || type == '*') type = 0 + const sourceTypes = String(type).toLowerCase().split(',') + + // Run the search + let occupiedSlot: number | TSlot | null = null + for (let i = 0; i < length; ++i) { + const slot: TSlot & IGenericLinkOrLinks = slots[i] + const destTypes = + slot.type == '0' || slot.type == '*' + ? ['0'] + : String(slot.type).toLowerCase().split(',') + + for (const sourceType of sourceTypes) { + // TODO: Remove _event_ entirely. + const source = sourceType == '_event_' ? LiteGraph.EVENT : sourceType + + for (const destType of destTypes) { + const dest = destType == '_event_' ? LiteGraph.EVENT : destType + + if (source == dest || source === '*' || dest === '*') { + if (preferFreeSlot && (slot.links?.length || slot.link != null)) { + // In case we can't find a free slot. + occupiedSlot ??= returnObj ? slot : i + continue + } + return returnObj ? slot : i + } + } + } + } + + return doNotUseOccupied ? -1 : (occupiedSlot ?? -1) + } + + /** + * Determines the slot index to connect to when attempting to connect by type. + * @param findInputs If true, searches for an input. Otherwise, an output. + * @param node The node at the other end of the connection. + * @param slotType The type of slot at the other end of the connection. + * @param options Search restrictions to adhere to. + * @see {connectByType} + * @see {connectByTypeOutput} + */ + findConnectByTypeSlot( + findInputs: boolean, + node: LGraphNode, + slotType: ISlotType, + options?: ConnectByTypeOptions + ): number | undefined { + // LEGACY: Old options names + if (options && typeof options === 'object') { + if ('firstFreeIfInputGeneralInCase' in options) + options.wildcardToTyped = !!options.firstFreeIfInputGeneralInCase + if ('firstFreeIfOutputGeneralInCase' in options) + options.wildcardToTyped = !!options.firstFreeIfOutputGeneralInCase + if ('generalTypeInCase' in options) + options.typedToWildcard = !!options.generalTypeInCase + } + const optsDef: ConnectByTypeOptions = { + createEventInCase: true, + wildcardToTyped: true, + typedToWildcard: true + } + const opts = Object.assign(optsDef, options) + + if (!this.graph) throw new NullGraphError() + + if (node && typeof node === 'number') { + const nodeById = this.graph.getNodeById(node) + if (!nodeById) return + + node = nodeById + } + const slot = node.findSlotByType(findInputs, slotType, false, true) + if (slot >= 0 && slot !== null) return slot + + // TODO: Remove or reimpl. events. WILL CREATE THE onTrigger IN SLOT + if (opts.createEventInCase && slotType == LiteGraph.EVENT) { + if (findInputs) return -1 + if (LiteGraph.do_add_triggers_slots) return node.addOnExecutedOutput() + } + + // connect to the first general output slot if not found a specific type and + if (opts.typedToWildcard) { + const generalSlot = node.findSlotByType(findInputs, 0, false, true, true) + if (generalSlot >= 0) return generalSlot + } + // connect to the first free input slot if not found a specific type and this output is general + if ( + opts.wildcardToTyped && + (slotType == 0 || slotType == '*' || slotType == '') + ) { + const opt = { typesNotAccepted: [LiteGraph.EVENT] } + const nonEventSlot = findInputs + ? node.findInputSlotFree(opt) + : node.findOutputSlotFree(opt) + if (nonEventSlot >= 0) return nonEventSlot + } + } + + /** + * Finds the first free output slot with any of the comma-delimited types in {@link type}. + * + * If no slots are free, falls back in order to: + * - The first free wildcard slot + * - The first occupied slot + * - The first occupied wildcard slot + * @param type The {@link ISlotType type} of slot to find + * @returns The index and slot if found, otherwise `undefined`. + */ + findOutputByType( + type: ISlotType + ): { index: number; slot: INodeOutputSlot } | undefined { + return findFreeSlotOfType( + this.outputs, + type, + (output) => !output.links?.length + ) + } + + /** + * Finds the first free input slot with any of the comma-delimited types in {@link type}. + * + * If no slots are free, falls back in order to: + * - The first free wildcard slot + * - The first occupied slot + * - The first occupied wildcard slot + * @param type The {@link ISlotType type} of slot to find + * @returns The index and slot if found, otherwise `undefined`. + */ + findInputByType( + type: ISlotType + ): { index: number; slot: INodeInputSlot } | undefined { + return findFreeSlotOfType( + this.inputs, + type, + (input) => + input.link == null || !!this.graph?.getLink(input.link)?._dragging + ) + } + + /** + * connect this node output to the input of another node BY TYPE + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param target_node the target node + * @param target_slotType the input slot type of the target node + * @returns the link_info is created, otherwise null + */ + connectByType( + slot: number | string, + target_node: LGraphNode, + target_slotType: ISlotType, + optsIn?: ConnectByTypeOptions + ): LLink | null { + const slotIndex = this.findConnectByTypeSlot( + true, + target_node, + target_slotType, + optsIn + ) + if (slotIndex !== undefined) + return this.connect(slot, target_node, slotIndex, optsIn?.afterRerouteId) + + // No compatible slot found - connection not possible + return null + } + + /** + * connect this node input to the output of another node BY TYPE + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param source_node the target node + * @param source_slotType the output slot type of the target node + * @returns the link_info is created, otherwise null + */ + connectByTypeOutput( + slot: number | string, + source_node: LGraphNode, + source_slotType: ISlotType, + optsIn?: ConnectByTypeOptions + ): LLink | null { + // LEGACY: Old options names + if (typeof optsIn === 'object') { + if ('firstFreeIfInputGeneralInCase' in optsIn) + optsIn.wildcardToTyped = !!optsIn.firstFreeIfInputGeneralInCase + if ('generalTypeInCase' in optsIn) + optsIn.typedToWildcard = !!optsIn.generalTypeInCase + } + const slotIndex = this.findConnectByTypeSlot( + false, + source_node, + source_slotType, + optsIn + ) + if (slotIndex !== undefined) + return source_node.connect(slotIndex, this, slot, optsIn?.afterRerouteId) + + console.error( + '[connectByType]: no way to connect type:', + source_slotType, + 'to node:', + source_node + ) + return null + } + + canConnectTo( + node: NodeLike, + toSlot: INodeInputSlot | SubgraphIO, + fromSlot: INodeOutputSlot | SubgraphIO + ) { + return ( + this.id !== node.id && + LiteGraph.isValidConnection(fromSlot.type, toSlot.type) + ) + } + + /** + * Connect an output of this node to an input of another node + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param target_node the target node + * @param target_slot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger) + * @returns the link_info is created, otherwise null + */ + connect( + slot: number | string, + target_node: LGraphNode, + target_slot: ISlotType, + afterRerouteId?: RerouteId + ): LLink | null { + // Allow legacy API support for searching target_slot by string, without mutating the input variables + let targetIndex: number | null + + const { graph, outputs } = this + if (!graph) { + // could be connected before adding it to a graph + // due to link ids being associated with graphs + console.error( + "Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them." + ) + return null + } + + // seek for the output slot + if (typeof slot === 'string') { + slot = this.findOutputSlot(slot) + if (slot == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${slot}`) + return null + } + } else if (!outputs || slot >= outputs.length) { + if (LiteGraph.debug) + console.error('Connect: Error, slot number not found') + return null + } + + if (target_node && typeof target_node === 'number') { + const nodeById = graph.getNodeById(target_node) + if (!nodeById) throw 'target node is null' + + target_node = nodeById + } + if (!target_node) throw 'target node is null' + + // avoid loopback + if (target_node == this) return null + + // you can specify the slot by name + if (typeof target_slot === 'string') { + targetIndex = target_node.findInputSlot(target_slot) + if (targetIndex == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${targetIndex}`) + return null + } + } else if (target_slot === LiteGraph.EVENT) { + // TODO: Events + if (LiteGraph.do_add_triggers_slots) { + target_node.changeMode(LGraphEventMode.ON_TRIGGER) + targetIndex = target_node.findInputSlot('onTrigger') + } else { + return null + } + } else if (typeof target_slot === 'number') { + targetIndex = target_slot + } else { + targetIndex = 0 + } + + // Allow target node to change slot + if (target_node.onBeforeConnectInput) { + // This way node can choose another slot (or make a new one?) + const requestedIndex = target_node.onBeforeConnectInput( + targetIndex, + target_slot + ) + targetIndex = typeof requestedIndex === 'number' ? requestedIndex : null + } + + if ( + targetIndex === null || + !target_node.inputs || + targetIndex >= target_node.inputs.length + ) { + if (LiteGraph.debug) + console.error('Connect: Error, slot number not found') + return null + } + + const input = target_node.inputs[targetIndex] + const output = outputs[slot] + + if (!output) return null + + if (output.links?.length) { + if ( + output.type === LiteGraph.EVENT && + !LiteGraph.allow_multi_output_for_events + ) { + graph.beforeChange() + this.disconnectOutput(slot) + } + } + + const link = this.connectSlots(output, target_node, input, afterRerouteId) + return link ?? null + } + + /** + * Connect two slots between two nodes + * @param output The output slot to connect + * @param inputNode The node that the input slot is on + * @param input The input slot to connect + * @param afterRerouteId The reroute ID to use for the link + * @returns The link that was created, or null if the connection was blocked + */ + connectSlots( + output: INodeOutputSlot, + inputNode: LGraphNode, + input: INodeInputSlot, + afterRerouteId: RerouteId | undefined + ): LLink | null | undefined { + const { graph } = this + if (!graph) throw new NullGraphError() + + const layoutMutations = useLayoutMutations() + + const outputIndex = this.outputs.indexOf(output) + if (outputIndex === -1) { + console.warn('connectSlots: output not found') + return + } + const inputIndex = inputNode.inputs.indexOf(input) + if (inputIndex === -1) { + console.warn('connectSlots: input not found') + return + } + + // check targetSlot and check connection types + if (!LiteGraph.isValidConnection(output.type, input.type)) { + this.setDirtyCanvas(false, true) + return null + } + + // Allow nodes to block connection + if ( + inputNode.onConnectInput?.( + inputIndex, + output.type, + output, + this, + outputIndex + ) === false + ) + return null + if ( + this.onConnectOutput?.( + outputIndex, + input.type, + input, + inputNode, + inputIndex + ) === false + ) + return null + + // if there is something already plugged there, disconnect + if (inputNode.inputs[inputIndex]?.link != null) { + graph.beforeChange() + inputNode.disconnectInput(inputIndex, true) + } + + const maybeCommonType = + input.type && output.type && commonType(input.type, output.type) + + const linkId = toLinkId(Number(graph.state.lastLinkId) + 1) + graph.state.lastLinkId = linkId + + const link = new LLink( + linkId, + maybeCommonType || input.type || output.type, + this.id, + outputIndex, + inputNode.id, + inputIndex, + afterRerouteId + ) + + // add to graph links list + graph._links.set(link.id, link) + + // Register link in Layout Store for spatial tracking + layoutMutations.setSource(LayoutSource.Canvas) + layoutMutations.createLink( + link.id, + this.id, + outputIndex, + inputNode.id, + inputIndex + ) + + // connect in output + output.links ??= [] + output.links.push(link.id) + // connect in input + const targetInput = inputNode.inputs[inputIndex] + targetInput.link = link.id + if (targetInput.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: inputNode.id, + slotType: NodeSlotType.INPUT, + slotIndex: inputIndex, + connected: true, + linkId: link.id + }) + } + + // Reroutes + const reroutes = LLink.getReroutes(graph, link) + for (const reroute of reroutes) { + reroute.linkIds.add(link.id) + if (reroute.floating) reroute.floating = undefined + reroute._dragging = undefined + } + + // If this is the terminus of a floating link, remove it + const lastReroute = reroutes.at(-1) + if (lastReroute) { + for (const linkId of lastReroute.floatingLinkIds) { + const link = graph.floatingLinks.get(linkId) + if (link?.parentId === lastReroute.id) { + graph.removeFloatingLink(link) + } + } + } + graph.incrementVersion() + + // link has been created now, so its updated + this.onConnectionsChange?.( + NodeSlotType.OUTPUT, + outputIndex, + true, + link, + output + ) + + inputNode.onConnectionsChange?.( + NodeSlotType.INPUT, + inputIndex, + true, + link, + input + ) + + this.setDirtyCanvas(false, true) + graph.afterChange() + + return link + } + + connectFloatingReroute( + pos: Point, + slot: INodeInputSlot | INodeOutputSlot, + afterRerouteId?: RerouteId + ): Reroute { + const { graph, id } = this + if (!graph) throw new NullGraphError() + + // Assertion: It's either there or it isn't. + const inputIndex = this.inputs.indexOf(slot as INodeInputSlot) + const outputIndex = this.outputs.indexOf(slot as INodeOutputSlot) + if (inputIndex === -1 && outputIndex === -1) throw new Error('Invalid slot') + + const slotType = outputIndex === -1 ? 'input' : 'output' + + const reroute = graph.setReroute({ + pos, + parentId: afterRerouteId, + linkIds: [], + floating: { slotType } + }) + + const parentReroute = graph.getReroute(afterRerouteId) + const fromLastFloatingReroute = + parentReroute?.floating?.slotType === 'output' + + // Adding from an output, or a floating reroute that is NOT the tip of an existing floating chain + if (afterRerouteId == null || !fromLastFloatingReroute) { + const link = new LLink( + toLinkId(-1), + slot.type, + outputIndex === -1 ? -1 : id, + outputIndex, + inputIndex === -1 ? -1 : id, + inputIndex + ) + link.parentId = reroute.id + graph.addFloatingLink(link) + return reroute + } + + // Adding a new floating reroute from the tip of a floating chain. + if (!parentReroute) + throw new Error('[connectFloatingReroute] Parent reroute not found') + + const link = parentReroute.getFloatingLinks('output')?.[0] + if (!link) + throw new Error('[connectFloatingReroute] Floating link not found') + + reroute.floatingLinkIds.add(link.id) + link.parentId = reroute.id + parentReroute.floating = undefined + return reroute + } + + /** + * disconnect one output to an specific node + * @param slot (could be the number of the slot or the string with the name of the slot) + * @param target_node the target node to which this slot is connected [Optional, + * if not target_node is specified all nodes will be disconnected] + * @returns if it was disconnected successfully + */ + disconnectOutput(slot: string | number, target_node?: LGraphNode): boolean { + if (typeof slot === 'string') { + slot = this.findOutputSlot(slot) + if (slot == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${slot}`) + return false + } + } else if (!this.outputs || slot >= this.outputs.length) { + if (LiteGraph.debug) + console.error('Connect: Error, slot number not found') + return false + } + + // get output slot + const output = this.outputs[slot] + if (!output) return false + + if (output._floatingLinks) { + for (const link of output._floatingLinks) { + if (link.hasOrigin(this.id, slot)) { + this.graph?.removeFloatingLink(link) + } + } + } + + if (!output.links || output.links.length == 0) return false + const { links } = output + + // one of the output links in this slot + const graph = this.graph + if (!graph) throw new NullGraphError() + + if (target_node) { + const target = + typeof target_node === 'number' + ? graph.getNodeById(target_node) + : target_node + if (!target) throw 'Target Node not found' + + for (const [i, link_id] of links.entries()) { + const link_info = graph._links.get(link_id) + if (link_info?.target_id != target.id) continue + + // is the link we are searching for... + // remove here + links.splice(i, 1) + const input = target.inputs[link_info.target_slot] + // remove there + input.link = null + if (input.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: target.id, + slotType: NodeSlotType.INPUT, + slotIndex: link_info.target_slot, + connected: false, + linkId: link_info.id + }) + } + + // remove the link from the links pool + link_info.disconnect(graph, 'input') + graph.incrementVersion() + + // link_info hasn't been modified so its ok + target.onConnectionsChange?.( + NodeSlotType.INPUT, + link_info.target_slot, + false, + link_info, + input + ) + this.onConnectionsChange?.( + NodeSlotType.OUTPUT, + slot, + false, + link_info, + output + ) + + break + } + } else { + // all the links in this output slot + for (const link_id of links) { + const link_info = graph._links.get(link_id) + if (!link_info) continue + if ( + link_info.target_id === SUBGRAPH_OUTPUT_ID && + graph instanceof Subgraph + ) { + const targetSlot = graph.outputNode.slots[link_info.target_slot] + if (targetSlot) { + targetSlot.linkIds.length = 0 + } else { + console.error('Missing subgraphOutput slot when disconnecting link') + } + } + + const target = graph.getNodeById(link_info.target_id) + graph.incrementVersion() + + if (target) { + const input = target.inputs[link_info.target_slot] + // remove other side link + input.link = null + if (input.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: target.id, + slotType: NodeSlotType.INPUT, + slotIndex: link_info.target_slot, + connected: false, + linkId: link_info.id + }) + } + + // link_info hasn't been modified so its ok + target.onConnectionsChange?.( + NodeSlotType.INPUT, + link_info.target_slot, + false, + link_info, + input + ) + } + // remove the link from the links pool + link_info.disconnect(graph, 'input') + + this.onConnectionsChange?.( + NodeSlotType.OUTPUT, + slot, + false, + link_info, + output + ) + } + output.links = null + } + + this.setDirtyCanvas(false, true) + return true + } + + /** + * Disconnect one input + * @param slot Input slot index, or the name of the slot + * @param keepReroutes If `true`, reroutes will not be garbage collected. + * @returns true if disconnected successfully or already disconnected, otherwise false + */ + disconnectInput(slot: number | string, keepReroutes?: boolean): boolean { + // Allow search by string + if (typeof slot === 'string') { + slot = this.findInputSlot(slot) + if (slot == -1) { + if (LiteGraph.debug) + console.error(`Connect: Error, no slot of name ${slot}`) + return false + } + } else if (!this.inputs || slot >= this.inputs.length) { + if (LiteGraph.debug) { + console.error('Connect: Error, slot number not found') + } + return false + } + + const input = this.inputs[slot] + if (!input) { + console.error('disconnectInput: input not found', slot, this.inputs) + return false + } + + const { graph } = this + if (!graph) throw new NullGraphError() + + // Break floating links + if (input._floatingLinks?.size) { + for (const link of input._floatingLinks) { + graph.removeFloatingLink(link) + } + } + + const link_id = this.inputs[slot].link + if (link_id != null) { + this.inputs[slot].link = null + if (input.widget) { + graph.trigger('node:slot-links:changed', { + nodeId: this.id, + slotType: NodeSlotType.INPUT, + slotIndex: slot, + connected: false, + linkId: link_id + }) + } + + // remove other side + const link_info = graph._links.get(link_id) + if (link_info) { + // Let SubgraphInput do the disconnect. + if (link_info.origin_id === SUBGRAPH_INPUT_ID && 'inputNode' in graph) { + graph.inputNode._disconnectNodeInput(this, input, link_info) + return true + } + + const target_node = graph.getNodeById(link_info.origin_id) + if (!target_node) { + console.error( + 'disconnectInput: output not found', + link_info.origin_slot + ) + return false + } + + const output = target_node.outputs[link_info.origin_slot] + if (!output?.links?.length) { + // Output not found - may have been removed + return false + } + + // search in the inputs list for this link + let i = 0 + for (const l = output.links.length; i < l; i++) { + if (output.links[i] == link_id) { + output.links.splice(i, 1) + break + } + } + + link_info.disconnect(graph, keepReroutes ? 'output' : undefined) + if (graph) graph.incrementVersion() + + this.onConnectionsChange?.( + NodeSlotType.INPUT, + slot, + false, + link_info, + input + ) + target_node.onConnectionsChange?.( + NodeSlotType.OUTPUT, + i, + false, + link_info, + output + ) + } + } + + this.setDirtyCanvas(false, true) + return true + } + + /** + * @deprecated Use {@link getInputPos} or {@link getOutputPos} instead. + * returns the center of a connection point in canvas coords + * @param is_input true if if a input slot, false if it is an output + * @param slot_number (could be the number of the slot or the string with the name of the slot) + * @param out [optional] a place to store the output, to free garbage + * @returns the position + */ + getConnectionPos(is_input: boolean, slot_number: number, out?: Point): Point { + out ||= [0, 0] + + const { + pos: [nodeX, nodeY], + inputs, + outputs + } = this + + if (this.flags.collapsed) { + const w = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH + out[0] = is_input ? nodeX : nodeX + w + out[1] = nodeY - LiteGraph.NODE_TITLE_HEIGHT * 0.5 + return out + } + + // weird feature that never got finished + if (is_input && slot_number == -1) { + out[0] = nodeX + LiteGraph.NODE_TITLE_HEIGHT * 0.5 + out[1] = nodeY + LiteGraph.NODE_TITLE_HEIGHT * 0.5 + return out + } + + // hard-coded pos + const inputPos = inputs?.[slot_number]?.pos + const outputPos = outputs?.[slot_number]?.pos + + if (is_input && inputPos) { + out[0] = nodeX + inputPos[0] + out[1] = nodeY + inputPos[1] + return out + } else if (!is_input && outputPos) { + out[0] = nodeX + outputPos[0] + out[1] = nodeY + outputPos[1] + return out + } + + // default vertical slots + const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5 + const slotIndex = is_input + ? this._defaultVerticalInputs.indexOf(this.inputs[slot_number]) + : this._defaultVerticalOutputs.indexOf(this.outputs[slot_number]) + + out[0] = is_input ? nodeX + offset : nodeX + this.size[0] + 1 - offset + out[1] = + nodeY + + (slotIndex + 0.7) * LiteGraph.NODE_SLOT_HEIGHT + + (this.constructor.slot_start_y || 0) + return out + } + + /** + * @internal The inputs that are not positioned with absolute coordinates. + */ + private get _defaultVerticalInputs() { + return this.inputs.filter( + (slot) => !slot.pos && !(this.widgets?.length && isWidgetInputSlot(slot)) + ) + } + + /** + * @internal The outputs that are not positioned with absolute coordinates. + */ + private get _defaultVerticalOutputs() { + return this.outputs.filter((slot: INodeOutputSlot) => !slot.pos) + } + + /** + * Get the context needed for slot position calculations + * @internal + */ + private _getSlotPositionContext(): SlotPositionContext { + return { + nodeX: this.pos[0], + nodeY: this.pos[1], + nodeWidth: this.size[0], + nodeHeight: this.size[1], + collapsed: this.flags.collapsed ?? false, + collapsedWidth: this._collapsed_width, + slotStartY: this.constructor.slot_start_y, + inputs: this.inputs, + outputs: this.outputs, + widgets: this.widgets + } + } + + /** + * Gets the position of an input slot, in graph co-ordinates. + * + * This method is preferred over the legacy {@link getConnectionPos} method. + * @param slot Input slot index + * @returns Position of the input slot + */ + getInputPos(slot: number): Point { + return getSlotPosition(this, slot, true) + } + + /** + * Gets the position of an input slot, in graph co-ordinates. + * @param input The actual node input object + * @returns Position of the centre of the input slot in graph co-ordinates. + */ + getInputSlotPos(input: INodeInputSlot): Point { + return calculateInputSlotPosFromSlot(this._getSlotPositionContext(), input) + } + + /** + * Gets the position of an output slot, in graph co-ordinates. + * + * This method is preferred over the legacy {@link getConnectionPos} method. + * @param outputSlotIndex Output slot index + * @returns Position of the output slot + */ + getOutputPos(outputSlotIndex: SlotIndex): Point { + return getSlotPosition(this, outputSlotIndex, false) + } + + /** + * Get slot position using layout tree if available, fallback to node's position * Unified implementation used by both LitegraphLinkAdapter and useLinkLayoutSync + * @param slotIndex The slot index + * @param isInput Whether this is an input slot + * @returns Position of the slot center in graph coordinates + */ + getSlotPosition(slotIndex: number, isInput: boolean): Point { + return getSlotPosition(this, slotIndex, isInput) + } + + /** @inheritdoc */ + snapToGrid(snapTo: number): boolean { + return this.pinned ? false : snapPoint(this.pos, snapTo) + } + + /** @see {@link snapToGrid} */ + alignToGrid(): void { + this.snapToGrid(LiteGraph.CANVAS_GRID_SIZE) + } + + /* Console output */ + trace(msg: string): void { + this.console ||= [] + this.console.push(msg) + // @ts-expect-error deprecated + if (this.console.length > LGraphNode.MAX_CONSOLE) this.console.shift() + } + + /* Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */ + setDirtyCanvas(dirty_foreground: boolean, dirty_background?: boolean): void { + this.graph?.canvasAction((c) => + c.setDirty(dirty_foreground, dirty_background) + ) + } + + loadImage(url: string): HTMLImageElement { + interface AsyncImageElement extends HTMLImageElement { + ready?: boolean + } + + const img: AsyncImageElement = new Image() + img.src = LiteGraph.node_images_path + url + img.ready = false + + const dirty = () => this.setDirtyCanvas(true) + img.addEventListener('load', function (this: AsyncImageElement) { + this.ready = true + dirty() + }) + return img + } + + /** + * Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus + * @deprecated Use {@link LGraphCanvas.pointer} instead. + */ + captureInput(v: boolean): void { + warnDeprecated( + '[DEPRECATED] captureInput will be removed in a future version. Please use LGraphCanvas.pointer (CanvasPointer) instead.' + ) + if (!this.graph || !this.graph.list_of_graphcanvas) return + + const list = this.graph.list_of_graphcanvas + + for (const c of list) { + // releasing somebody elses capture?! + if (!v && c.node_capturing_input != this) continue + + // change + c.node_capturing_input = v ? this : null + } + } + + get collapsed() { + return !!this.flags.collapsed + } + + get collapsible() { + return !this.pinned && this.constructor.collapsable !== false + } + + /** + * Toggle node collapse (makes it smaller on the canvas) + */ + collapse(force?: boolean): void { + if (!this.collapsible && !force) return + if (!this.graph) throw new NullGraphError() + this.graph.incrementVersion() + this.flags.collapsed = !this.flags.collapsed + this.setDirtyCanvas(true, true) + } + + /** + * Toggles advanced mode of the node, showing advanced widgets + */ + toggleAdvanced() { + if (!this.hasAdvancedWidgets()) return + if (!this.graph) throw new NullGraphError() + this.graph.incrementVersion() + this.showAdvanced = !this.showAdvanced + this.expandToFitContent() + this.setDirtyCanvas(true, true) + } + + get pinned() { + return !!this.flags.pinned + } + + /** + * Prevents the node being accidentally moved or resized by mouse interaction. + * Toggles pinned state if no value is provided. + */ + pin(v?: boolean): void { + if (!this.graph) throw new NullGraphError() + + this.graph.incrementVersion() + this.flags.pinned = v ?? !this.flags.pinned + this.resizable = !this.pinned + if (!this.pinned) this.flags.pinned = undefined + } + + unpin(): void { + this.pin(false) + } + + localToScreen(x: number, y: number, dragAndScale: DragAndScale): Point { + return [ + (x + this.pos[0]) * dragAndScale.scale + dragAndScale.offset[0], + (y + this.pos[1]) * dragAndScale.scale + dragAndScale.offset[1] + ] + } + + get width() { + return this.collapsed + ? this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH + : this.size[0] + } + + /** + * Returns the height of the node, including the title bar. + */ + get height() { + return LiteGraph.NODE_TITLE_HEIGHT + this.bodyHeight + } + + /** + * Returns the height of the node, excluding the title bar. + */ + get bodyHeight() { + return this.collapsed ? 0 : this.size[1] + } + + drawBadges(ctx: CanvasRenderingContext2D, { gap = 2 } = {}): void { + const badgeInstances = this.badges.map((badge) => + badge instanceof LGraphBadge ? badge : badge() + ) + const isLeftAligned = this.badgePosition === BadgePosition.TopLeft + + let currentX = isLeftAligned + ? 0 + : this.width - + badgeInstances.reduce( + (acc, badge) => acc + badge.getWidth(ctx) + gap, + 0 + ) + const y = -(LiteGraph.NODE_TITLE_HEIGHT + gap) + + for (const badge of badgeInstances) { + badge.draw(ctx, currentX, y - badge.height) + currentX += badge.getWidth(ctx) + gap + } + } + + /** + * Renders the node's title bar background + */ + drawTitleBarBackground( + ctx: CanvasRenderingContext2D, + { + scale, + title_height = LiteGraph.NODE_TITLE_HEIGHT, + low_quality = false + }: DrawTitleOptions + ): void { + const fgcolor = this.renderingColor + const shape = this.renderingShape + const size = this.renderingSize + + if (this.onDrawTitleBar) { + this.onDrawTitleBar(ctx, title_height, size, scale, fgcolor) + return + } + + if (this.title_mode === TitleMode.TRANSPARENT_TITLE) { + return + } + + if (this.collapsed) { + ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR + } + + ctx.fillStyle = this.constructor.title_color || fgcolor + ctx.beginPath() + + if (shape == RenderShape.BOX || low_quality) { + ctx.rect(0, -title_height, size[0], title_height) + } else if (shape == RenderShape.ROUND || shape == RenderShape.CARD) { + ctx.roundRect( + 0, + -title_height, + size[0], + title_height, + this.collapsed + ? [LiteGraph.ROUND_RADIUS] + : [LiteGraph.ROUND_RADIUS, LiteGraph.ROUND_RADIUS, 0, 0] + ) + } + ctx.fill() + ctx.shadowColor = 'transparent' + } + + /** + * Renders the node's title box, i.e. the dot in front of the title text that + * when clicked toggles the node's collapsed state. The term `title box` comes + * from the original LiteGraph implementation. + */ + drawTitleBox( + ctx: CanvasRenderingContext2D, + { + scale, + low_quality = false, + title_height = LiteGraph.NODE_TITLE_HEIGHT, + box_size = 10 + }: DrawTitleBoxOptions + ): void { + const size = this.renderingSize + const shape = this.renderingShape + + if (this.onDrawTitleBox) { + this.onDrawTitleBox(ctx, title_height, size, scale) + return + } + + if ( + [RenderShape.ROUND, RenderShape.CIRCLE, RenderShape.CARD].includes(shape) + ) { + if (low_quality) { + ctx.fillStyle = 'black' + ctx.beginPath() + ctx.arc( + title_height * 0.5, + title_height * -0.5, + box_size * 0.5 + 1, + 0, + Math.PI * 2 + ) + ctx.fill() + } + + ctx.fillStyle = this.renderingBoxColor + if (low_quality) { + ctx.fillRect( + title_height * 0.5 - box_size * 0.5, + title_height * -0.5 - box_size * 0.5, + box_size, + box_size + ) + } else { + ctx.beginPath() + ctx.arc( + title_height * 0.5, + title_height * -0.5, + box_size * 0.5, + 0, + Math.PI * 2 + ) + ctx.fill() + } + } else { + if (low_quality) { + ctx.fillStyle = 'black' + ctx.fillRect( + (title_height - box_size) * 0.5 - 1, + (title_height + box_size) * -0.5 - 1, + box_size + 2, + box_size + 2 + ) + } + ctx.fillStyle = this.renderingBoxColor + ctx.fillRect( + (title_height - box_size) * 0.5, + (title_height + box_size) * -0.5, + box_size, + box_size + ) + } + } + + /** + * Renders the node's title text. + */ + drawTitleText( + ctx: CanvasRenderingContext2D, + { + scale, + default_title_color, + low_quality = false, + title_height = LiteGraph.NODE_TITLE_HEIGHT + }: DrawTitleTextOptions + ): void { + const size = this.renderingSize + const selected = this.selected + + if (this.onDrawTitleText) { + this.onDrawTitleText( + ctx, + title_height, + size, + scale, + this.titleFontStyle, + selected + ) + return + } + + // Don't render title text if low quality + if (low_quality) { + return + } + + ctx.font = this.titleFontStyle + const rawTitle = this.getTitle() ?? `❌ ${this.type}` + const title = String(rawTitle) + (this.pinned ? '📌' : '') + if (title) { + if (selected) { + ctx.fillStyle = LiteGraph.NODE_SELECTED_TITLE_COLOR + } else { + ctx.fillStyle = this.constructor.title_text_color || default_title_color + } + + // Calculate available width for title + let availableWidth = size[0] - title_height * 2 // Basic margins + + // Subtract space for title buttons + if (this.title_buttons?.length > 0) { + let buttonsWidth = 0 + const savedFont = ctx.font // Save current font + for (const button of this.title_buttons) { + if (button.visible) { + buttonsWidth += button.getWidth(ctx) + 2 // button width + gap + } + } + ctx.font = savedFont // Restore font after button measurements + if (buttonsWidth > 0) { + buttonsWidth -= 20 // Reduce by empty padding + availableWidth -= buttonsWidth + } + } + + // Truncate title if needed + let displayTitle = title + + if (this.collapsed) { + // For collapsed nodes, limit to 20 chars as before + displayTitle = title.substr(0, 20) + } else if (availableWidth > 0) { + // For regular nodes, truncate based on available width + displayTitle = truncateText(ctx, title, availableWidth) + } + + ctx.textAlign = 'left' + ctx.fillText( + displayTitle, + title_height, + LiteGraph.NODE_TITLE_TEXT_Y - title_height + ) + } + } + + /** + * Attempts to gracefully bypass this node in all of its connections by reconnecting all links. + * + * Each input is checked against each output. This is done on a matching index basis, i.e. input 3 -> output 3. + * If there are any input links remaining, + * and {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `true`, + * each input will check for outputs that match, and take the first one that matches + * `true`: Try the index matching first, then every input to every output. + * `false`: Only matches indexes, e.g. input 3 to output 3. + * + * If {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `undefined`, it will fall back to + * the static {@link keepAllLinksOnBypass}. + * @returns `true` if any new links were established, otherwise `false`. + * @todo Decision: Change API to return array of new links instead? + */ + connectInputToOutput(): boolean | undefined { + const { inputs, outputs, graph } = this + if (!inputs || !outputs) return + if (!graph) throw new NullGraphError() + + const { _links } = graph + let madeAnyConnections = false + + // First pass: only match exactly index-to-index + for (const [index, input] of inputs.entries()) { + if (input.link == null) continue + + const output = outputs[index] + if (!output || !LiteGraph.isValidConnection(input.type, output.type)) + continue + + const inLink = _links.get(input.link) + if (!inLink) continue + const inNode = graph.getNodeById(inLink?.origin_id) + if (!inNode) continue + + bypassAllLinks(output, inNode, inLink, graph) + } + // Configured to only use index-to-index matching + if (!(this.flags.keepAllLinksOnBypass ?? LGraphNode.keepAllLinksOnBypass)) + return madeAnyConnections + + // Second pass: match any remaining links + for (const input of inputs) { + if (input.link == null) continue + + const inLink = _links.get(input.link) + if (!inLink) continue + const inNode = graph.getNodeById(inLink?.origin_id) + if (!inNode) continue + + for (const output of outputs) { + if (!LiteGraph.isValidConnection(input.type, output.type)) continue + + bypassAllLinks(output, inNode, inLink, graph) + break + } + } + return madeAnyConnections + + function bypassAllLinks( + output: INodeOutputSlot, + inNode: LGraphNode, + inLink: LLink, + graph: LGraph + ) { + const outLinks = output.links + ?.map((x) => _links.get(x)) + .filter((x) => !!x) + if (!outLinks?.length) return + + for (const outLink of outLinks) { + const outNode = graph.getNodeById(outLink.target_id) + if (!outNode) continue + + const result = inNode.connect( + inLink.origin_slot, + outNode, + outLink.target_slot, + inLink.parentId + ) + madeAnyConnections ||= !!result + } + } + } + + /** + * Returns `true` if the widget is visible, otherwise `false`. + */ + isWidgetVisible(widget: IBaseWidget): boolean { + const isHidden = + this.collapsed || widget.hidden || (widget.advanced && !this.showAdvanced) + return !isHidden + } + + /** + * Returns all widgets that should participate in layout calculations. + * Filters out hidden widgets only (not collapsed/advanced). + */ + getLayoutWidgets(): IBaseWidget[] { + return this.widgets?.filter((w) => !w.hidden) ?? [] + } + + /** + * Returns `true` if the node has any advanced widgets. + */ + hasAdvancedWidgets(): boolean { + return this.widgets?.some((w) => w.advanced) ?? false + } + + updateComputedDisabled() { + if (!this.widgets) return + for (const widget of this.widgets) + widget.computedDisabled = + widget.disabled || this.getSlotFromWidget(widget)?.link != null + } + + drawWidgets( + ctx: CanvasRenderingContext2D, + { lowQuality = false, editorAlpha = 1 }: DrawWidgetsOptions + ): void { + if (!this.widgets) return + + const nodeWidth = this.size[0] + const { widgets } = this + const H = LiteGraph.NODE_WIDGET_HEIGHT + const showText = !lowQuality + ctx.save() + ctx.globalAlpha = editorAlpha + + this.updateComputedDisabled() + for (const widget of widgets) { + if (!this.isWidgetVisible(widget)) continue + + const { y } = widget + const outlineColour = widget.advanced + ? LiteGraph.WIDGET_ADVANCED_OUTLINE_COLOR + : LiteGraph.WIDGET_OUTLINE_COLOR + + widget.last_y = y + + ctx.strokeStyle = outlineColour + ctx.fillStyle = '#222' + ctx.textAlign = 'left' + if (widget.computedDisabled) ctx.globalAlpha *= 0.5 + const width = widget.width || nodeWidth + + if (typeof widget.draw === 'function') { + widget.draw(ctx, this, width, y, H, lowQuality) + } else { + toConcreteWidget(widget, this, false)?.drawWidget(ctx, { + width, + showText + }) + } + ctx.globalAlpha = editorAlpha + } + ctx.restore() + } + + /** + * When {@link LGraphNode.collapsed} is `true`, this method draws the node's collapsed slots. + */ + drawCollapsedSlots(ctx: CanvasRenderingContext2D): void { + // Render the first connected slot only. + for (const slot of this._concreteInputs) { + if (slot.link != null) { + slot.drawCollapsed(ctx) + break + } + } + for (const slot of this._concreteOutputs) { + if (slot.links?.length) { + slot.drawCollapsed(ctx) + break + } + } + } + + get slots(): (INodeInputSlot | INodeOutputSlot)[] { + return [...this.inputs, ...this.outputs] + } + + private _measureSlot( + slot: NodeInputSlot | NodeOutputSlot, + slotIndex: number, + isInput: boolean + ): void { + const pos = isInput + ? this.getInputPos(slotIndex) + : this.getOutputPos(slotIndex) + + slot.boundingRect[0] = pos[0] - LiteGraph.NODE_SLOT_HEIGHT * 0.5 + slot.boundingRect[1] = pos[1] - LiteGraph.NODE_SLOT_HEIGHT * 0.5 + slot.boundingRect[2] = slot.isWidgetInputSlot + ? BaseWidget.margin + : LiteGraph.NODE_SLOT_HEIGHT + slot.boundingRect[3] = LiteGraph.NODE_SLOT_HEIGHT + } + + private _measureSlots(): ReadOnlyRect | null { + const slots: (NodeInputSlot | NodeOutputSlot)[] = [] + + for (const [slotIndex, slot] of this._concreteInputs.entries()) { + // Unrecognized nodes (Nodes with error) has inputs but no widgets. Treat + // converted inputs as normal inputs. + /** Widget input slots are handled in {@link layoutWidgetInputSlots} */ + if (this.widgets?.length && isWidgetInputSlot(slot)) continue + + this._measureSlot(slot, slotIndex, true) + slots.push(slot) + } + for (const [slotIndex, slot] of this._concreteOutputs.entries()) { + this._measureSlot(slot, slotIndex, false) + slots.push(slot) + } + + return slots.length ? createBounds(slots, 0) : null + } + + private _getMouseOverSlot(slot: INodeSlot): INodeSlot | null { + const isInput = isINodeInputSlot(slot) + const mouseOverId = this.mouseOver?.[isInput ? 'inputId' : 'outputId'] ?? -1 + if (mouseOverId === -1) { + return null + } + return isInput ? this.inputs[mouseOverId] : this.outputs[mouseOverId] + } + + private _isMouseOverSlot(slot: INodeSlot): boolean { + return this._getMouseOverSlot(slot) === slot + } + + private _isMouseOverWidget(widget: IBaseWidget | undefined): boolean { + if (!widget) return false + return this.mouseOver?.overWidget === widget + } + + /** + * Returns the input slot that is associated with the given widget. + */ + getSlotFromWidget( + widget: IBaseWidget | undefined + ): INodeInputSlot | undefined { + if (widget) + return this.inputs.find( + (slot) => isWidgetInputSlot(slot) && slot.widget.name === widget.name + ) + } + + /** + * Returns the widget that is associated with the given input slot. + */ + getWidgetFromSlot(slot: INodeInputSlot): IBaseWidget | undefined { + if (!isWidgetInputSlot(slot)) return + return this.widgets?.find((w) => w.name === slot.widget.name) + } + + /** + * Draws the node's input and output slots. + */ + drawSlots( + ctx: CanvasRenderingContext2D, + { fromSlot, colorContext, editorAlpha, lowQuality }: DrawSlotsOptions + ) { + for (const slot of [...this._concreteInputs, ...this._concreteOutputs]) { + const isValidTarget = fromSlot && slot.isValidTarget(fromSlot) + const isMouseOverSlot = this._isMouseOverSlot(slot) + + // change opacity of incompatible slots when dragging a connection + const isValid = !fromSlot || isValidTarget + const highlight = isValid && isMouseOverSlot + + // Show slot if it's not a widget input slot + // or if it's a widget input slot and satisfies one of the following: + // - the mouse is over the widget + // - the slot is valid during link drop + // - the slot is connected + if ( + isMouseOverSlot || + isValidTarget || + !slot.isWidgetInputSlot || + this._isMouseOverWidget(this.getWidgetFromSlot(slot)) || + slot.isConnected || + slot.alwaysVisible + ) { + ctx.globalAlpha = isValid ? editorAlpha : 0.4 * editorAlpha + slot.draw(ctx, { + colorContext, + lowQuality, + highlight + }) + } + } + } + + /** + * Arranges the node's widgets vertically. + * Sets following properties on each widget: + * - {@link IBaseWidget.computedHeight} + * - {@link IBaseWidget.y} + * @param widgetStartY The y-coordinate of the first widget + */ + private _arrangeWidgets(widgetStartY: number): void { + if (!this.widgets || !this.widgets.length) return + + const bodyHeight = this.bodyHeight + const startY = + this.widgets_start_y ?? (this.widgets_up ? 0 : widgetStartY) + 2 + + let freeSpace = bodyHeight - startY + + // Collect fixed height widgets first + let fixedWidgetHeight = 0 + const growableWidgets: { + minHeight: number + prefHeight?: number + w: IBaseWidget + }[] = [] + + const visibleWidgets = this.getLayoutWidgets() + + for (const w of visibleWidgets) { + if (w.computeSize) { + const height = w.computeSize()[1] + 4 + w.computedHeight = height + fixedWidgetHeight += height + } else if (w.computeLayoutSize) { + const { minHeight, maxHeight } = w.computeLayoutSize(this) + growableWidgets.push({ + minHeight, + prefHeight: maxHeight, + w + }) + } else { + const height = LiteGraph.NODE_WIDGET_HEIGHT + 4 + w.computedHeight = height + fixedWidgetHeight += height + } + } + + // Calculate remaining space for DOM widgets + freeSpace -= fixedWidgetHeight + this.freeWidgetSpace = freeSpace + + // Prepare space requests for distribution + const spaceRequests = growableWidgets.map((d) => ({ + minSize: d.minHeight, + maxSize: d.prefHeight + })) + + // Distribute space among DOM widgets + const allocations = distributeSpace(Math.max(0, freeSpace), spaceRequests) + + // Apply computed heights + for (const [i, d] of growableWidgets.entries()) { + d.w.computedHeight = allocations[i] + } + + // Position widgets + let y = startY + for (const w of visibleWidgets) { + w.y = y + y += w.computedHeight ?? 0 + } + + if (!this.graph) throw new NullGraphError() + + // Grow the node if necessary. + // Ref: https://github.com/Comfy-Org/ComfyUI_frontend/issues/2652 + // TODO: Move the layout logic before drawing of the node shape, so we don't + // need to trigger extra round of rendering. + // In Vue mode, the DOM is the source of truth for node sizing — the + // ResizeObserver feeds measurements back to the layout store. Allowing + // LiteGraph to also call setSize() here creates an infinite feedback loop + // (LG grows node → CSS min-height increases → textarea fills extra space → + // ResizeObserver reports larger size → LG grows node again). + if (!LiteGraph.vueNodesMode && y > bodyHeight) { + this.setSize([this.size[0], y]) + this.graph.setDirtyCanvas(false, true) + } + } + + /** + * Arranges the layout of the node's widget input slots. + */ + private _arrangeWidgetInputSlots(): void { + if (!this.widgets?.length) return + + // Build a name→widget map for fast lookup. + const widgetByName = new Map() + for (const w of this.widgets) widgetByName.set(w.name, w) + + // Set widget-backed slot positions from widget Y coordinates. + // In Vue mode, promoted widget inputs are not rendered as + // components (NodeSlots filters them out), so they have no DOM-registered + // position. input.pos serves as the fallback for getSlotPosition(). + for (const [i, slot] of this._concreteInputs.entries()) { + if (!isWidgetInputSlot(slot)) continue + + // Prefer the slot's direct _widget binding (1:1 for promoted inputs). + // Fall back to name-map lookup for regular nodes without _widget set. + // Note: the name-map is ambiguous if two promoted inputs share a label; + // _widget avoids this since it is a direct reference. + const widget = slot._widget ?? widgetByName.get(slot.widget.name) + if (!widget) continue + + const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5 + const pos: [number, number] = [offset, widget.y + offset] + slot.pos = pos + this.inputs[i].pos = pos + this._measureSlot(slot, i, true) + } + } + + /** + * @internal Sets the internal concrete slot arrays, ensuring they are instances of + * {@link NodeInputSlot} or {@link NodeOutputSlot}. + * + * A temporary workaround until duck-typed inputs and outputs + * have been removed from the ecosystem. + */ + _setConcreteSlots(): void { + this._concreteInputs = this.inputs.map((slot) => + toClass(NodeInputSlot, slot, this) + ) + this._concreteOutputs = this.outputs.map((slot) => + toClass(NodeOutputSlot, slot, this) + ) + } + + /** + * Arranges node elements in preparation for rendering (slots & widgets). + */ + arrange(): void { + const slotsBounds = this._measureSlots() + const widgetStartY = slotsBounds + ? slotsBounds[1] + slotsBounds[3] - this.pos[1] + : 0 + this._arrangeWidgets(widgetStartY) + this._arrangeWidgetInputSlots() + this._widgetSlotsDirty = false + } + + /** + * Draws a progress bar on the node. + * @param ctx The canvas context to draw on + */ + drawProgressBar(ctx: CanvasRenderingContext2D): void { + if (!this.progress) return + + const originalFillStyle = ctx.fillStyle + ctx.fillStyle = 'green' + ctx.fillRect(0, 0, this.width * this.progress, 6) + ctx.fillStyle = originalFillStyle + } +} diff --git a/docs/hel-892/setget-reference/1.48.6__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts b/docs/hel-892/setget-reference/1.48.6__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts new file mode 100644 index 00000000..35220e8b --- /dev/null +++ b/docs/hel-892/setget-reference/1.48.6__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts @@ -0,0 +1,429 @@ +import { toLinkId } from '@/types/linkId' +import type { LGraph } from '@/lib/litegraph/src/LGraph' +import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' +import type { SerializedNodeId } from '@/types/nodeId' +import type { LinkId } from '@/lib/litegraph/src/LLink' +import { InvalidLinkError } from '@/lib/litegraph/src/infrastructure/InvalidLinkError' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import { NullGraphError } from '@/lib/litegraph/src/infrastructure/NullGraphError' +import { RecursionError } from '@/lib/litegraph/src/infrastructure/RecursionError' +import { SlotIndexError } from '@/lib/litegraph/src/infrastructure/SlotIndexError' +import type { ISlotType } from '@/lib/litegraph/src/interfaces' +import { LGraphEventMode, LiteGraph } from '@/lib/litegraph/src/litegraph' + +import type { Subgraph } from './Subgraph' +import type { SubgraphNode } from './SubgraphNode' + +export type ExecutionId = string + +/** + * Interface describing the data transfer objects used when compiling a graph for execution. + */ +export type ExecutableLGraphNode = Omit< + ExecutableNodeDTO, + 'graph' | 'node' | 'subgraphNode' +> + +/** + * The end result of resolving a DTO input. + * When a widget value is returned, {@link widgetInfo} is present and {@link origin_slot} is `-1`. + */ +type ResolvedInput = { + /** DTO for the node that the link originates from. */ + node: ExecutableLGraphNode + /** Full unique execution ID of the node that the link originates from. In the case of a widget value, this is the ID of the subgraph node. */ + origin_id: ExecutionId + /** The slot index of the output on the node that the link originates from. `-1` when widget value is set. */ + origin_slot: number + /** Boxed widget value (e.g. for widgets). If this box is `undefined`, then an input link is connected, and widget values from the subgraph node are ignored. */ + widgetInfo?: { value: unknown } +} + +/** + * Concrete implementation of {@link ExecutableLGraphNode}. + * @remarks This is the class that is used to create the data transfer objects for executable nodes. + */ +export class ExecutableNodeDTO implements ExecutableLGraphNode { + applyToGraph?( + ...args: Parameters> + ): ReturnType> + + /** The graph that this node is a part of. */ + readonly graph: LGraph | Subgraph + + inputs: { linkId: LinkId | null; name: string; type: ISlotType }[] + + /** Backing field for {@link id}. */ + private _id: ExecutionId + + /** + * The path to the actual node through subgraph instances, represented as a list of all subgraph node IDs (instances), + * followed by the actual original node ID within the subgraph. Each segment is separated by `:`. + * + * e.g. `1:2:3`: + * - `1` is the node ID of the first subgraph node in the parent workflow + * - `2` is the node ID of the second subgraph node in the first subgraph + * - `3` is the node ID of the actual node in the subgraph definition + */ + get id() { + return this._id + } + + get type() { + return this.node.type + } + + get title() { + return this.node.title + } + + get mode() { + return this.node.mode + } + + get comfyClass() { + return this.node.comfyClass + } + + get isVirtualNode() { + return this.node.isVirtualNode + } + + get widgets() { + return this.node.widgets + } + + get subgraphId() { + return this.subgraphNode?.subgraph.id + } + + constructor( + /** The actual node that this DTO wraps. */ + readonly node: LGraphNode | SubgraphNode, + /** A list of subgraph instance node IDs from the root graph to the containing instance. @see {@link id} */ + readonly subgraphNodePath: readonly SerializedNodeId[], + /** A flattened map of all DTOs in this node network. Subgraph instances have been expanded into their inner nodes. */ + readonly nodesByExecutionId: Map, + /** The actual subgraph instance that contains this node, otherwise undefined. */ + readonly subgraphNode?: SubgraphNode + ) { + if (!node.graph) throw new NullGraphError() + + // Set the internal ID of the DTO + this._id = [...this.subgraphNodePath, this.node.id].join(':') + this.graph = node.graph + this.inputs = this.node.inputs.map((x) => ({ + linkId: x.link == null ? null : toLinkId(x.link), + name: x.name, + type: x.type + })) + + // Only create a wrapper if the node has an applyToGraph method + if (this.node.applyToGraph) { + this.applyToGraph = (...args) => this.node.applyToGraph?.(...args) + } + } + + /** Returns either the DTO itself, or the DTOs of the inner nodes of the subgraph. */ + getInnerNodes(): ExecutableLGraphNode[] { + return this.node.isSubgraphNode() + ? this.node.getInnerNodes(this.nodesByExecutionId, this.subgraphNodePath) + : [this] + } + + /** + * Resolves the executable node & link IDs for a given input slot. + * @param slot The slot index of the input. + * @param visited Leave empty unless overriding this method. + * A set of unique IDs, used to guard against infinite recursion. + * If overriding, ensure that the set is passed on all recursive calls. + * @returns The node and the origin ID / slot index of the output. + */ + resolveInput( + slot: number, + visited = new Set(), + type?: ISlotType + ): ResolvedInput | undefined { + const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[I]${slot}` + if (visited.has(uniqueId)) { + const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}` + const pathInfo = + this.subgraphNodePath.length > 0 + ? ` at path ${this.subgraphNodePath.join(':')}` + : '' + throw new RecursionError( + `Circular reference detected while resolving input ${slot} of node ${nodeInfo}${pathInfo}. ` + + `This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]` + ) + } + visited.add(uniqueId) + + const input = this.inputs.at(slot) + if (!input) + throw new SlotIndexError( + `No input found for flattened id [${this.id}] slot [${slot}]` + ) + + // Nothing connected + if (input.linkId == null) return + + const link = this.graph.getLink(input.linkId) + if (!link) + throw new InvalidLinkError( + `No link found in parent graph for id [${this.id}] slot [${slot}] ${input.name}` + ) + + const { subgraphNode } = this + + // Link goes up and out of this subgraph + if (subgraphNode && link.originIsIoNode) { + const subgraphNodeInput = subgraphNode.inputs.at(link.origin_slot) + if (!subgraphNodeInput) + throw new SlotIndexError( + `No input found for slot [${link.origin_slot}] ${input.name}` + ) + + // Nothing connected + const linkId = subgraphNodeInput.link + if (linkId == null) { + const id = subgraphNodeInput.widgetId + if (!id) return + + return { + node: this, + origin_id: this.id, + origin_slot: -1, + widgetInfo: { value: useWidgetValueStore().getWidget(id)?.value } + } + } + + if (!subgraphNode.graph) + throw new NullGraphError( + `SubgraphNode ${subgraphNode.id} has no graph during input resolution` + ) + const outerLink = subgraphNode.graph.getLink(linkId) + if (!outerLink) + throw new InvalidLinkError( + `No outer link found for slot [${link.origin_slot}] ${input.name}` + ) + + const subgraphNodeExecutionId: ExecutionId = + this.subgraphNodePath.join(':') + const subgraphNodeDto = this.nodesByExecutionId.get( + subgraphNodeExecutionId + ) + if (!subgraphNodeDto) + throw new Error( + `No subgraph node DTO found for id [${subgraphNodeExecutionId}]` + ) + + return subgraphNodeDto.resolveInput(outerLink.target_slot, visited) + } + + // Not part of a subgraph; use the original link + const outputNode = this.graph.getNodeById(link.origin_id) + if (!outputNode) + throw new InvalidLinkError( + `No input node found for id [${this.id}] slot [${slot}] ${input.name}` + ) + + const outputNodeExecutionId: ExecutionId = [ + ...this.subgraphNodePath, + outputNode.id + ].join(':') + const outputNodeDto = this.nodesByExecutionId.get(outputNodeExecutionId) + if (!outputNodeDto) + throw new Error( + `No output node DTO found for id [${outputNodeExecutionId}]` + ) + + return outputNodeDto.resolveOutput( + link.origin_slot, + type ?? input.type, + visited + ) + } + + /** + * Determines whether this output is a valid endpoint for a link (non-virtual, non-bypass). + * @param slot The slot index of the output. + * @param type The type of the input + * @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}. + * @returns The node and the origin ID / slot index of the output. + */ + resolveOutput( + slot: number, + type: ISlotType, + visited: Set + ): ResolvedInput | undefined { + const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[O]${slot}` + if (visited.has(uniqueId)) { + const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}` + const pathInfo = + this.subgraphNodePath.length > 0 + ? ` at path ${this.subgraphNodePath.join(':')}` + : '' + throw new RecursionError( + `Circular reference detected while resolving output ${slot} of node ${nodeInfo}${pathInfo}. ` + + `This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]` + ) + } + visited.add(uniqueId) + + // Muted nodes produce no output + if (this.mode === LGraphEventMode.NEVER) return + + // Upstreamed: Bypass nodes are bypassed using the first input with matching type + if (this.mode === LGraphEventMode.BYPASS) { + // Bypass nodes by finding first input with matching type + const matchingIndex = this._getBypassSlotIndex(slot, type) + + // No input types match - bypass not possible + if (matchingIndex === -1) { + console.warn( + `[ExecutableNodeDTO.resolveOutput] No input types match type [${type}] for id [${this.id}] slot [${slot}]`, + this + ) + return + } + + return this.resolveInput(matchingIndex, visited) + } + + const { node } = this + if (node.isSubgraphNode()) + return this._resolveSubgraphOutput(slot, type, visited) + + if (node.isVirtualNode) { + // Cross-graph virtual nodes (e.g. Set/Get) resolve their source directly. + const virtualSource = this.node.resolveVirtualOutput?.(slot) + if (virtualSource) { + const inputNodeDto = [...this.nodesByExecutionId.values()].find( + (dto) => + dto instanceof ExecutableNodeDTO && dto.node === virtualSource.node + ) + if (!inputNodeDto) + throw new Error( + `No DTO found for virtual source node [${virtualSource.node.id}]` + ) + + return inputNodeDto.resolveOutput(virtualSource.slot, type, visited) + } + const virtualLink = this.node.getInputLink(slot) + if (virtualLink) { + const { inputNode } = virtualLink.resolve(this.graph) + if (!inputNode) + throw new InvalidLinkError( + `Virtual node failed to resolve parent [${this.id}] slot [${slot}]` + ) + + const inputNodeExecutionId: ExecutionId = [ + ...this.subgraphNodePath, + inputNode.id + ].join(':') + const inputNodeDto = this.nodesByExecutionId.get(inputNodeExecutionId) + if (!inputNodeDto) + throw new Error(`No input node DTO found for id [${inputNode.id}]`) + + return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type) + } + + // Virtual nodes without a matching input should be discarded. + return + } + + return { + node: this, + origin_id: this.id, + origin_slot: slot + } + } + + /** + * Finds the index of the input slot on this node that matches the given output {@link slot} index. + * Used when bypassing nodes. + * @param slot The output slot index on this node + * @param type The type of the final target input (so type list matches are accurate) + * @returns The index of the input slot on this node, otherwise `-1`. + */ + private _getBypassSlotIndex(slot: number, type: ISlotType) { + const { inputs } = this + const oppositeInput = inputs[slot] + const outputType = this.node.outputs[slot].type + + // Any type short circuit - match slot ID, fallback to first slot + if (type === '*' || type === '') { + return inputs.length > slot ? slot : 0 + } + + // Prefer input with the same slot ID + if ( + oppositeInput && + LiteGraph.isValidConnection(oppositeInput.type, outputType) && + LiteGraph.isValidConnection(oppositeInput.type, type) + ) { + return slot + } + + // Preserve legacy behaviour; use exact match first. + const exactMatch = inputs.findIndex((input) => input.type === type) + if (exactMatch !== -1) return exactMatch + + // Find first matching slot - prefer exact type + return inputs.findIndex( + (input) => + LiteGraph.isValidConnection(input.type, outputType) && + LiteGraph.isValidConnection(input.type, type) + ) + } + + /** + * Resolves the link inside a subgraph node, from the subgraph IO node to the node inside the subgraph. + * @param slot The slot index of the output on the subgraph node. + * @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}. + * @returns A DTO for the node, and the origin ID / slot index of the output. + */ + private _resolveSubgraphOutput( + slot: number, + type: ISlotType, + visited: Set + ): ResolvedInput | undefined { + const { node } = this + const output = node.outputs.at(slot) + + if (!output) + throw new SlotIndexError( + `No output found for flattened id [${this.id}] slot [${slot}]` + ) + if (!node.isSubgraphNode()) + throw new TypeError(`Node is not a subgraph node: ${node.id}`) + + // Link inside the subgraph + const innerResolved = node.resolveSubgraphOutputLink(slot) + if (!innerResolved) return + + const innerNode = innerResolved.outputNode + if (!innerNode) + throw new Error( + `No output node found for id [${this.id}] slot [${slot}] ${output.name}` + ) + + // Recurse into the subgraph + const innerNodeExecutionId: ExecutionId = [ + ...this.subgraphNodePath, + node.id, + innerNode.id + ].join(':') + const innerNodeDto = this.nodesByExecutionId.get(innerNodeExecutionId) + if (!innerNodeDto) + throw new Error( + `No inner node DTO found for id [${innerNodeExecutionId}]` + ) + + return innerNodeDto.resolveOutput( + innerResolved.link.origin_slot, + type, + visited + ) + } +} diff --git a/docs/hel-892/setget-reference/1.48.6__src__scripts__app.ts b/docs/hel-892/setget-reference/1.48.6__src__scripts__app.ts new file mode 100644 index 00000000..e0429038 --- /dev/null +++ b/docs/hel-892/setget-reference/1.48.6__src__scripts__app.ts @@ -0,0 +1,2260 @@ +import { useEventListener, useResizeObserver } from '@vueuse/core' +import _ from 'es-toolkit/compat' +import type { ToastMessageOptions } from 'primevue/toast' +import { reactive, unref } from 'vue' +import { shallowRef } from 'vue' + +import { useCanvasPositionConversion } from '@/composables/element/useCanvasPositionConversion' +import { layoutStore } from '@/renderer/core/layout/store/layoutStore' +import { syncLayoutStoreNodeBoundsFromGraph } from '@/renderer/core/layout/sync/syncLayoutStoreFromGraph' +import { flushScheduledSlotLayoutSync } from '@/renderer/extensions/vueNodes/composables/useSlotElementTracking' + +import { promotedInputSource } from '@/core/graph/subgraph/promotedInputWidget' +import { resolveConcretePromotedWidget } from '@/core/graph/subgraph/resolveConcretePromotedWidget' +import { st, t } from '@/i18n' +import { ChangeTracker } from '@/scripts/changeTracker' +import type { IContextMenuValue } from '@/lib/litegraph/src/interfaces' +import { + LGraph, + LGraphCanvas, + LGraphNode, + LiteGraph +} from '@/lib/litegraph/src/litegraph' +import { snapPoint } from '@/lib/litegraph/src/measure' +import type { Vector2 } from '@/lib/litegraph/src/litegraph' +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { LGraphEventMode } from '@/lib/litegraph/src/types/globalEnums' +import { useFreeTierQuota } from '@/platform/cloud/subscription/composables/useFreeTierQuota' +import { isCloud } from '@/platform/distribution/types' +import { useSettingStore } from '@/platform/settings/settingStore' +import { useTelemetry } from '@/platform/telemetry' +import { installNodeAddedTelemetry } from '@/platform/telemetry/nodeAdded/installNodeAddedTelemetry' +import { groupMissingNodesByPack } from '@/platform/telemetry/utils/groupMissingNodesByPack' +import type { WorkflowOpenSource } from '@/platform/telemetry/types' +import { useToastStore } from '@/platform/updates/common/toastStore' +import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' +import { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore' +import { useWorkflowValidation } from '@/platform/workflow/validation/composables/useWorkflowValidation' +import type { + ComfyApiWorkflow, + ComfyWorkflowJSON +} from '@/platform/workflow/validation/schemas/workflowSchema' +import { toNodeId } from '@/types/nodeId' +import type { SerializedNodeId } from '@/types/nodeId' +import { + collectSubgraphDefinitions, + buildSubgraphExecutionPaths +} from '@/platform/workflow/core/utils/workflowFlattening' +import type { FlattenableWorkflowNode } from '@/platform/workflow/core/utils/workflowFlattening' +import type { + ExecutionErrorWsMessage, + NodeError, + NodeExecutionOutput, + ResultItem +} from '@/schemas/apiSchema' +import { + type ComfyNodeDef as ComfyNodeDefV1, + isComboInputSpecV1, + isComboInputSpecV2 +} from '@/schemas/nodeDefSchema' +import { + type BaseDOMWidget, + ComponentWidgetImpl, + DOMWidgetImpl +} from '@/scripts/domWidget' +import { useAccountPreconditionDialog } from '@/platform/cloud/subscription/composables/useAccountPreconditionDialog' +import { resolveAccountPrecondition } from '@/platform/errorCatalog/accountPreconditionRouting' +import { useDialogService } from '@/services/dialogService' +import { useExtensionService } from '@/services/extensionService' +import { useLitegraphService } from '@/services/litegraphService' +import { useSubgraphService } from '@/services/subgraphService' +import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' +import { useCommandStore } from '@/stores/commandStore' +import { useDomWidgetStore } from '@/stores/domWidgetStore' +import { useExecutionStore } from '@/stores/executionStore' +import { useExecutionErrorStore } from '@/stores/executionErrorStore' +import { useMissingNodesErrorStore } from '@/platform/nodeReplacement/missingNodesErrorStore' +import { useExtensionStore } from '@/stores/extensionStore' +import { useAuthStore } from '@/stores/authStore' +import { useNodeOutputStore } from '@/stores/nodeOutputStore' +import { useJobPreviewStore } from '@/stores/jobPreviewStore' +import { + getAncestorExecutionIds, + tryNormalizeNodeExecutionId +} from '@/types/nodeIdentification' +import { KeyComboImpl } from '@/platform/keybindings/keyCombo' +import { useKeybindingStore } from '@/platform/keybindings/keybindingStore' +import { SYSTEM_NODE_DEFS, useNodeDefStore } from '@/stores/nodeDefStore' +import { useNodeReplacementStore } from '@/platform/nodeReplacement/nodeReplacementStore' + +import { useSubgraphNavigationStore } from '@/stores/subgraphNavigationStore' +import { useSubgraphStore } from '@/stores/subgraphStore' +import { useWidgetStore } from '@/stores/widgetStore' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import { useWorkspaceStore } from '@/stores/workspaceStore' +import type { ComfyExtension, MissingNodeType } from '@/types/comfy' +import type { ExtensionManager } from '@/types/extensionTypes' +import type { NodeExecutionId } from '@/types/nodeIdentification' +import { normalizePromptError } from '@/utils/executionErrorUtil' +import { graphToPrompt } from '@/utils/executionUtil' +import { parseJsonWithNonFinite } from '@/utils/jsonUtil' +import { getCnrIdFromProperties } from '@/platform/nodeReplacement/cnrIdUtil' +import { rescanAndSurfaceMissingNodes } from '@/platform/nodeReplacement/missingNodeScan' +import { + refreshMissingModelPipeline, + runMissingModelPipeline +} from '@/platform/missingModel/missingModelPipeline' +import type { MissingModelPipelineResult } from '@/platform/missingModel/missingModelPipeline' +import { useMissingModelStore } from '@/platform/missingModel/missingModelStore' +import { runMissingMediaPipeline } from '@/platform/missingMedia/missingMediaPipeline' +import { useMissingMediaStore } from '@/platform/missingMedia/missingMediaStore' + +import { anyItemOverlapsRect } from '@/utils/mathUtil' +import { + collectAllNodes, + forEachNode, + getNodeByExecutionId, + isAncestorPathActive, + triggerCallbackOnAllNodes +} from '@/utils/graphTraversalUtil' +import { + executeWidgetsCallback, + createNode, + fixLinkInputSlots, + isImageNode, + isVideoNode +} from '@/utils/litegraphUtil' +import { + createSharedObjectUrl, + releaseSharedObjectUrl +} from '@/utils/objectUrlUtil' +import { + findLegacyRerouteNodes, + noNativeReroutes +} from '@/utils/migration/migrateReroute' +import { deserialiseAndCreate } from '@/utils/vintageClipboard' + +import { type ComfyApi, PromptExecutionError, api } from './api' +import { defaultGraph } from './defaultGraph' +import { importA1111 } from './pnginfo' +import { applyPromotedWidgetControl } from './promotedWidgetControl' +import { $el, ComfyUI } from './ui' +import { ComfyAppMenu } from './ui/menu/index' +import { clone } from './utils' +import { type ComfyWidgetConstructor } from './widgets' +import { ensureCorrectLayoutScale } from '@/renderer/extensions/vueNodes/layout/ensureCorrectLayoutScale' +import { + extractFilesFromDragEvent, + hasAudioType, + hasImageType, + hasVideoType, + isMediaFile +} from '@/utils/eventUtils' +import { getWorkflowDataFromFile } from '@/scripts/metadata/parser' +import { SUPPORTED_MESH_EXTENSIONS } from '@/extensions/core/load3d/constants' +import Load3dUtils from '@/extensions/core/load3d/Load3dUtils' +import { + pasteAudioNode, + pasteAudioNodes, + pasteImageNode, + pasteImageNodes, + pasteVideoNode, + pasteVideoNodes +} from '@/composables/usePaste' + +export const ANIM_PREVIEW_WIDGET = '$$comfy_animation_preview' + +function isMeshModelFile(file: File): boolean { + const name = file.name.toLowerCase() + return SUPPORTED_MESH_EXTENSIONS.has(name.slice(name.lastIndexOf('.'))) +} + +export function sanitizeNodeName(string: string) { + let entityMap = { + '&': '', + '<': '', + '>': '', + '"': '', + "'": '', + '`': '', + '=': '' + } + return String(string).replace(/[&<>"'`=]/g, function fromEntityMap(s) { + return entityMap[s as keyof typeof entityMap] + }) +} + +function syncPromotedComboHostOptions(rootGraph: LGraph): void { + const widgetValueStore = useWidgetValueStore() + forEachNode(rootGraph, (node) => { + if (!node.isSubgraphNode()) return + for (const input of node.inputs) { + if (!input.widgetId) continue + + const source = promotedInputSource(node, input) + if (!source) continue + + const resolution = resolveConcretePromotedWidget( + node, + source.nodeId, + source.widgetName + ) + if (resolution.status !== 'resolved') continue + + const sourceWidget = resolution.resolved.widget + if (sourceWidget.type !== 'combo') continue + + const state = widgetValueStore.getWidget(input.widgetId) + if (!state) continue + + state.options = { ...(sourceWidget.options ?? {}) } + } + }) +} + +type Clipspace = { + widgets?: Pick[] | null + imgs?: HTMLImageElement[] | null + original_imgs?: HTMLImageElement[] | null + images?: ResultItem[] | null + selectedIndex: number + img_paste_mode: string + paintedIndex: number + combinedIndex: number +} + +export class ComfyApp { + /** + * List of entries to queue + */ + private queueItems: { + number: number + batchCount: number + requestId: number + queueNodeIds?: NodeExecutionId[] + }[] = [] + private nextQueueRequestId = 1 + /** + * If the queue is currently being processed + */ + private processingQueue: boolean = false + + /** + * Content Clipboard + * @type {serialized node object} + */ + static clipspace: Clipspace | null = null + static clipspace_invalidate_handler: (() => void) | null = null + static open_maskeditor: (() => void) | null = null + static maskeditor_is_opended: (() => void) | null = null + static clipspace_return_node = null + + vueAppReady: boolean + api: ComfyApi + ui: ComfyUI + extensionManager!: ExtensionManager + private _nodeOutputs!: Record + nodePreviewImages: Record + + private rootGraphInternal: LGraph | undefined + + // TODO: Migrate internal usage to the + /** @deprecated Use {@link rootGraph} instead */ + get graph() { + return this.rootGraphInternal! + } + + get rootGraph(): LGraph { + if (!this.rootGraphInternal) { + console.error('ComfyApp graph accessed before initialization') + } + return this.rootGraphInternal! + } + + /** Whether the root graph has been initialized. Safe to check without triggering error logs. */ + get isGraphReady(): boolean { + return !!this.rootGraphInternal + } + + canvas!: LGraphCanvas + dragOverNode: Pick | null = null + readonly canvasElRef = shallowRef() + get canvasEl() { + // TODO: Fix possibly undefined reference + return unref(this.canvasElRef)! + } + + private configuringGraphLevel: number = 0 + get configuringGraph() { + return this.configuringGraphLevel > 0 + } + ctx!: CanvasRenderingContext2D + bodyTop: HTMLElement + bodyLeft: HTMLElement + bodyRight: HTMLElement + bodyBottom: HTMLElement + canvasContainer: HTMLElement + menu: ComfyAppMenu + // Set by Comfy.Clipspace extension + openClipspace: () => void = () => {} + + private positionConversion?: { + clientPosToCanvasPos: (pos: Vector2) => Vector2 + canvasPosToClientPos: (pos: Vector2) => Vector2 + } + + /** + * The node errors from the previous execution. + * @deprecated Use app.extensionManager.lastNodeErrors instead + */ + get lastNodeErrors(): Record | null { + return useExecutionErrorStore().lastNodeErrors + } + + /** + * The error from the previous execution. + * @deprecated Use app.extensionManager.lastExecutionError instead + */ + get lastExecutionError(): ExecutionErrorWsMessage | null { + return useExecutionErrorStore().lastExecutionError + } + + /** + * @deprecated Use useExecutionStore().executingNodeId instead + * TODO: Update to support multiple executing nodes. This getter returns only the first executing node. + * Consider updating consumers to handle multiple nodes or use executingNodeIds array. + */ + get runningNodeId(): SerializedNodeId | null { + return useExecutionStore().executingNodeId + } + + /** + * @deprecated Use useWorkspaceStore().shiftDown instead + */ + get shiftDown(): boolean { + return useWorkspaceStore().shiftDown + } + + /** + * @deprecated Use useWidgetStore().widgets instead + */ + get widgets(): Record { + return Object.fromEntries(useWidgetStore().widgets.entries()) + } + + /** + * @deprecated storageLocation is always 'server' since + * https://github.com/comfyanonymous/ComfyUI/commit/53c8a99e6c00b5e20425100f6680cd9ea2652218 + */ + get storageLocation() { + return 'server' + } + + /** + * @deprecated storage migration is no longer needed. + */ + get isNewUserSession() { + return false + } + + /** + * @deprecated Use useExtensionStore().extensions instead + */ + get extensions(): ComfyExtension[] { + return useExtensionStore().extensions + } + + /** + * The progress on the current executing node, if the node reports any. + * @deprecated Use useExecutionStore().executingNodeProgress instead + */ + get progress() { + return useExecutionStore()._executingNodeProgress + } + + /** + * @deprecated Use {@link isImageNode} from @/utils/litegraphUtil instead + */ + static isImageNode(node: LGraphNode) { + return isImageNode(node) + } + + /** + * Resets the canvas view to the default + * @deprecated Use {@link useLitegraphService().resetView} instead + */ + resetView() { + useLitegraphService().resetView() + } + + constructor() { + this.vueAppReady = false + this.ui = new ComfyUI(this) + this.api = api + // Dummy placeholder elements before GraphCanvas is mounted. + this.bodyTop = $el('div.comfyui-body-top') + this.bodyLeft = $el('div.comfyui-body-left') + this.bodyRight = $el('div.comfyui-body-right') + this.bodyBottom = $el('div.comfyui-body-bottom') + this.canvasContainer = $el('div.graph-canvas-container') + + this.menu = new ComfyAppMenu(this) + + /** + * Stores the execution output data for each node + * @type {Record} + */ + this.nodeOutputs = {} + + /** + * Stores the preview image data for each node + * @type {Record} + */ + this.nodePreviewImages = {} + } + + get nodeOutputs() { + return this._nodeOutputs + } + + set nodeOutputs(value) { + this._nodeOutputs = value + if (this.vueAppReady) + useExtensionService().invokeExtensions('onNodeOutputsUpdated', value) + } + + /** + * If the user has specified a preferred format to receive preview images in, + * this function will return that format as a url query param. + * If the node's outputs are not images, this param should not be used, as it will + * force the server to load the output file as an image. + */ + getPreviewFormatParam() { + let preview_format = useSettingStore().get('Comfy.PreviewFormat') + if (preview_format) return `&preview=${preview_format}` + else return '' + } + + getRandParam() { + if (isCloud) return '' + return '&rand=' + Math.random() + } + + static onClipspaceEditorSave() { + if (ComfyApp.clipspace_return_node) { + ComfyApp.pasteFromClipspace(ComfyApp.clipspace_return_node) + } + } + + static onClipspaceEditorClosed() { + ComfyApp.clipspace_return_node = null + } + + static copyToClipspace(node: LGraphNode) { + var widgets = null + if (node.widgets) { + widgets = node.widgets.map(({ type, name, value }) => ({ + type, + name, + value + })) + } + + var imgs = undefined + var orig_imgs = undefined + if (node.imgs != undefined) { + imgs = [] + orig_imgs = [] + + for (let i = 0; i < node.imgs.length; i++) { + imgs[i] = new Image() + imgs[i].src = node.imgs[i].src + orig_imgs[i] = imgs[i] + } + } + + var selectedIndex = 0 + if (node.imageIndex) { + selectedIndex = node.imageIndex + } + + const paintedIndex = imgs ? imgs.length + 1 : 1 + const combinedIndex = imgs ? imgs.length + 2 : 2 + + // for vueNodes mode + const images = + node.images ?? useNodeOutputStore().getNodeOutputs(node)?.images + + ComfyApp.clipspace = { + widgets: widgets, + imgs: imgs, + original_imgs: orig_imgs, + images: images, + selectedIndex: selectedIndex, + img_paste_mode: 'selected', // reset to default im_paste_mode state on copy action + paintedIndex: paintedIndex, + combinedIndex: combinedIndex + } + + ComfyApp.clipspace_return_node = null + + if (ComfyApp.clipspace_invalidate_handler) { + ComfyApp.clipspace_invalidate_handler() + } + } + + static pasteFromClipspace(node: LGraphNode) { + if (ComfyApp.clipspace) { + // image paste + let combinedImgSrc: string | undefined + if ( + ComfyApp.clipspace.combinedIndex !== undefined && + ComfyApp.clipspace.imgs && + ComfyApp.clipspace.combinedIndex < ComfyApp.clipspace.imgs.length + ) { + combinedImgSrc = + ComfyApp.clipspace.imgs[ComfyApp.clipspace.combinedIndex].src + } + if (ComfyApp.clipspace.imgs && node.imgs) { + // Update node.images even if it's initially undefined (vueNodes mode) + if (ComfyApp.clipspace.images) { + if (ComfyApp.clipspace['img_paste_mode'] == 'selected') { + node.images = [ + ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']] + ] + } else { + node.images = ComfyApp.clipspace.images + } + + if (app.nodeOutputs[node.id + '']) + app.nodeOutputs[node.id + ''].images = node.images + } + + if (ComfyApp.clipspace.imgs) { + // deep-copy to cut link with clipspace + if (ComfyApp.clipspace['img_paste_mode'] == 'selected') { + const img = new Image() + img.src = + ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src + node.imgs = [img] + node.imageIndex = 0 + } else { + const imgs = [] + for (let i = 0; i < ComfyApp.clipspace.imgs.length; i++) { + imgs[i] = new Image() + imgs[i].src = ComfyApp.clipspace.imgs[i].src + node.imgs = imgs + } + } + } + } + + // Paste the RGB canvas if paintedindex exists + if ( + ComfyApp.clipspace.imgs?.[ComfyApp.clipspace.paintedIndex] && + node.imgs + ) { + const paintedImg = new Image() + paintedImg.src = + ComfyApp.clipspace.imgs[ComfyApp.clipspace.paintedIndex].src + node.imgs.push(paintedImg) // Add the RGB canvas to the node's images + } + + // Store only combined image inside the node if it exists + if ( + ComfyApp.clipspace.imgs?.[ComfyApp.clipspace.combinedIndex] && + node.imgs && + combinedImgSrc + ) { + const combinedImg = new Image() + combinedImg.src = combinedImgSrc + node.imgs = [combinedImg] + } + + if (node.widgets) { + if (ComfyApp.clipspace.images) { + const clip_image = + ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']] + const index = node.widgets.findIndex((obj) => obj.name === 'image') + if (index >= 0) { + if ( + node.widgets[index].type != 'image' && + typeof node.widgets[index].value == 'string' && + clip_image.filename + ) { + node.widgets[index].value = + (clip_image.subfolder ? clip_image.subfolder + '/' : '') + + clip_image.filename + + (clip_image.type ? ` [${clip_image.type}]` : '') + } else { + node.widgets[index].value = clip_image + } + } + } + if (ComfyApp.clipspace.widgets && node.widgets) { + ComfyApp.clipspace.widgets.forEach(({ type, name, value }) => { + const prop = node.widgets?.find( + (obj) => obj.type === type && obj.name === name + ) + if (prop && prop.type != 'button') { + const valueObj = value as Record | undefined + if ( + prop.type != 'image' && + typeof prop.value == 'string' && + valueObj?.filename + ) { + const resultItem = value as ResultItem + prop.value = + (resultItem.subfolder ? resultItem.subfolder + '/' : '') + + resultItem.filename + + (resultItem.type ? ` [${resultItem.type}]` : '') + } else { + prop.value = value + prop.callback?.(value) + } + } + }) + } + } + + app.canvas.setDirty(true) + + useNodeOutputStore().updateNodeImages(node) + } + } + + /** + * Adds a handler allowing drag+drop of files onto the window to load workflows + */ + private addDropHandler() { + // Get prompt from dropped PNG or json + useEventListener(document, 'drop', async (event: DragEvent) => { + try { + // Skip if already handled (e.g. file drop onto publish dialog tiles) + if (event.defaultPrevented) return + + event.preventDefault() + event.stopPropagation() + + // graph_mouse is only updated on mousemove, so when files are dragged + // in from another window the canvas-space cursor is stale. Sync it + // from the drop event so nodes created below land at the cursor. + this.canvas.adjustMouseEvent(event) + this.canvas.graph_mouse[0] = event.canvasX + this.canvas.graph_mouse[1] = event.canvasY + + const n = this.dragOverNode + this.dragOverNode = null + // Node handles file drop, we dont use the built in onDropFile handler as its buggy + // If you drag multiple files it will call it multiple times with the same file + if (await n?.onDragDrop?.(event)) return + + const files = await extractFilesFromDragEvent(event) + if (files.length === 0) return + + const workspace = useWorkspaceStore() + try { + workspace.spinner = true + const imageFiles = files.filter(hasImageType) + const audioFiles = files.filter(hasAudioType) + const videoFiles = files.filter(hasVideoType) + const totalMedia = + imageFiles.length + audioFiles.length + videoFiles.length + const hasMultipleMedia = totalMedia > 1 + + const createdNodes: LGraphNode[] = [] + const handleFileOptions = { + deferWarnings: true, + onNodeCreated: (node: LGraphNode) => createdNodes.push(node) + } + + if (hasMultipleMedia) { + if (imageFiles.length > 0) { + await this.handleFileList(imageFiles) + } + if (audioFiles.length > 0) { + await this.handleAudioFileList(audioFiles) + } + if (videoFiles.length > 0) { + await this.handleVideoFileList(videoFiles) + } + for (const file of files.filter((f) => !isMediaFile(f))) { + await this.handleFile(file, 'file_drop', handleFileOptions) + } + } else { + for (const file of files) { + await this.handleFile(file, 'file_drop', handleFileOptions) + } + } + + this.positionNodes(createdNodes) + } finally { + workspace.spinner = false + } + useWorkflowService().showPendingWarnings() + } catch (error: unknown) { + useToastStore().addAlert(t('toastMessages.dropFileError', { error })) + } + }) + + // Always clear over node on drag leave + useEventListener(this.canvasElRef, 'dragleave', async () => { + if (!this.dragOverNode) return + this.dragOverNode = null + this.canvas.setDirty(false, true) + }) + + // Add handler for dropping onto a specific node + useEventListener( + this.canvasElRef, + 'dragover', + (event: DragEvent) => { + this.canvas.adjustMouseEvent(event) + const node = this.canvas.graph?.getNodeOnPos( + event.canvasX, + event.canvasY + ) + + if (!node?.onDragOver?.(event)) { + this.dragOverNode = null + return + } + + this.dragOverNode = node + + // dragover event is fired very frequently, run this on an animation frame + requestAnimationFrame(() => { + this.canvas.setDirty(false, true) + }) + }, + false + ) + } + + /** + * Handle keypress + */ + private addProcessKeyHandler() { + const origProcessKey = LGraphCanvas.prototype.processKey + LGraphCanvas.prototype.processKey = function (e: KeyboardEvent) { + if (!this.graph) return + + if (e.target instanceof Element && e.target.localName == 'input') { + return + } + + if (e.type == 'keydown' && !e.repeat) { + const keyCombo = KeyComboImpl.fromEvent(e) + const keybindingStore = useKeybindingStore() + const keybinding = keybindingStore.getKeybinding(keyCombo) + + if ( + keybinding && + keybinding.targetElementId === 'graph-canvas-container' + ) { + useCommandStore().execute(keybinding.commandId) + + this.graph.change() + e.preventDefault() + e.stopImmediatePropagation() + return + } + } + + // Fall through to Litegraph defaults + return origProcessKey.apply(this, [e]) + } + } + + /** + * Handles updates from the API socket + */ + private addApiUpdateHandlers() { + api.addEventListener('status', ({ detail }) => { + this.ui.setStatus(detail) + }) + + api.addEventListener('progress', () => { + this.canvas.setDirty(true, false) + }) + + api.addEventListener('executing', () => { + this.canvas.setDirty(true, false) + }) + + api.addEventListener('executed', ({ detail }) => { + const nodeOutputStore = useNodeOutputStore() + const executionId = tryNormalizeNodeExecutionId( + detail.display_node || detail.node + ) + if (!executionId) return + + nodeOutputStore.setNodeOutputsByExecutionId(executionId, detail.output, { + merge: detail.merge + }) + + const node = getNodeByExecutionId(this.rootGraph, executionId) + if (node && node.onExecuted) { + node.onExecuted(detail.output) + } + }) + + api.addEventListener('execution_start', () => { + triggerCallbackOnAllNodes(this.rootGraph, 'onExecutionStart') + }) + + api.addEventListener('execution_error', ({ detail }) => { + const precondition = resolveAccountPrecondition({ + exceptionType: detail.exception_type ?? '', + exceptionMessage: detail.exception_message ?? '' + }) + if (precondition) { + useAccountPreconditionDialog().open(precondition, { + nodeType: detail.node_type + }) + } else if (useSettingStore().get('Comfy.RightSidePanel.ShowErrorsTab')) { + useExecutionErrorStore().showErrorOverlay() + } else { + useDialogService().showExecutionErrorDialog(detail) + } + this.canvas.draw(true, true) + }) + + api.addEventListener('b_preview_with_metadata', ({ detail }) => { + // Enhanced preview with explicit node context + const { blob, displayNodeId, jobId } = detail + const { setNodePreviewsByExecutionId, revokePreviewsByExecutionId } = + useNodeOutputStore() + const displayNodeExecutionId = tryNormalizeNodeExecutionId(displayNodeId) + if (!displayNodeExecutionId) return + const blobUrl = createSharedObjectUrl(blob) + useJobPreviewStore().setPreviewUrl(jobId, blobUrl, displayNodeId) + // Ensure clean up if `executing` event is missed. + revokePreviewsByExecutionId(displayNodeExecutionId) + // Preview cleanup is handled in progress_state event to support multiple concurrent previews + for (const executionId of getAncestorExecutionIds( + displayNodeExecutionId + )) { + setNodePreviewsByExecutionId(executionId, [blobUrl]) + } + releaseSharedObjectUrl(blobUrl) + }) + + api.addEventListener('feature_flags', () => { + void useNodeReplacementStore().load() + }) + + api.init() + } + + /** Flag that the graph is configuring to prevent nodes from running checks while its still loading */ + private addConfigureHandler() { + const app = this + const configure = LGraph.prototype.configure + LGraph.prototype.configure = function (...args) { + app.configuringGraphLevel++ + try { + return configure.apply(this, args) + } finally { + app.configuringGraphLevel-- + } + } + } + + private addAfterConfigureHandler(graph: LGraph) { + const { onConfigure } = graph + graph.onConfigure = function (...args) { + // Set pending sync flag to suppress link rendering until slots are synced + if (LiteGraph.vueNodesMode) { + layoutStore.setPendingSlotSync(true) + } + + try { + fixLinkInputSlots(this) + + // Fire callbacks before the onConfigure, this is used by widget inputs to setup the config + triggerCallbackOnAllNodes(this, 'onGraphConfigured') + + const r = onConfigure?.apply(this, args) + + // Fire after onConfigure, used by primitives to generate widget using input nodes config + triggerCallbackOnAllNodes(this, 'onAfterGraphConfigured') + + return r + } finally { + // Flush pending slot layout syncs to fix link alignment after undo/redo + // Using finally ensures links aren't permanently suppressed if an error occurs + if (LiteGraph.vueNodesMode) { + flushScheduledSlotLayoutSync() + app.canvas?.setDirty(true, true) + } + } + } + } + + /** + * Set up the app on the page + */ + async setup(canvasEl: HTMLCanvasElement) { + this.bodyTop = document.getElementById('comfyui-body-top')! + this.bodyLeft = document.getElementById('comfyui-body-left')! + this.bodyRight = document.getElementById('comfyui-body-right')! + this.bodyBottom = document.getElementById('comfyui-body-bottom')! + this.canvasContainer = document.getElementById('graph-canvas-container')! + + this.canvasElRef.value = canvasEl + + await useWorkspaceStore().workflow.syncWorkflows() + //Doesn't need to block. Blueprints will load async + void useSubgraphStore().fetchSubgraphs() + await useExtensionService().loadExtensions() + + this.addProcessKeyHandler() + this.addConfigureHandler() + this.addApiUpdateHandlers() + + const graph = new LGraph() + + // Register the subgraph - adds type wrapper for Litegraph's `createNode` factory + graph.events.addEventListener('subgraph-created', (e) => { + try { + const { subgraph, data } = e.detail + useSubgraphService().registerNewSubgraph(subgraph, data) + } catch (err) { + console.error('Failed to register subgraph', err) + useToastStore().add({ + severity: 'error', + summary: 'Failed to register subgraph', + detail: err instanceof Error ? err.message : String(err) + }) + } + }) + + this.addAfterConfigureHandler(graph) + + this.rootGraphInternal = graph + installNodeAddedTelemetry(graph) + this.canvas = new LGraphCanvas(canvasEl, graph) + // Make canvas states reactive so we can observe changes on them. + this.canvas.state = reactive(this.canvas.state) + + this.ctx = canvasEl.getContext('2d')! + + LiteGraph.alt_drag_do_clone_nodes = true + LiteGraph.macGesturesRequireMac = false + + this.canvas.canvas.addEventListener<'litegraph:set-graph'>( + 'litegraph:set-graph', + (e) => { + const { newGraph } = e.detail + + const widgetStore = useDomWidgetStore() + + const activeWidgets: Record< + string, + BaseDOMWidget + > = Object.fromEntries( + newGraph.nodes + .flatMap((node) => node.widgets ?? []) + .filter( + (w) => + w instanceof DOMWidgetImpl || w instanceof ComponentWidgetImpl + ) + .map((w) => [w.id, w]) + ) + + for (const [ + widgetId, + widgetState + ] of widgetStore.widgetStates.entries()) { + if (widgetId in activeWidgets) { + widgetState.active = true + widgetState.widget = activeWidgets[widgetId] + } else { + widgetState.active = false + } + } + } + ) + + // Ensure subgraphs are scaled when entering them + this.canvas.canvas.addEventListener<'litegraph:set-graph'>( + 'litegraph:set-graph', + (e) => { + const { newGraph, oldGraph } = e.detail + // Only scale when switching between graphs (not during initial setup) + // oldGraph is null/undefined during initial setup, so skip scaling then + if (oldGraph) { + ensureCorrectLayoutScale( + newGraph.extra.workflowRendererVersion, + newGraph + ) + } + } + ) + + this.rootGraph.start() + + // Ensure the canvas fills the window + useResizeObserver(this.canvasElRef, ([canvasEl]) => { + if (canvasEl.target instanceof HTMLCanvasElement) { + this.resizeCanvas(canvasEl.target) + } + }) + + await useExtensionService().invokeExtensionsAsync('init') + await this.registerNodes() + + this.addDropHandler() + + await useExtensionService().invokeExtensionsAsync('setup') + + this.positionConversion = useCanvasPositionConversion( + this.canvasContainer, + this.canvas + ) + } + + private resizeCanvas(canvas: HTMLCanvasElement) { + // Limit minimal scale to 1, see https://github.com/comfyanonymous/ComfyUI/pull/845 + const scale = Math.max(window.devicePixelRatio, 1) + + // Clear fixed width and height while calculating rect so it uses 100% instead + canvas.height = canvas.width = NaN + const { width, height } = canvas.getBoundingClientRect() + canvas.width = Math.round(width * scale) + canvas.height = Math.round(height * scale) + canvas.getContext('2d')?.scale(scale, scale) + this.canvas?.draw(true, true) + } + + private updateVueAppNodeDefs(defs: Record) { + // Frontend only nodes registered by custom nodes. + // Example: https://github.com/rgthree/rgthree-comfy/blob/dd534e5384be8cf0c0fa35865afe2126ba75ac55/src_web/comfyui/fast_groups_bypasser.ts#L10 + + // Only create frontend_only definitions for nodes that don't have backend definitions + const frontendOnlyDefs: Record = {} + for (const [name, node] of Object.entries( + LiteGraph.registered_node_types + )) { + // Skip if we already have a backend definition or system definition + if (name in defs || name in SYSTEM_NODE_DEFS || node.skip_list) { + continue + } + + frontendOnlyDefs[name] = { + name, + display_name: name, + category: node.category || '__frontend_only__', + input: { required: {}, optional: {} }, + output: [], + output_name: [], + output_is_list: [], + output_node: false, + python_module: 'custom_nodes.frontend_only', + description: node.description ?? `Frontend only node for ${name}` + } as ComfyNodeDefV1 + } + + const allNodeDefs = { + ...frontendOnlyDefs, + ...defs, + ...SYSTEM_NODE_DEFS + } + + const nodeDefStore = useNodeDefStore() + const nodeDefArray: ComfyNodeDefV1[] = Object.values(allNodeDefs) + useExtensionService().invokeExtensions( + 'beforeRegisterVueAppNodeDefs', + nodeDefArray + ) + nodeDefStore.updateNodeDefs(nodeDefArray) + } + + async getNodeDefs(): Promise> { + const translateNodeDef = (def: ComfyNodeDefV1): ComfyNodeDefV1 => { + // Use object info display_name as fallback before using name + const objectInfoDisplayName = def.display_name || def.name + + return { + ...def, + display_name: st( + `nodeDefs.${def.name}.display_name`, + objectInfoDisplayName + ), + description: def.description + ? st(`nodeDefs.${def.name}.description`, def.description) + : '', + category: def.category + .split('/') + .map((category: string) => st(`nodeCategories.${category}`, category)) + .join('/') + } + } + + return _.mapValues(await api.getNodeDefs(), (def) => translateNodeDef(def)) + } + + /** + * Registers nodes with the graph + */ + async registerNodes() { + // Load node definitions from the backend + const defs = await this.getNodeDefs() + await this.registerNodesFromDefs(defs) + await useExtensionService().invokeExtensionsAsync('registerCustomNodes') + if (this.vueAppReady) { + this.updateVueAppNodeDefs(defs) + } + } + + async registerNodeDef(nodeId: string, nodeDef: ComfyNodeDefV1) { + return await useLitegraphService().registerNodeDef(nodeId, nodeDef) + } + + async registerNodesFromDefs(defs: Record) { + await useExtensionService().invokeExtensionsAsync('addCustomNodeDefs', defs) + + // Register a node for each definition + await Promise.all( + Object.keys(defs).map((nodeId) => + this.registerNodeDef(nodeId, defs[nodeId]) + ) + ) + } + + loadTemplateData(templateData: { + templates?: { name?: string; data?: string }[] + }): void { + if (!templateData?.templates) { + return + } + + const old = localStorage.getItem('litegrapheditor_clipboard') + + for (const template of templateData.templates) { + if (!template?.data) { + continue + } + + // Check for old clipboard format + const data = parseJsonWithNonFinite<{ reroutes?: unknown }>(template.data) + if (!data.reroutes) { + deserialiseAndCreate(template.data, app.canvas) + } else { + localStorage.setItem('litegrapheditor_clipboard', template.data) + app.canvas.pasteFromClipboard() + } + + // Move mouse position down to paste the next template below + let maxY: number | undefined + + for (const i in app.canvas.selected_nodes) { + const node = app.canvas.selected_nodes[i] + const nodeBottom = node.pos[1] + node.size[1] + if (maxY === undefined || nodeBottom > maxY) { + maxY = nodeBottom + } + } + + if (maxY !== undefined) { + app.canvas.graph_mouse[1] = maxY + 50 + } + } + + if (old !== null) { + localStorage.setItem('litegrapheditor_clipboard', old) + } + } + + private showMissingNodesError(missingNodeTypes: MissingNodeType[]) { + if (useMissingNodesErrorStore().surfaceMissingNodes(missingNodeTypes)) { + useExecutionErrorStore().showErrorOverlay() + } + } + + async loadGraphData( + graphData?: ComfyWorkflowJSON, + clean: boolean = true, + restore_view: boolean = true, + workflow: string | null | ComfyWorkflow = null, + options: { + checkForRerouteMigration?: boolean + openSource?: WorkflowOpenSource + shareId?: string + deferWarnings?: boolean + skipAssetScans?: boolean + silentAssetErrors?: boolean + } = {} + ) { + const { + checkForRerouteMigration = false, + openSource, + shareId, + deferWarnings = false, + skipAssetScans = false, + silentAssetErrors = false + } = options + useWorkflowService().beforeLoadNewGraph() + + if (skipAssetScans) { + // Only reset candidates; preserve UI state (fileSizes, etc.) + // so cached results restored by showPendingWarnings still display sizes. + // Abort any in-flight verification from the outgoing workflow so a late + // result cannot repopulate the store after we've switched workflows. + useMissingModelStore().createVerificationAbortController().abort() + useMissingMediaStore().createVerificationAbortController().abort() + useMissingModelStore().setMissingModels([]) + useMissingMediaStore().setMissingMedia([]) + } else { + useMissingModelStore().clearMissingModels() + useMissingMediaStore().clearMissingMedia() + } + + if (clean !== false) { + // Reset canvas context before configuring a new graph so subgraph UI + // state from the previous workflow cannot leak into the newly loaded + // one, and so `clean()` can clear the root graph even when the user is + // currently inside a subgraph. + this.canvas.setGraph(this.rootGraph) + + this.clean() + } + + let reset_invalid_values = false + // Use explicit validation instead of falsy check to avoid replacing + // valid but falsy values (empty objects, 0, false, etc.) + if ( + !graphData || + typeof graphData !== 'object' || + Array.isArray(graphData) + ) { + graphData = defaultGraph + reset_invalid_values = true + } + + graphData = clone(graphData) + + if (useSettingStore().get('Comfy.Validation.Workflows')) { + const { graphData: validatedGraphData } = + await useWorkflowValidation().validateWorkflow(graphData) + + // If the validation failed, use the original graph data. + // Ideally we should not block users from loading the workflow. + graphData = validatedGraphData ?? graphData + } + // Only show the reroute migration warning if the workflow does not have native + // reroutes. Merging reroute network has great complexity, and it is not supported + // for now. + // See: https://github.com/Comfy-Org/ComfyUI_frontend/issues/3317 + if ( + checkForRerouteMigration && + graphData.version === 0.4 && + findLegacyRerouteNodes(graphData).length && + noNativeReroutes(graphData) + ) { + useToastStore().add({ + group: 'reroute-migration', + severity: 'warn' + }) + } + useSubgraphService().loadSubgraphs(graphData) + + const missingNodeTypes: MissingNodeType[] = [] + await useExtensionService().invokeExtensionsAsync( + 'beforeConfigureGraph', + graphData, + missingNodeTypes + ) + + const nodeReplacementStore = useNodeReplacementStore() + await nodeReplacementStore.load() + + // Collect missing node types from all nodes (root + subgraphs) + const collectMissingNodes = ( + nodes: readonly FlattenableWorkflowNode[], + pathPrefix: string = '', + displayName: string = '' + ) => { + if (!Array.isArray(nodes)) { + console.warn( + 'Workflow nodes data is missing or invalid, skipping node processing', + { nodes, pathPrefix } + ) + return + } + for (let n of nodes) { + if (!(n.type in LiteGraph.registered_node_types)) { + // Always sanitize so configure() can handle unregistered types, + // but only report as missing if the node is active. + const isMuted = + n.mode === LGraphEventMode.NEVER || + n.mode === LGraphEventMode.BYPASS + if (!isMuted) { + const replacement = nodeReplacementStore.getReplacementFor(n.type) + const cnrId = getCnrIdFromProperties( + n.properties as Record | undefined + ) + const executionId = pathPrefix + ? `${pathPrefix}:${n.id}` + : String(n.id) + + missingNodeTypes.push({ + type: n.type, + nodeId: executionId, + cnrId, + ...(displayName && { + hint: t('g.inSubgraph', { name: displayName }) + }), + isReplaceable: replacement !== null, + replacement: replacement ?? undefined + }) + } + + n.type = sanitizeNodeName(n.type) + } + } + } + + collectMissingNodes(graphData.nodes) + const subgraphDefs = collectSubgraphDefinitions( + graphData.definitions?.subgraphs ?? [] + ) + const subgraphContainerIdMap = buildSubgraphExecutionPaths( + graphData.nodes, + subgraphDefs + ) + for (const subgraph of subgraphDefs) { + const paths = subgraphContainerIdMap.get(subgraph.id) ?? [] + for (const pathPrefix of paths) { + collectMissingNodes( + subgraph.nodes, + pathPrefix, + subgraph.name || subgraph.id + ) + } + } + + const canvasVisible = !!(this.canvasEl.width && this.canvasEl.height) + const fitView = () => { + if ( + restore_view && + useSettingStore().get('Comfy.EnableWorkflowViewRestore') + ) { + // Always fit view for templates to ensure they're visible on load + if (openSource === 'template') { + useLitegraphService().fitView() + } else if (graphData.extra?.ds) { + this.canvas.ds.offset = graphData.extra.ds.offset + this.canvas.ds.scale = graphData.extra.ds.scale + + // Fit view if no nodes visible in restored viewport + this.canvas.ds.computeVisibleArea(this.canvas.viewport) + if ( + this.canvas.visible_area.width && + this.canvas.visible_area.height && + !anyItemOverlapsRect( + this.rootGraph._nodes, + this.canvas.visible_area + ) + ) { + requestAnimationFrame(() => useLitegraphService().fitView()) + } + } else { + useLitegraphService().fitView() + } + } + } + + ChangeTracker.isLoadingGraph = true + try { + let normalizedMainGraph = false + try { + // @ts-expect-error Discrepancies between zod and litegraph - in progress + this.rootGraph.configure(graphData) + + // Save original renderer version before scaling (it gets modified during scaling) + const originalMainGraphRenderer = + this.rootGraph.extra.workflowRendererVersion + + // Scale main graph + normalizedMainGraph = ensureCorrectLayoutScale( + originalMainGraphRenderer, + this.rootGraph + ) + + // Scale all subgraphs that were loaded with the workflow + // Use original main graph renderer as fallback (not the modified one) + for (const subgraph of this.rootGraph.subgraphs.values()) { + ensureCorrectLayoutScale( + subgraph.extra.workflowRendererVersion || originalMainGraphRenderer, + subgraph + ) + } + + if (canvasVisible) fitView() + } catch (error) { + useDialogService().showErrorDialog(error, { + title: t('errorDialog.loadWorkflowTitle'), + reportType: 'loadWorkflowError' + }) + console.error(error) + return + } + const snapTo = LiteGraph.alwaysSnapToGrid + ? this.rootGraph.getSnapToGridSize() + : 0 + forEachNode(this.rootGraph, (node) => { + const size = node.computeSize() + size[0] = Math.max(node.size[0], size[0]) + size[1] = Math.max(node.size[1], size[1]) + snapPoint(size, snapTo, 'ceil') + node.setSize(size) + if (node.widgets) { + // If you break something in the backend and want to patch workflows in the frontend + // This is the place to do this + for (let widget of node.widgets) { + if (node.type == 'KSampler' || node.type == 'KSamplerAdvanced') { + if (widget.name == 'sampler_name') { + if ( + typeof widget.value === 'string' && + widget.value.startsWith('sample_') + ) { + widget.value = widget.value.slice(7) + } + } + } + if ( + node.type == 'KSampler' || + node.type == 'KSamplerAdvanced' || + node.type == 'PrimitiveNode' + ) { + if (widget.name == 'control_after_generate') { + if (widget.value === true) { + widget.value = 'randomize' + } else if (widget.value === false) { + widget.value = 'fixed' + } + } + } + if (widget.type == 'combo') { + const values = widget.options.values as + | (string | number | boolean)[] + | undefined + if ( + values && + values.length > 0 && + (widget.value == null || + (reset_invalid_values && + !values.includes( + widget.value as string | number | boolean + ))) + ) { + widget.value = values[0] + } + } + } + } + + useExtensionService().invokeExtensions('loadedGraphNode', node) + }) + + if (normalizedMainGraph) { + syncLayoutStoreNodeBoundsFromGraph(this.rootGraph) + } + + await useExtensionService().invokeExtensionsAsync( + 'afterConfigureGraph', + missingNodeTypes + ) + + const effectiveShareId = + shareId ?? + (workflow instanceof ComfyWorkflow ? workflow.shareId : undefined) + const telemetryPayload = { + missing_node_count: missingNodeTypes.length, + missing_node_types: missingNodeTypes.map((node) => + typeof node === 'string' ? node : node.type + ), + missing_node_packs: groupMissingNodesByPack(missingNodeTypes), + open_source: openSource ?? 'unknown', + ...(effectiveShareId ? { share_id: effectiveShareId } : {}) + } + useTelemetry()?.trackWorkflowOpened(telemetryPayload) + useTelemetry()?.trackWorkflowImported(telemetryPayload) + await useWorkflowService().afterLoadNewGraph( + workflow, + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, + effectiveShareId + ) + + // If the canvas was not visible and we're a fresh load, resize the canvas and fit the view + // This fixes switching from app mode to a new graph mode workflow (e.g. load template) + if (!canvasVisible && (!workflow || typeof workflow === 'string')) { + this.canvas.resize() + requestAnimationFrame(() => fitView()) + } + + // Drop missing-node entries whose enclosing subgraph is + // muted/bypassed. The initial JSON scan only checks each node's + // own mode; the cascade from an inactive container is applied here + // using the now-configured live graph. + const activeMissingNodeTypes = missingNodeTypes.filter( + (n) => + typeof n === 'string' || + n.nodeId == null || + isAncestorPathActive(this.rootGraph, String(n.nodeId)) + ) + + if (!skipAssetScans) { + await runMissingModelPipeline({ + graph: this.rootGraph, + graphData, + missingModelStore: useMissingModelStore(), + missingNodeTypes: activeMissingNodeTypes, + silent: silentAssetErrors + }) + + await runMissingMediaPipeline({ + rootGraph: this.rootGraph, + silent: silentAssetErrors + }) + } + + if (!deferWarnings) { + useWorkflowService().showPendingWarnings(undefined, { + silent: silentAssetErrors + }) + } + + void useSubgraphNavigationStore().updateHash() + requestAnimationFrame(() => { + this.canvas.setDirty(true, true) + }) + } finally { + ChangeTracker.isLoadingGraph = false + } + } + + async refreshMissingModels( + options: { silent?: boolean; reloadDefs?: boolean } = {} + ): Promise { + return refreshMissingModelPipeline({ + graph: this.rootGraph, + reloadNodeDefs: + options.reloadDefs === false ? undefined : () => this.reloadNodeDefs(), + missingModelStore: useMissingModelStore(), + silent: options.silent ?? true + }) + } + + async graphToPrompt(graph = this.rootGraph) { + return graphToPrompt(graph, { + sortNodes: useSettingStore().get('Comfy.Workflow.SortNodeIdOnSave') + }) + } + + async queuePrompt( + number: number, + batchCount: number = 1, + queueNodeIds?: NodeExecutionId[] + ): Promise { + const requestId = this.nextQueueRequestId++ + this.queueItems.push({ number, batchCount, queueNodeIds, requestId }) + api.dispatchCustomEvent('promptQueueing', { + requestId, + batchCount + }) + + // Only have one action process the items so each one gets a unique seed correctly + if (this.processingQueue) { + return false + } + + this.processingQueue = true + const executionStore = useExecutionStore() + const executionErrorStore = useExecutionErrorStore() + executionErrorStore.clearAllErrors() + let queueResultOverride: boolean | null = null + + // Get auth token for backend nodes - uses workspace token if enabled, otherwise Firebase token + const comfyOrgAuthToken = await useAuthStore().getAuthToken() + const comfyOrgApiKey = useApiKeyAuthStore().getApiKey() + + try { + while (this.queueItems.length) { + const { number, batchCount, queueNodeIds, requestId } = + this.queueItems.pop()! + let queuedCount = 0 + const previewMethod = useSettingStore().get( + 'Comfy.Execution.PreviewMethod' + ) + + const isPartialExecution = !!queueNodeIds?.length + for (let i = 0; i < batchCount; i++) { + // Allow widgets to run callbacks before a prompt has been queued + // e.g. random seed before every gen + forEachNode(this.rootGraph, (node) => { + for (const widget of node.widgets ?? []) { + widget.beforeQueued?.({ isPartialExecution }) + } + applyPromotedWidgetControl(node, 'beforeQueued', { + isPartialExecution + }) + }) + + // Capture workflow before await — activeWorkflow may change if the + // user switches tabs while the request is in flight. + const queuedWorkflow = useWorkspaceStore().workflow + .activeWorkflow as ComfyWorkflow + const startTime = performance.now() + const p = await this.graphToPrompt(this.rootGraph) + const queuedNodes = collectAllNodes(this.rootGraph) + try { + api.authToken = comfyOrgAuthToken + api.apiKey = comfyOrgApiKey ?? undefined + const res = await api.queuePrompt(number, p, { + partialExecutionTargets: queueNodeIds, + previewMethod + }) + delete api.authToken + delete api.apiKey + executionErrorStore.recordNodeErrors(res.node_errors ?? null) + queueResultOverride = null + try { + if (res.prompt_id) { + executionStore.storeJob({ + id: res.prompt_id, + nodes: Object.keys(p.output), + promptOutput: p.output, + startTime, + workflow: queuedWorkflow + }) + } + } catch (error) { + console.warn('Failed to store queued job metadata', { + promptId: res.prompt_id, + error + }) + } + if (executionErrorStore.hasNodeError) { + if (useSettingStore().get('Comfy.RightSidePanel.ShowErrorsTab')) { + executionErrorStore.showErrorOverlay() + } + this.canvas.draw(true, true) + } + } catch (error: unknown) { + const hasPromptNodeErrors = + error instanceof PromptExecutionError && + Object.keys(error.response.node_errors ?? {}).length > 0 + const preconditionResponseError = + error instanceof PromptExecutionError && + typeof error.response.error === 'object' + ? error.response.error + : undefined + const promptPrecondition = preconditionResponseError + ? resolveAccountPrecondition({ + exceptionType: preconditionResponseError.type, + exceptionMessage: preconditionResponseError.message + }) + : undefined + // Account preconditions (sign-in, subscription, credits) open their + // own modal and must stay out of the error panel and error count. + if (promptPrecondition) { + useAccountPreconditionDialog().open(promptPrecondition) + console.error(error) + break + } + if ( + error instanceof PromptExecutionError && + typeof error.response.error === 'object' && + error.response.error?.type === 'missing_node_type' + ) { + // Re-scan the full graph instead of using the server's single-node response. + rescanAndSurfaceMissingNodes(this.rootGraph) + } else if ( + error instanceof PromptExecutionError && + error.status === 403 && + !hasPromptNodeErrors + ) { + // User is authenticated but not authorized (e.g. not whitelisted). + // Show a clear message instead of a generic error or sign-in prompt. + // The response may be middleware JSON {"message": "..."} or the + // standard {"error": {"message": "..."}} shape, so check both. + const raw = + error.response && typeof error.response === 'object' + ? (error.response as Record) + : {} + const rawError = + raw.error && typeof raw.error === 'object' + ? (raw.error as Record) + : undefined + const detail = + typeof raw.message === 'string' + ? raw.message + : typeof rawError?.message === 'string' + ? rawError.message + : typeof raw.error === 'string' + ? raw.error + : t('errorDialog.accessRestrictedMessage') + useDialogService().showErrorDialog(new Error(detail), { + title: t('errorDialog.accessRestrictedTitle'), + reportType: 'accessRestrictedError' + }) + } else if ( + !useSettingStore().get('Comfy.RightSidePanel.ShowErrorsTab') || + !(error instanceof PromptExecutionError) + ) { + useDialogService().showErrorDialog(error, { + title: t('errorDialog.promptExecutionError'), + reportType: 'promptExecutionError' + }) + } + console.error(error) + + if (error instanceof PromptExecutionError) { + // Keep the legacy result before empty node errors are normalized. + const nodeErrors = error.response.node_errors + queueResultOverride = !nodeErrors + executionErrorStore.recordNodeErrors(nodeErrors ?? null) + + // Store prompt-level error separately only when no node-specific errors exist, + // because node errors already carry the full context. Prompt-level errors + // (e.g. prompt_no_outputs, no_prompt) lack node IDs and need their own path. + if (!executionErrorStore.hasNodeError) { + const promptError = normalizePromptError(error.response.error) + if (promptError) { + executionErrorStore.recordPromptError(promptError) + } + } + + if (useSettingStore().get('Comfy.RightSidePanel.ShowErrorsTab')) { + executionErrorStore.showErrorOverlay() + } + this.canvas.draw(true, true) + } + break + } + + queuedCount++ + + // Allow widgets to run callbacks after a prompt has been queued + // e.g. random seed after every gen + executeWidgetsCallback(queuedNodes, 'afterQueued', { + isPartialExecution + }) + for (const node of queuedNodes) { + applyPromotedWidgetControl(node, 'afterQueued', { + isPartialExecution + }) + } + useFreeTierQuota().trackRun() + this.canvas.draw(true, true) + await this.ui.queue.update() + } + + if (queuedCount > 0) { + api.dispatchCustomEvent('promptQueued', { + number, + batchCount: queuedCount, + requestId + }) + } + } + } finally { + this.processingQueue = false + } + return queueResultOverride ?? !executionErrorStore.lastNodeErrors + } + + showErrorOnFileLoad(file: File) { + useToastStore().addAlert( + t('toastMessages.fileLoadError', { fileName: file.name }) + ) + } + + /** + * Loads workflow data from the specified file + * @param {File} file + */ + async handleFile( + file: File, + openSource?: WorkflowOpenSource, + options?: { + deferWarnings?: boolean + onNodeCreated?: (node: LGraphNode) => void + } + ) { + const fileName = file.name.replace(/\.\w+$/, '') // Strip file extension + const workflowData = await getWorkflowDataFromFile(file) + const { workflow, prompt, parameters, templates } = workflowData ?? {} + + if (!(workflow || prompt || parameters || templates)) { + const mediaNodeTypes: Record = { + image: ['LoadImage', pasteImageNode], + audio: ['LoadAudio', pasteAudioNode], + video: ['LoadVideo', pasteVideoNode] + } + + const mediaType = Object.keys(mediaNodeTypes).find((t) => + file.type.startsWith(t) + ) + if (mediaType) { + const [nodeType, pasteFn] = mediaNodeTypes[mediaType] + const transfer = new DataTransfer() + transfer.items.add(file) + const node = await createNode(this.canvas, nodeType) + await pasteFn(this.canvas, transfer.items, node) + if (node) options?.onNodeCreated?.(node) + return + } + + if (isMeshModelFile(file)) { + const node = await this.handleMeshFile(file) + if (node) options?.onNodeCreated?.(node) + return + } + + this.showErrorOnFileLoad(file) + return + } + + if ( + templates && + typeof templates === 'object' && + Array.isArray(templates) + ) { + this.loadTemplateData({ + templates: templates as { name?: string; data?: string }[] + }) + } + + // Check workflow first - it should take priority over parameters + // when both are present (e.g., in ComfyUI-generated PNGs) + if (workflow) { + let workflowObj: ComfyWorkflowJSON | undefined = undefined + try { + workflowObj = + typeof workflow === 'string' + ? parseJsonWithNonFinite(workflow) + : (workflow as ComfyWorkflowJSON) + + // Only load workflow if parsing succeeded AND validation passed + if ( + workflowObj && + typeof workflowObj === 'object' && + !Array.isArray(workflowObj) + ) { + await this.loadGraphData(workflowObj, true, true, fileName, { + openSource, + deferWarnings: options?.deferWarnings + }) + return + } else { + console.error( + 'Invalid workflow structure, trying parameters fallback' + ) + this.showErrorOnFileLoad(file) + } + } catch (err) { + console.error('Failed to parse workflow:', err) + this.showErrorOnFileLoad(file) + // Fall through to check parameters as fallback + } + } + + if (prompt) { + try { + const promptObj = + typeof prompt === 'string' + ? parseJsonWithNonFinite(prompt) + : prompt + if (this.isApiJson(promptObj)) { + this.loadApiJson(promptObj, fileName) + return + } + } catch (err) { + console.error('Failed to parse prompt:', err) + } + // Fall through to parameters as a last resort + } + + // Use parameters strictly as the final fallback + if (parameters && typeof parameters === 'string') { + useWorkflowService().beforeLoadNewGraph() + importA1111(this.rootGraph, parameters) + useWorkflowService().afterLoadNewGraph( + fileName, + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON + ) + return + } + + this.showErrorOnFileLoad(file) + } + + /** + * Uploads a mesh model file and creates a Load3DAdvanced node displaying it + * @param {File} file + */ + private async handleMeshFile(file: File): Promise { + const uploadedPath = await Load3dUtils.uploadFile(file, '3d') + if (!uploadedPath) return null + + const node = await createNode(this.canvas, 'Load3DAdvanced') + if (!node) return null + + const modelWidget = node.widgets?.find((w) => w.name === 'model_file') + if (!modelWidget) return node + + const values = (modelWidget.options as { values?: string[] } | undefined) + ?.values + if (values && !values.includes(uploadedPath)) { + values.push(uploadedPath) + } + modelWidget.value = uploadedPath + return node + } + + /** + * Loads multiple files, connects to a batch node, and selects them + * @param {FileList} fileList + */ + async handleFileList(fileList: File[]) { + if (fileList.length === 0) return + if (!fileList[0].type.startsWith('image')) return + + const imageNodes = await pasteImageNodes(this.canvas, fileList) + if (imageNodes.length === 0) return + + if (imageNodes.length > 1) { + const batchImagesNode = await createNode(this.canvas, 'BatchImagesNode') + if (!batchImagesNode) return + + this.positionBatchNodes(imageNodes, batchImagesNode) + this.canvas.selectItems([...imageNodes, batchImagesNode]) + + imageNodes.forEach((imageNode, index) => { + imageNode.connect(0, batchImagesNode, index) + }) + } else { + this.canvas.selectItems(imageNodes) + } + } + + async handleAudioFileList(fileList: File[]) { + const audioNodes = await pasteAudioNodes(this.canvas, fileList) + if (audioNodes.length === 0) return + + this.positionNodes(audioNodes) + this.canvas.selectItems(audioNodes) + } + + async handleVideoFileList(fileList: File[]) { + const videoNodes = await pasteVideoNodes(this.canvas, fileList) + if (videoNodes.length === 0) return + + this.positionNodes(videoNodes) + this.canvas.selectItems(videoNodes) + } + + /** + * Positions batched nodes in drag and drop + * @param nodes + * @param batchNode + */ + positionNodes(nodes: LGraphNode[]): void { + if (nodes.length <= 1) return + + const [x, y] = nodes[0].getBounding() + const nodeHeight = 150 + + nodes.forEach((node, index) => { + if (index > 0) { + node.pos = [x, y + nodeHeight * index + 25 * (index + 1)] + } + }) + + this.canvas.graph?.change() + } + + positionBatchNodes(nodes: LGraphNode[], batchNode: LGraphNode): void { + const [x, y, width] = nodes[0].getBounding() + batchNode.pos = [x + width + 100, y + 30] + + // Retrieving Node Height is inconsistent + let height = 0 + if (nodes[0].type === 'LoadImage') { + height = 344 + } + + nodes.forEach((node, index) => { + if (index > 0) { + node.pos = [x, y + height * index + 25 * (index + 1)] + } + }) + + this.canvas.graph?.change() + } + + // @deprecated + isApiJson(data: unknown): data is ComfyApiWorkflow { + if (!_.isObject(data) || Array.isArray(data)) { + return false + } + if (Object.keys(data).length === 0) return false + + return Object.values(data).every((node) => { + if (!node || typeof node !== 'object' || Array.isArray(node)) { + return false + } + + const { class_type: classType, inputs } = node as Record + const inputsIsRecord = _.isObject(inputs) && !Array.isArray(inputs) + return typeof classType === 'string' && inputsIsRecord + }) + } + + loadApiJson(apiData: ComfyApiWorkflow, fileName: string) { + useWorkflowService().beforeLoadNewGraph() + + const missingNodeTypes = Object.values(apiData).filter( + (n) => !LiteGraph.registered_node_types[n.class_type] + ) + if (missingNodeTypes.length) { + this.showMissingNodesError(missingNodeTypes.map((t) => t.class_type)) + } + + const ids = Object.keys(apiData) + app.rootGraph.clear() + for (const id of ids) { + const data = apiData[id] + const node = LiteGraph.createNode(data.class_type) + if (!node) continue + node.id = toNodeId(isNaN(+id) ? id : +id) + node.title = data._meta?.title ?? node.title + app.rootGraph.add(node) + } + + const processNodeInputs = (id: string) => { + const data = apiData[id] + const currentNodeId = toNodeId(isNaN(+id) ? id : +id) + const node = app.rootGraph.getNodeById(currentNodeId) + if (!node) return + + for (const input in data.inputs ?? {}) { + const value = data.inputs[input] + if (value instanceof Array) { + const [fromId, fromSlot] = value + const fromNode = app.rootGraph.getNodeById(toNodeId(fromId)) + if (!fromNode) continue + + let toSlot = node.inputs?.findIndex((inp) => inp.name === input) ?? -1 + if (toSlot === -1) { + try { + const widget = node.widgets?.find((w) => w.name === input) + const convertFn = ( + node as LGraphNode & { + convertWidgetToInput?: (w: IBaseWidget) => boolean + } + ).convertWidgetToInput + if (widget && convertFn?.(widget)) { + // Re-find the target slot by name after conversion + toSlot = + node.inputs?.findIndex((inp) => inp.name === input) ?? -1 + } + } catch (_error) { + // Ignore conversion errors + } + } + if (toSlot !== -1) { + fromNode.connect(fromSlot, node, toSlot) + } + } else { + const widget = node.widgets?.find((w) => w.name === input) + if (widget) { + widget.value = value + widget.callback?.(value) + } + } + } + } + + for (const id of ids) processNodeInputs(id) + app.rootGraph.arrange() + for (const id of ids) processNodeInputs(id) + app.rootGraph.arrange() + + useWorkflowService().afterLoadNewGraph( + fileName, + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON + ) + } + + /** + * Registers a Comfy web extension with the app + * @param {ComfyExtension} extension + */ + registerExtension(extension: ComfyExtension) { + useExtensionService().registerExtension(extension) + } + + /** + * Collects context menu items from all extensions for canvas menus + * @param canvas The canvas instance + * @returns Array of context menu items from all extensions + */ + collectCanvasMenuItems(canvas: LGraphCanvas): IContextMenuValue[] { + return useExtensionService() + .invokeExtensions('getCanvasMenuItems', canvas) + .flat() as IContextMenuValue[] + } + + /** + * Collects context menu items from all extensions for node menus + * @param node The node being right-clicked + * @returns Array of context menu items from all extensions + */ + collectNodeMenuItems(node: LGraphNode): IContextMenuValue[] { + return useExtensionService() + .invokeExtensions('getNodeMenuItems', node) + .flat() as IContextMenuValue[] + } + + /** + * Reload node definitions and refresh combo lists on all nodes. + */ + async reloadNodeDefs() { + const defs = await this.getNodeDefs() + for (const nodeId in defs) { + this.registerNodeDef(nodeId, defs[nodeId]) + } + // Refresh combo widgets in all nodes including those in subgraphs + const nodeOutputStore = useNodeOutputStore() + forEachNode(this.rootGraph, (node) => { + const def = defs[node.type] + // Allow primitive nodes to handle refresh + node.refreshComboInNode?.(defs) + + if (!def?.input) return + + if (node.widgets) { + const nodeInputs = def.input + for (const widget of node.widgets) { + if (widget.type === 'combo') { + let inputType: 'required' | 'optional' | undefined + if (nodeInputs.required?.[widget.name] !== undefined) { + inputType = 'required' + } else if (nodeInputs.optional?.[widget.name] !== undefined) { + inputType = 'optional' + } + if (inputType !== undefined) { + // Get the input spec associated with the widget + const inputSpec = nodeInputs[inputType]?.[widget.name] + if (inputSpec) { + // Refresh the combo widget's options with the values from the input spec + if (isComboInputSpecV2(inputSpec)) { + widget.options.values = inputSpec[1]?.options + } else if (isComboInputSpecV1(inputSpec)) { + widget.options.values = inputSpec[0] + } + } + } + } + } + } + + // Re-trigger previews on media nodes (e.g. LoadImage) + // to bust browser cache when files are edited externally + if (isImageNode(node) || isVideoNode(node)) { + nodeOutputStore.refreshNodeOutputs(node) + } + }) + + await useExtensionService().invokeExtensionsAsync( + 'refreshComboInNodes', + defs + ) + + // Promoted widgets keep hosted option snapshots; sync them after source refresh hooks run. + syncPromotedComboHostOptions(this.rootGraph) + + if (this.vueAppReady) { + this.updateVueAppNodeDefs(defs) + } + } + + /** + * Refresh combo list on whole nodes + */ + async refreshComboInNodes() { + const requestToastMessage: ToastMessageOptions = { + severity: 'info', + summary: t('g.update'), + detail: t('toastMessages.updateRequested') + } + if (this.vueAppReady) { + useToastStore().add(requestToastMessage) + } + + try { + await this.reloadNodeDefs() + + if (this.vueAppReady) { + useToastStore().add({ + severity: 'success', + summary: t('g.updated'), + detail: t('toastMessages.nodeDefinitionsUpdated'), + life: 1000 + }) + } + } catch (error) { + if (this.vueAppReady) { + useToastStore().add({ + severity: 'error', + summary: t('g.error'), + detail: t('toastMessages.nodeDefinitionsUpdateFailed') + }) + } + throw error + } finally { + if (this.vueAppReady) { + useToastStore().remove(requestToastMessage) + } + } + } + + /** + * Clean current state + */ + clean() { + const nodeOutputStore = useNodeOutputStore() + nodeOutputStore.resetAllOutputsAndPreviews() + const executionErrorStore = useExecutionErrorStore() + executionErrorStore.clearAllErrors() + + useDomWidgetStore().clear() + + // Subgraph does not properly implement `clear` and the parent class's + // (`LGraph`) `clear` breaks the subgraph structure. + if (this.rootGraph && !this.canvas.subgraph) { + this.rootGraph.clear() + } + } + + clientPosToCanvasPos(pos: Vector2): Vector2 { + if (!this.positionConversion) { + throw new Error('clientPosToCanvasPos called before setup') + } + return this.positionConversion.clientPosToCanvasPos(pos) + } + + canvasPosToClientPos(pos: Vector2): Vector2 { + if (!this.positionConversion) { + throw new Error('canvasPosToClientPos called before setup') + } + return this.positionConversion.canvasPosToClientPos(pos) + } +} + +export const app = new ComfyApp() diff --git a/docs/hel-892/setget-reference/1.48.6__src__utils__executionUtil.ts b/docs/hel-892/setget-reference/1.48.6__src__utils__executionUtil.ts new file mode 100644 index 00000000..0b6ad406 --- /dev/null +++ b/docs/hel-892/setget-reference/1.48.6__src__utils__executionUtil.ts @@ -0,0 +1,160 @@ +import type { + ExecutableLGraphNode, + ExecutionId, + LGraph +} from '@/lib/litegraph/src/litegraph' +import { + ExecutableNodeDTO, + LGraphEventMode +} from '@/lib/litegraph/src/litegraph' +import type { + ComfyApiWorkflow, + ComfyWorkflowJSON +} from '@/platform/workflow/validation/schemas/workflowSchema' + +import { compressWidgetInputSlots } from './litegraphUtil' + +/** + * Converts the current graph workflow for sending to the API. + * @note Node widgets are updated before serialization to prepare queueing. + * + * @param graph The graph to convert. + * @param options The options for the conversion. + * - `sortNodes`: Whether to sort the nodes by execution order. + * @returns The workflow and node links + */ +export const graphToPrompt = async ( + graph: LGraph, + options: { sortNodes?: boolean } = {} +): Promise<{ workflow: ComfyWorkflowJSON; output: ComfyApiWorkflow }> => { + const { sortNodes = false } = options + + for (const node of graph.computeExecutionOrder(false)) { + const innerNodes = node.getInnerNodes + ? node.getInnerNodes(new Map()) + : [node] + for (const innerNode of innerNodes) { + if (innerNode.isVirtualNode) { + innerNode.applyToGraph?.() + } + } + } + + const workflow = graph.serialize({ sortNodes }) + + // Remove localized_name from the workflow + for (const node of workflow.nodes) { + for (const slot of node.inputs ?? []) { + delete slot.localized_name + } + for (const slot of node.outputs ?? []) { + delete slot.localized_name + } + } + + compressWidgetInputSlots(workflow) + workflow.extra ??= {} + workflow.extra.frontendVersion = __COMFYUI_FRONTEND_VERSION__ + + const nodeDtoMap = new Map() + for (const node of graph.computeExecutionOrder(false)) { + const dto: ExecutableLGraphNode = new ExecutableNodeDTO( + node, + [], + nodeDtoMap + ) + + nodeDtoMap.set(dto.id, dto) + + if ( + node.mode === LGraphEventMode.NEVER || + node.mode === LGraphEventMode.BYPASS + ) { + continue + } + + for (const innerNode of dto.getInnerNodes()) { + nodeDtoMap.set(innerNode.id, innerNode) + } + } + + const output: ComfyApiWorkflow = {} + // Process nodes in order of execution + for (const node of nodeDtoMap.values()) { + // Don't serialize muted nodes + if ( + node.isVirtualNode || + node.mode === LGraphEventMode.NEVER || + node.mode === LGraphEventMode.BYPASS + ) { + continue + } + + const inputs: ComfyApiWorkflow[string]['inputs'] = {} + const { widgets } = node + + // Store all widget values in the API prompt. + // Note: widget.options.serialize controls prompt inclusion (checked here). + // widget.serialize controls workflow persistence (checked by LGraphNode). + if (widgets) { + for (const [i, widget] of widgets.entries()) { + if (!widget.name || widget.options?.serialize === false) continue + + const widgetValue = widget.serializeValue + ? await widget.serializeValue(node, i) + : widget.value + // By default, Array values are reserved to represent node connections. + // We need to wrap the array as an object to avoid the misinterpretation + // of the array as a node connection. + // The backend automatically unwraps the object to an array during + // execution. + inputs[widget.name] = Array.isArray(widgetValue) + ? widget.type === 'curve' + ? { __type__: 'CURVE', __value__: widgetValue } + : { __value__: widgetValue } + : widgetValue + } + } + + // Store all node links + for (const [i, input] of node.inputs.entries()) { + const resolvedInput = node.resolveInput(i) + if (!resolvedInput) continue + + // Resolved to an actual widget value rather than a node connection + if (resolvedInput.widgetInfo) { + const { value } = resolvedInput.widgetInfo + inputs[input.name] = Array.isArray(value) ? { __value__: value } : value + continue + } + + inputs[input.name] = [ + String(resolvedInput.origin_id), + // @ts-expect-error link.origin_slot is already number. + parseInt(resolvedInput.origin_slot) + ] + } + + output[String(node.id)] = { + inputs, + // TODO(huchenlei): Filter out all nodes that cannot be mapped to a + // comfyClass. + class_type: node.comfyClass!, + // Ignored by the backend. + _meta: { + title: node.title + } + } + } + + // Remove inputs connected to removed nodes + for (const { inputs } of Object.values(output)) { + for (const [i, input] of Object.entries(inputs)) { + if (Array.isArray(input) && input.length === 2 && !output[input[0]]) { + delete inputs[i] + } + } + } + + return { workflow: workflow as ComfyWorkflowJSON, output } +} diff --git a/docs/hel-892/setget-reference/LICENSE b/docs/hel-892/setget-reference/LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/docs/hel-892/setget-reference/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/docs/hel-892/setget-reference/__init__.py b/docs/hel-892/setget-reference/__init__.py new file mode 100644 index 00000000..66c76b1c --- /dev/null +++ b/docs/hel-892/setget-reference/__init__.py @@ -0,0 +1,458 @@ +from .nodes.nodes import ( + BOOLConstant, INTConstant, FloatConstant, StringConstant, StringConstantMultiline, + ScaleBatchPromptSchedule, GetLatentsFromBatchIndexed, ConditioningMultiCombine, + AppendStringsToList, JoinStrings, JoinStringMulti, CondPassThrough, ModelPassThrough, + ConditioningSetMaskAndCombine, ConditioningSetMaskAndCombine3, + ConditioningSetMaskAndCombine4, ConditioningSetMaskAndCombine5, + VRAM_Debug, SomethingToString, Sleep, EmptyLatentImagePresets, + EmptyLatentImageCustomPresets, WidgetToString, DummyOut, FlipSigmasAdjusted, + CustomSigmas, StringToFloatList, InjectNoiseToLatent, SoundReactive, GenerateNoise, + StableZero123_BatchSchedule, SV3D_BatchSchedule, Superprompt, CameraPoseVisualizer, + CheckpointPerturbWeights, DifferentialDiffusionAdvanced, FluxBlockLoraSelect, + HunyuanVideoBlockLoraSelect, Wan21BlockLoraSelect, LTX2BlockLoraSelect, + DiTBlockLoraLoader, CustomControlNetWeightsFluxFromList, + SetShakkerLabsUnionControlNetType, ModelSaveKJ, StyleModelApplyAdvanced, + AudioConcatenate, LeapfusionHunyuanI2V, ImageNoiseAugmentation, VAELoaderKJ, VAEMergeKJ, + ScheduledCFGGuidance, ApplyRifleXRoPE_WanVideo, ApplyRifleXRoPE_HunuyanVideo, + TimerNodeKJ, HunyuanVideoEncodeKeyframesToCond, LazySwitchKJ, LatentInpaintTTM, + SimpleCalculatorKJ, GetTrackRange, AddNoiseToTrackPath, VAEDecodeLoopKJ, + WanImageToVideoSVIPro, DeprecatedCompileNodeKJ, VisualizeSigmasKJ, + PreviewLatentNoiseMask, PlaySoundKJ, +) +from .nodes.curve_nodes import ( + PlotCoordinates, SplineEditor, CreateShapeMaskOnPath, CreateShapeImageOnPath, + CreateTextOnPath, CreateGradientFromCoords, GradientToFloat, MaskOrImageToWeight, + WeightScheduleConvert, FloatToMask, WeightScheduleExtend, FloatToSigmas, SigmasToFloat, + GLIGENTextBoxApplyBatchCoords, CreateInstanceDiffusionTracking, + AppendInstanceDiffusionTracking, InterpolateCoords, DrawInstanceDiffusionTracking, + PointsEditor, CutAndDragOnPath, +) +from .nodes.batchcrop_nodes import ( + BatchCropFromMask, BatchUncrop, BatchCropFromMaskAdvanced, + FilterZeroMasksAndCorrespondingImages, InsertImageBatchByIndexes, BatchUncropAdvanced, + SplitBboxes, BboxToInt, BboxVisualize, +) +from .nodes.audioscheduler_nodes import ( + NormalizedAmplitudeToMask, NormalizedAmplitudeToFloatList, + OffsetMaskByNormalizedAmplitude, ImageTransformByNormalizedAmplitude, +) +from .nodes.image_nodes import ( + ImagePass, ColorMatch, ColorMatchV2, SaveImageWithAlpha, ImageConcanate, + ImageConcatFromBatch, ImageGridComposite2x2, ImageGridComposite3x3, + ImageBatchTestPattern, ImageGrabPIL, Screencap_mss, ScreencapStream, WebcamCaptureCV2, + AddLabel, GetImageSizeAndCount, GetLatentSizeAndCount, ImageBatchRepeatInterleaving, + ImageUpscaleWithModelBatched, ImageNormalize_Neg1_To_1, RemapImageRange, + SplitImageChannels, MergeImageChannels, ImagePadForOutpaintMasked, + ImagePadForOutpaintTargetSize, ImagePrepForICLora, ImageAndMaskPreview, + CrossFadeImages, CrossFadeImagesMulti, TransitionImagesMulti, TransitionImagesInBatch, + ImageBatchJoinWithTransition, ShuffleImageBatch, GetImageRangeFromBatch, + RandomImageFromBatch, ImageBatchExtendWithOverlap, GetLatentRangeFromBatch, + InsertLatentToIndex, ImageBatchFilter, GetImagesFromBatchIndexed, + InsertImagesToBatchIndexed, PadImageBatchInterleaved, ReplaceImagesInBatch, + ReverseImageBatch, ImageBatchMulti, ImageTensorList, ImageAddMulti, ImageConcatMulti, + PreviewAnimation, ImageResizeKJ, ImageResizeKJv2, LoadAndResizeImage, + LoadImagesFromFolderKJ, ImageGridtoBatch, SaveImageKJ, SaveStringKJ, FastPreview, + FastPreviewBatch, ImageCropByMaskAndResize, ImageCropByMask, ImageUncropByMask, + ImageCropByMaskBatch, ImagePadKJ, LoadVideosFromFolder, EncodeVideoComponents, + DecodeAndSaveVideo, PreviewImageOrMask, +) + +from .nodes.mask_nodes import ( + BatchCLIPSeg, DownloadAndLoadCLIPSeg, CreateTextMask, ColorToMask, CreateFluidMask, + CreateAudioMask, CreateGradientMask, CreateFadeMask, CreateFadeMaskAdvanced, + CreateMagicMask, CreateShapeMask, CreateVoronoiMask, GetMaskSizeAndCount, + GrowMaskWithBlur, MaskBatchMulti, OffsetMask, RoundMask, ResizeMask, RemapMaskRange, + SeparateMasks, ConsolidateMasksKJ, DrawMaskOnImage, BlockifyMask, +) +from .nodes.model_optimization_nodes import ( + PathchSageAttentionKJ, PatchFlashAttentionKJ, CheckpointLoaderKJ, DiffusionModelSelector, + DiffusionModelLoaderKJ, ModelPatchTorchSettings, PatchModelPatcherOrder, + TorchCompileModelFluxAdvancedV2, TorchCompileModelWanVideoV2, + TorchCompileModelAdvanced, TorchCompileVAE, TorchCompileControlNet, + WanVideoTeaCacheKJ, WanVideoEnhanceAVideoKJ, LTXVEnhanceAVideoKJ, WanVideoNAG, Krea2PromptWeight, MossImagePromptWeight, + SkipLayerGuidanceWanVideo, CFGZeroStarAndInit, GGUFLoaderKJ, NABLA_AttentionKJ, + StartRecordCUDAMemoryHistory, EndRecordCUDAMemoryHistory, VisualizeCUDAMemoryHistory, + ModelMemoryUseReportPatch, ModelMemoryUsageFactorOverride, WanChunkFeedForward, + SamplerSelfRefineVideo, PiDColorBiasCorrection, Ideogram4OptimizationsKJ, +) +from .nodes.lora_nodes import LoraExtractKJ, LoraReduceRank +from .nodes.image_transform_node import ImageTransformKJ, BBOXToBoundingBoxKJ +from .nodes.image_compare_node import ImageCompareKJ +from .nodes.sharpen_nodes import ImageSharpenKJ +from .nodes.nodes_looping import LOOP_NODES +from .nodes.hdr_preview_node import HDRPreviewKJ +from .nodes.preview_override_node import ModelPreviewOverrideKJ, GetPreviewOverrideFramesKJ +from .nodes.context_windows_visualizer import ContextWindowsVisualizerKJ +from .nodes.ideogram4_nodes import Ideogram4PromptBuilderKJ +from .nodes.flux3_nodes import Flux3PromptBuilderKJ, Flux3BoxReconcileKJ +from .nodes.moss_image_nodes import MossImagePromptBuilderKJ + +import logging + +NODE_CONFIG = { + #constants + "BOOLConstant": {"class": BOOLConstant, "name": "BOOL Constant"}, + "INTConstant": {"class": INTConstant, "name": "INT Constant"}, + "FloatConstant": {"class": FloatConstant, "name": "Float Constant"}, + "StringConstant": {"class": StringConstant, "name": "String Constant"}, + "StringConstantMultiline": {"class": StringConstantMultiline, "name": "String Constant Multiline"}, + #conditioning + "ConditioningMultiCombine": {"class": ConditioningMultiCombine, "name": "Conditioning Multi Combine"}, + "ConditioningSetMaskAndCombine": {"class": ConditioningSetMaskAndCombine, "name": "ConditioningSetMaskAndCombine"}, + "ConditioningSetMaskAndCombine3": {"class": ConditioningSetMaskAndCombine3, "name": "ConditioningSetMaskAndCombine3"}, + "ConditioningSetMaskAndCombine4": {"class": ConditioningSetMaskAndCombine4, "name": "ConditioningSetMaskAndCombine4"}, + "ConditioningSetMaskAndCombine5": {"class": ConditioningSetMaskAndCombine5, "name": "ConditioningSetMaskAndCombine5"}, + "CondPassThrough": {"class": CondPassThrough}, + "WanImageToVideoSVIPro": {"class": WanImageToVideoSVIPro, "name": "Wan Image To Video SVIPro"}, + #masking + "DrawMaskOnImage": {"class": DrawMaskOnImage, "name": "Draw Mask On Image"}, + "DownloadAndLoadCLIPSeg": {"class": DownloadAndLoadCLIPSeg, "name": "(Down)load CLIPSeg"}, + "BatchCLIPSeg": {"class": BatchCLIPSeg, "name": "Batch CLIPSeg"}, + "BlockifyMask": {"class": BlockifyMask, "name": "Blockify Mask"}, + "ColorToMask": {"class": ColorToMask, "name": "Color To Mask"}, + "CreateGradientMask": {"class": CreateGradientMask, "name": "Create Gradient Mask"}, + "CreateTextMask": {"class": CreateTextMask, "name": "Create Text Mask"}, + "CreateAudioMask": {"class": CreateAudioMask, "name": "Create Audio Mask"}, + "CreateFadeMask": {"class": CreateFadeMask, "name": "Create Fade Mask"}, + "CreateFadeMaskAdvanced": {"class": CreateFadeMaskAdvanced, "name": "Create Fade Mask Advanced"}, + "CreateFluidMask": {"class": CreateFluidMask, "name": "Create Fluid Mask"}, + "CreateShapeMask": {"class": CreateShapeMask, "name": "Create Shape Mask"}, + "CreateVoronoiMask": {"class": CreateVoronoiMask, "name": "Create Voronoi Mask"}, + "CreateMagicMask": {"class": CreateMagicMask, "name": "Create Magic Mask"}, + "GetMaskSizeAndCount": {"class": GetMaskSizeAndCount, "name": "Get Mask Size & Count"}, + "GrowMaskWithBlur": {"class": GrowMaskWithBlur, "name": "Grow Mask With Blur"}, + "MaskBatchMulti": {"class": MaskBatchMulti, "name": "Mask Batch Multi"}, + "OffsetMask": {"class": OffsetMask, "name": "Offset Mask"}, + "RemapMaskRange": {"class": RemapMaskRange, "name": "Remap Mask Range"}, + "ResizeMask": {"class": ResizeMask, "name": "Resize Mask"}, + "RoundMask": {"class": RoundMask, "name": "Round Mask"}, + "SeparateMasks": {"class": SeparateMasks, "name": "Separate Masks"}, + "ConsolidateMasksKJ": {"class": ConsolidateMasksKJ, "name": "Consolidate Masks"}, + #images + "AddLabel": {"class": AddLabel, "name": "Add Label"}, + "ColorMatch": {"class": ColorMatch, "name": "Color Match"}, + "ColorMatchV2": {"class": ColorMatchV2, "name": "Color Match V2"}, + "ImageTensorList": {"class": ImageTensorList, "name": "Image Tensor List"}, + "CrossFadeImages": {"class": CrossFadeImages, "name": "Cross Fade Images"}, + "CrossFadeImagesMulti": {"class": CrossFadeImagesMulti, "name": "Cross Fade Images Multi"}, + "GetImagesFromBatchIndexed": {"class": GetImagesFromBatchIndexed, "name": "Get Images From Batch Indexed"}, + "GetImageRangeFromBatch": {"class": GetImageRangeFromBatch, "name": "Get Image or Mask Range From Batch"}, + "RandomImageFromBatch": {"class": RandomImageFromBatch, "name": "Random Image From Batch"}, + "GetLatentRangeFromBatch": {"class": GetLatentRangeFromBatch, "name": "Get Latent Range From Batch"}, + "GetLatentSizeAndCount": {"class": GetLatentSizeAndCount, "name": "Get Latent Size & Count"}, + "GetImageSizeAndCount": {"class": GetImageSizeAndCount, "name": "Get Image Size & Count"}, + "FastPreview": {"class": FastPreview, "name": "Fast Preview"}, + "FastPreviewBatch": {"class": FastPreviewBatch, "name": "Fast Preview Batch"}, + "ImageBatchFilter": {"class": ImageBatchFilter, "name": "Image Batch Filter"}, + "ImageAndMaskPreview": {"class": ImageAndMaskPreview}, + "ImageAddMulti": {"class": ImageAddMulti, "name": "Image Add Multi"}, + "ImageBatchJoinWithTransition": {"class": ImageBatchJoinWithTransition, "name": "Image Batch Join With Transition"}, + "ImageBatchMulti": {"class": ImageBatchMulti, "name": "Image Batch Multi"}, + "ImageBatchRepeatInterleaving": {"class": ImageBatchRepeatInterleaving}, + "ImageBatchTestPattern": {"class": ImageBatchTestPattern, "name": "Image Batch Test Pattern"}, + "ImageConcanate": {"class": ImageConcanate, "name": "Image Concatenate"}, + "ImageConcatFromBatch": {"class": ImageConcatFromBatch, "name": "Image Concatenate From Batch"}, + "ImageConcatMulti": {"class": ImageConcatMulti, "name": "Image Concatenate Multi"}, + "ImageCropByMask": {"class": ImageCropByMask, "name": "Image Crop By Mask"}, + "ImageCropByMaskAndResize": {"class": ImageCropByMaskAndResize, "name": "Image Crop By Mask And Resize"}, + "ImageCropByMaskBatch": {"class": ImageCropByMaskBatch, "name": "Image Crop By Mask Batch"}, + "ImageUncropByMask": {"class": ImageUncropByMask, "name": "Image Uncrop By Mask"}, + "ImageBatchExtendWithOverlap": {"class": ImageBatchExtendWithOverlap, "name": "Image Batch Extend With Overlap"}, + "ImageGrabPIL": {"class": ImageGrabPIL, "name": "Image Grab PIL"}, + "ImageGridComposite2x2": {"class": ImageGridComposite2x2, "name": "Image Grid Composite 2x2"}, + "ImageGridComposite3x3": {"class": ImageGridComposite3x3, "name": "Image Grid Composite 3x3"}, + "ImageGridtoBatch": {"class": ImageGridtoBatch, "name": "Image Grid To Batch"}, + "ImageNoiseAugmentation": {"class": ImageNoiseAugmentation, "name": "Image Noise Augmentation"}, + "ImageNormalize_Neg1_To_1": {"class": ImageNormalize_Neg1_To_1, "name": "Image Normalize -1 to 1"}, + "ImagePass": {"class": ImagePass}, + "ImagePadKJ": {"class": ImagePadKJ, "name": "ImagePad KJ"}, + "ImagePadForOutpaintMasked": {"class": ImagePadForOutpaintMasked, "name": "Image Pad For Outpaint Masked"}, + "ImagePadForOutpaintTargetSize": {"class": ImagePadForOutpaintTargetSize, "name": "Image Pad For Outpaint Target Size"}, + "ImagePrepForICLora": {"class": ImagePrepForICLora, "name": "Image Prep For ICLora"}, + "ImageResizeKJ": {"class": ImageResizeKJ, "name": "Resize Image (deprecated)"}, + "ImageResizeKJv2": {"class": ImageResizeKJv2, "name": "Resize Image v2"}, + "ImageUpscaleWithModelBatched": {"class": ImageUpscaleWithModelBatched, "name": "Image Upscale With Model Batched"}, + "InsertImagesToBatchIndexed": {"class": InsertImagesToBatchIndexed, "name": "Insert Images To Batch Indexed"}, + "InsertLatentToIndexed": {"class": InsertLatentToIndex, "name": "Insert Latent To Index"}, + "LoadAndResizeImage": {"class": LoadAndResizeImage, "name": "Load & Resize Image"}, + "LoadImagesFromFolderKJ": {"class": LoadImagesFromFolderKJ, "name": "Load Images From Folder (KJ)"}, + "LoadVideosFromFolder": {"class": LoadVideosFromFolder, "name": "Load Videos From Folder"}, + "MergeImageChannels": {"class": MergeImageChannels, "name": "Merge Image Channels"}, + "PadImageBatchInterleaved": {"class": PadImageBatchInterleaved, "name": "Pad Image Batch Interleaved"}, + "PreviewAnimation": {"class": PreviewAnimation, "name": "Preview Animation"}, + "RemapImageRange": {"class": RemapImageRange, "name": "Remap Image Range"}, + "ReverseImageBatch": {"class": ReverseImageBatch, "name": "Reverse Image Batch"}, + "ReplaceImagesInBatch": {"class": ReplaceImagesInBatch, "name": "Replace Images In Batch"}, + "SaveImageWithAlpha": {"class": SaveImageWithAlpha, "name": "Save Image With Alpha"}, + "SaveImageKJ": {"class": SaveImageKJ, "name": "Save Image KJ"}, + "ShuffleImageBatch": {"class": ShuffleImageBatch, "name": "Shuffle Image Batch"}, + "SplitImageChannels": {"class": SplitImageChannels, "name": "Split Image Channels"}, + "TransitionImagesMulti": {"class": TransitionImagesMulti, "name": "Transition Images Multi"}, + "TransitionImagesInBatch": {"class": TransitionImagesInBatch, "name": "Transition Images In Batch"}, + "EncodeVideoComponents": {"class": EncodeVideoComponents, "name": "Encode Video Components"}, + "DecodeAndSaveVideo": {"class": DecodeAndSaveVideo, "name": "Decode And Save Video"}, + "ImageTransformKJ": {"class": ImageTransformKJ, "name": "Image Transform KJ"}, + "ImageCompareKJ": {"class": ImageCompareKJ, "name": "Image Compare KJ"}, + "BBOXToBoundingBoxKJ": {"class": BBOXToBoundingBoxKJ, "name": "BBOX to Bounding Box KJ"}, + "Ideogram4PromptBuilderKJ": {"class": Ideogram4PromptBuilderKJ, "name": "Ideogram 4 Prompt Builder KJ"}, + "Flux3PromptBuilderKJ": {"class": Flux3PromptBuilderKJ, "name": "FLUX.3 Prompt Builder KJ"}, + "Flux3BoxReconcileKJ": {"class": Flux3BoxReconcileKJ, "name": "FLUX.3 Box Reconcile KJ"}, + "MossImagePromptBuilderKJ": {"class": MossImagePromptBuilderKJ, "name": "MOSS-Image Prompt Builder KJ"}, + "HDRPreviewKJ": {"class": HDRPreviewKJ, "name": "HDR Preview KJ"}, + "ModelPreviewOverrideKJ": {"class": ModelPreviewOverrideKJ, "name": "Model Preview Override KJ"}, + "GetPreviewOverrideFramesKJ": {"class": GetPreviewOverrideFramesKJ, "name": "Get Preview Override Frames KJ"}, + "PreviewImageOrMask": {"class": PreviewImageOrMask, "name": "Preview Image Or Mask"}, + "ImageSharpenKJ": {"class": ImageSharpenKJ, "name": "Image Sharpen KJ"}, + #batch cropping + "BatchCropFromMask": {"class": BatchCropFromMask, "name": "Batch Crop From Mask"}, + "BatchCropFromMaskAdvanced": {"class": BatchCropFromMaskAdvanced, "name": "Batch Crop From Mask Advanced"}, + "FilterZeroMasksAndCorrespondingImages": {"class": FilterZeroMasksAndCorrespondingImages}, + "InsertImageBatchByIndexes": {"class": InsertImageBatchByIndexes, "name": "Insert Image Batch By Indexes"}, + "BatchUncrop": {"class": BatchUncrop, "name": "Batch Uncrop"}, + "BatchUncropAdvanced": {"class": BatchUncropAdvanced, "name": "Batch Uncrop Advanced"}, + "SplitBboxes": {"class": SplitBboxes, "name": "Split Bboxes"}, + "BboxToInt": {"class": BboxToInt, "name": "Bbox To Int"}, + "BboxVisualize": {"class": BboxVisualize, "name": "Bbox Visualize"}, + #noise + "GenerateNoise": {"class": GenerateNoise, "name": "Generate Noise"}, + "FlipSigmasAdjusted": {"class": FlipSigmasAdjusted, "name": "Flip Sigmas Adjusted"}, + "InjectNoiseToLatent": {"class": InjectNoiseToLatent, "name": "Inject Noise To Latent"}, + "CustomSigmas": {"class": CustomSigmas, "name": "Custom Sigmas"}, + #utility + "StringToFloatList": {"class": StringToFloatList, "name": "String to Float List"}, + "WidgetToString": {"class": WidgetToString, "name": "Widget To String"}, + "SaveStringKJ": {"class": SaveStringKJ, "name": "Save String KJ"}, + "DummyOut": {"class": DummyOut, "name": "Dummy Out"}, + "GetLatentsFromBatchIndexed": {"class": GetLatentsFromBatchIndexed, "name": "Get Latents From Batch Indexed"}, + "ScaleBatchPromptSchedule": {"class": ScaleBatchPromptSchedule, "name": "Scale Batch Prompt Schedule"}, + "CameraPoseVisualizer": {"class": CameraPoseVisualizer, "name": "Camera Pose Visualizer"}, + "AppendStringsToList": {"class": AppendStringsToList, "name": "Append Strings To List"}, + "JoinStrings": {"class": JoinStrings, "name": "Join Strings"}, + "JoinStringMulti": {"class": JoinStringMulti, "name": "Join String Multi"}, + "SimpleCalculatorKJ": {"class": SimpleCalculatorKJ, "name": "Simple Calculator KJ"}, + "SomethingToString": {"class": SomethingToString, "name": "Something To String"}, + "Sleep": {"class": Sleep, "name": "Sleep"}, + "VRAM_Debug": {"class": VRAM_Debug, "name": "VRAM Debug"}, + "EmptyLatentImagePresets": {"class": EmptyLatentImagePresets, "name": "Empty Latent Image Presets"}, + "EmptyLatentImageCustomPresets": {"class": EmptyLatentImageCustomPresets, "name": "Empty Latent Image Custom Presets"}, + "ModelPassThrough": {"class": ModelPassThrough, "name": "ModelPass"}, + "ModelSaveKJ": {"class": ModelSaveKJ, "name": "Model Save KJ"}, + "SetShakkerLabsUnionControlNetType": {"class": SetShakkerLabsUnionControlNetType, "name": "Set Shakker Labs Union ControlNet Type"}, + "StyleModelApplyAdvanced": {"class": StyleModelApplyAdvanced, "name": "Style Model Apply Advanced"}, + "DiffusionModelSelector": {"class": DiffusionModelSelector, "name": "Diffusion Model Selector"}, + "LazySwitchKJ": {"class": LazySwitchKJ, "name": "Lazy Switch KJ"}, + "VisualizeSigmasKJ": {"class": VisualizeSigmasKJ, "name": "Visualize Sigmas KJ"}, + #audioscheduler stuff + "NormalizedAmplitudeToMask": {"class": NormalizedAmplitudeToMask}, + "NormalizedAmplitudeToFloatList": {"class": NormalizedAmplitudeToFloatList}, + "OffsetMaskByNormalizedAmplitude": {"class": OffsetMaskByNormalizedAmplitude}, + "ImageTransformByNormalizedAmplitude": {"class": ImageTransformByNormalizedAmplitude}, + "AudioConcatenate": {"class": AudioConcatenate}, + #curve nodes + "SplineEditor": {"class": SplineEditor, "name": "Spline Editor"}, + "CreateShapeImageOnPath": {"class": CreateShapeImageOnPath, "name": "Create Shape Image On Path"}, + "CreateShapeMaskOnPath": {"class": CreateShapeMaskOnPath, "name": "Create Shape Mask On Path"}, + "CreateTextOnPath": {"class": CreateTextOnPath, "name": "Create Text On Path"}, + "CreateGradientFromCoords": {"class": CreateGradientFromCoords, "name": "Create Gradient From Coords"}, + "CutAndDragOnPath": {"class": CutAndDragOnPath, "name": "Cut And Drag On Path"}, + "GradientToFloat": {"class": GradientToFloat, "name": "Gradient To Float"}, + "WeightScheduleExtend": {"class": WeightScheduleExtend, "name": "Weight Schedule Extend"}, + "MaskOrImageToWeight": {"class": MaskOrImageToWeight, "name": "Mask Or Image To Weight"}, + "WeightScheduleConvert": {"class": WeightScheduleConvert, "name": "Weight Schedule Convert"}, + "FloatToMask": {"class": FloatToMask, "name": "Float To Mask"}, + "FloatToSigmas": {"class": FloatToSigmas, "name": "Float To Sigmas"}, + "SigmasToFloat": {"class": SigmasToFloat, "name": "Sigmas To Float"}, + "PlotCoordinates": {"class": PlotCoordinates, "name": "Plot Coordinates"}, + "InterpolateCoords": {"class": InterpolateCoords, "name": "Interpolate Coords"}, + "PointsEditor": {"class": PointsEditor, "name": "Points Editor"}, + #experimental + "SoundReactive": {"class": SoundReactive, "name": "Sound Reactive"}, + "StableZero123_BatchSchedule": {"class": StableZero123_BatchSchedule, "name": "Stable Zero123 Batch Schedule"}, + "SV3D_BatchSchedule": {"class": SV3D_BatchSchedule, "name": "SV3D Batch Schedule"}, + "Superprompt": {"class": Superprompt, "name": "Superprompt"}, + "GLIGENTextBoxApplyBatchCoords": {"class": GLIGENTextBoxApplyBatchCoords}, + "CheckpointPerturbWeights": {"class": CheckpointPerturbWeights, "name": "CheckpointPerturbWeights"}, + "Screencap_mss": {"class": Screencap_mss, "name": "Screencap mss"}, + "ScreencapStream": {"class": ScreencapStream, "name": "Screencap Stream"}, + "WebcamCaptureCV2": {"class": WebcamCaptureCV2, "name": "Webcam Capture CV2"}, + "DifferentialDiffusionAdvanced": {"class": DifferentialDiffusionAdvanced, "name": "Differential Diffusion Advanced"}, + "DiTBlockLoraLoader": {"class": DiTBlockLoraLoader, "name": "DiT Block Lora Loader"}, + "FluxBlockLoraSelect": {"class": FluxBlockLoraSelect, "name": "Flux Block Lora Select"}, + "HunyuanVideoBlockLoraSelect": {"class": HunyuanVideoBlockLoraSelect, "name": "Hunyuan Video Block Lora Select"}, + "Wan21BlockLoraSelect": {"class": Wan21BlockLoraSelect, "name": "Wan21 Block Lora Select"}, + "LTX2BlockLoraSelect": {"class": LTX2BlockLoraSelect, "name": "LTX2 Block Lora Select"}, + "CustomControlNetWeightsFluxFromList": {"class": CustomControlNetWeightsFluxFromList, "name": "Custom ControlNet Weights Flux From List"}, + "CheckpointLoaderKJ": {"class": CheckpointLoaderKJ, "name": "CheckpointLoaderKJ"}, + "DiffusionModelLoaderKJ": {"class": DiffusionModelLoaderKJ, "name": "Diffusion Model Loader KJ"}, + "TorchCompileModelFluxAdvancedV2": {"class": TorchCompileModelFluxAdvancedV2, "name": "TorchCompileModelFluxAdvancedV2"}, + "TorchCompileVAE": {"class": TorchCompileVAE, "name": "TorchCompileVAE"}, + "TorchCompileControlNet": {"class": TorchCompileControlNet, "name": "TorchCompileControlNet"}, + "TorchCompileModelWanVideoV2": {"class": TorchCompileModelWanVideoV2, "name": "TorchCompileModelWanVideoV2"}, + "PathchSageAttentionKJ": {"class": PathchSageAttentionKJ, "name": "Patch Sage Attention KJ"}, + "PatchFlashAttentionKJ": {"class": PatchFlashAttentionKJ, "name": "Patch Flash Attention KJ"}, + "LeapfusionHunyuanI2VPatcher": {"class": LeapfusionHunyuanI2V, "name": "Leapfusion Hunyuan I2V Patcher"}, + "VAELoaderKJ": {"class": VAELoaderKJ, "name": "VAELoader KJ"}, + "VAEMergeKJ": {"class": VAEMergeKJ, "name": "VAE Merge KJ"}, + "VAEDecodeLoopKJ": {"class": VAEDecodeLoopKJ, "name": "VAE Decode Loop KJ"}, + "ScheduledCFGGuidance": {"class": ScheduledCFGGuidance, "name": "Scheduled CFG Guidance"}, + "ApplyRifleXRoPE_HunuyanVideo": {"class": ApplyRifleXRoPE_HunuyanVideo, "name": "Apply RifleXRoPE HunuyanVideo"}, + "ApplyRifleXRoPE_WanVideo": {"class": ApplyRifleXRoPE_WanVideo, "name": "Apply RifleXRoPE WanVideo"}, + "WanVideoTeaCacheKJ": {"class": WanVideoTeaCacheKJ, "name": "WanVideo Tea Cache (native)"}, + "WanVideoEnhanceAVideoKJ": {"class": WanVideoEnhanceAVideoKJ, "name": "WanVideo Enhance A Video (native)"}, + "SkipLayerGuidanceWanVideo": {"class": SkipLayerGuidanceWanVideo, "name": "Skip Layer Guidance WanVideo"}, + "TimerNodeKJ": {"class": TimerNodeKJ, "name": "Timer Node KJ"}, + "HunyuanVideoEncodeKeyframesToCond": {"class": HunyuanVideoEncodeKeyframesToCond, "name": "HunyuanVideo Encode Keyframes To Cond"}, + "CFGZeroStarAndInit": {"class": CFGZeroStarAndInit, "name": "CFG Zero Star/Init"}, + "PiDColorBiasCorrection": {"class": PiDColorBiasCorrection, "name": "PiD Color Bias Correction"}, + "ModelPatchTorchSettings": {"class": ModelPatchTorchSettings, "name": "Model Patch Torch Settings"}, + "WanVideoNAG": {"class": WanVideoNAG, "name": "WanVideoNAG"}, + "Krea2PromptWeight": {"class": Krea2PromptWeight, "name": "Krea2 Prompt Weight"}, + "MossImagePromptWeight": {"class": MossImagePromptWeight, "name": "MOSS-Image Prompt Weight"}, + "GGUFLoaderKJ": {"class": GGUFLoaderKJ, "name": "GGUF Loader KJ"}, + "LatentInpaintTTM": {"class": LatentInpaintTTM, "name": "Latent Inpaint TTM"}, + "NABLA_AttentionKJ": {"class": NABLA_AttentionKJ, "name": "NABLA Attention KJ"}, + "TorchCompileModelAdvanced": {"class": TorchCompileModelAdvanced, "name": "TorchCompileModelAdvanced"}, + "StartRecordCUDAMemoryHistory": {"class": StartRecordCUDAMemoryHistory, "name": "Start Recording CUDAMemory History"}, + "EndRecordCUDAMemoryHistory": {"class": EndRecordCUDAMemoryHistory, "name": "End Recording CUDAMemory History"}, + "VisualizeCUDAMemoryHistory": {"class": VisualizeCUDAMemoryHistory, "name": "Visualize CUDAMemory History"}, + "PreviewLatentNoiseMask": {"class": PreviewLatentNoiseMask, "name": "Preview Latent Noise Mask"}, + "ModelMemoryUseReportPatch": {"class": ModelMemoryUseReportPatch, "name": "Model Memory Use Report Patch"}, + "ModelMemoryUsageFactorOverride": {"class": ModelMemoryUsageFactorOverride, "name": "Model Memory Usage Factor Override"}, + "WanChunkFeedForward": {"class": WanChunkFeedForward, "name": "Wan ChunkFeedForward"}, + "Ideogram4OptimizationsKJ": {"class": Ideogram4OptimizationsKJ, "name": "Ideogram4 Optimizations KJ"}, + "SamplerSelfRefineVideo": {"class": SamplerSelfRefineVideo, "name": "Sampler SelfRefineVideo"}, + "PlaySoundKJ": {"class": PlaySoundKJ, "name": "Play Sound KJ"}, + + #instance diffusion + "CreateInstanceDiffusionTracking": {"class": CreateInstanceDiffusionTracking}, + "AppendInstanceDiffusionTracking": {"class": AppendInstanceDiffusionTracking}, + "DrawInstanceDiffusionTracking": {"class": DrawInstanceDiffusionTracking}, + + #lora + "LoraExtractKJ": {"class": LoraExtractKJ, "name": "LoraExtractKJ"}, + "LoraReduceRankKJ": {"class": LoraReduceRank, "name": "LoraReduceRank"}, + #looping + **{n.GET_SCHEMA().node_id: {"class": n, "name": n.GET_SCHEMA().display_name} for n in LOOP_NODES}, + + #tracks + "GetTrackRange": {"class": GetTrackRange, "name": "Get Track Range"}, + "AddNoiseToTrackPath": {"class": AddNoiseToTrackPath, "name": "Add Noise To Track"}, + + #context windows + "ContextWindowsVisualizerKJ": {"class": ContextWindowsVisualizerKJ, "name": "Context Windows Visualizer (KJ)"}, + # deprecated + "PatchModelPatcherOrder": {"class": PatchModelPatcherOrder, "name": "Patch Model Patcher Order"}, + "TorchCompileModelFluxAdvanced": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelFluxAdvanced"}, + "TorchCompileLTXModel": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileLTXModel"}, + "TorchCompileCosmosModel": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileCosmosModel"}, + "TorchCompileModelHyVideo": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelHyVideo"}, + "TorchCompileModelQwenImage": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelQwenImage"}, + "TorchCompileModelWanVideo": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelWanVideo"}, +} + +#ltxv +try: + from .nodes.ltxv_nodes import ( + LTXVAddGuideMulti, LTXVAddGuidesFromBatch, LTXVAudioVideoMask, LTX2_NAG, + LTXVChunkFeedForward, LTX2SamplingPreviewOverride, + LTX2AudioLatentNormalizingSampling, LTXVImgToVideoInplaceKJ, + LTX2AttentionTunerPatch, LTX2MemoryEfficientSageAttentionPatch, + LTX2LoraLoaderAdvanced, WanVideoMemoryEfficientSageAttentionPatch, + MiniMaxH3MemoryEfficientSageAttentionPatch, + ) + NODE_CONFIG.update({ + "LTXVEnhanceAVideoKJ": {"class": LTXVEnhanceAVideoKJ, "name": "LTXV Enhance A Video KJ"}, + "LTXVAddGuideMulti": {"class": LTXVAddGuideMulti, "name": "LTXV Add Guide Multi"}, + "LTXVAddGuidesFromBatch": {"class": LTXVAddGuidesFromBatch, "name": "LTXV Add Guides From Batch"}, + "LTXVAudioVideoMask": {"class": LTXVAudioVideoMask, "name": "LTXV Audio Video Mask"}, + "LTX2_NAG": {"class": LTX2_NAG, "name": "LTX2 NAG"}, + "LTXVChunkFeedForward": {"class": LTXVChunkFeedForward, "name": "LTXV Chunk Feed Forward"}, + "LTX2SamplingPreviewOverride": {"class": LTX2SamplingPreviewOverride, "name": "LTX2 Sampling Preview Override"}, + "LTX2AudioLatentNormalizingSampling": {"class": LTX2AudioLatentNormalizingSampling, "name": "LTX2 Audio Latent Normalizing Sampling"}, + "LTXVImgToVideoInplaceKJ": {"class": LTXVImgToVideoInplaceKJ, "name": "LTXV Img To Video Inplace KJ"}, + "LTX2AttentionTunerPatch": {"class": LTX2AttentionTunerPatch, "name": "LTX2 Attention Tuner Patch"}, + "LTX2MemoryEfficientSageAttentionPatch": {"class": LTX2MemoryEfficientSageAttentionPatch, "name": "LTX2 Memory Efficient Sage Attention Patch"}, + "LTX2LoraLoaderAdvanced": {"class": LTX2LoraLoaderAdvanced, "name": "LTX2 Lora Loader Advanced"}, + "WanVideoMemoryEfficientSageAttentionPatch": {"class": WanVideoMemoryEfficientSageAttentionPatch, "name": "WanVideo Memory Efficient Sage Attention Patch"}, + "MiniMaxH3MemoryEfficientSageAttentionPatch": {"class": MiniMaxH3MemoryEfficientSageAttentionPatch, "name": "MiniMax H3 Memory Efficient Sage Attention Patch"}, + }) +except Exception as e: + logging.warning(f"KJNodes: LTXV nodes could not be imported. LTXV nodes will be unavailable. Error: {e}", exc_info=True) + +#minimax +try: + from .nodes.minimax_nodes import MiniMaxChunkFeedForward, MiniMaxLowVRAMAttention, MiniMaxH3TokenCounter + NODE_CONFIG.update({ + "MiniMaxChunkFeedForward": {"class": MiniMaxChunkFeedForward, "name": "MiniMax H3 ChunkFeedForward"}, + "MiniMaxLowVRAMAttention": {"class": MiniMaxLowVRAMAttention, "name": "MiniMax H3 Low VRAM Attention"}, + "MiniMaxH3TokenCounter": {"class": MiniMaxH3TokenCounter, "name": "MiniMax H3 Token Counter"}, + }) +except Exception as e: + logging.warning(f"KJNodes: MiniMax nodes could not be imported. MiniMax nodes will be unavailable. Error: {e}", exc_info=True) + +try: + from .nodes.triton_vae import PatchTritonVAE + NODE_CONFIG.update({ + "PatchTritonVAE": {"class": PatchTritonVAE, "name": "Patch Triton VAE"}, + }) +except Exception: + logging.warning("KJNodes: PatchTritonVAE node could not be imported. PatchTritonVAE will be unavailable.", exc_info=True) + +def generate_node_mappings(node_config): + node_class_mappings = {} + node_display_name_mappings = {} + + for node_name, node_info in node_config.items(): + node_class_mappings[node_name] = node_info["class"] + node_display_name_mappings[node_name] = node_info.get("name", node_info["class"].__name__) + + return node_class_mappings, node_display_name_mappings + +NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS = generate_node_mappings(NODE_CONFIG) + +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"] + +WEB_DIRECTORY = "./web" + +from aiohttp import web +from server import PromptServer +from pathlib import Path + +if hasattr(PromptServer, "instance"): + # NOTE: we add an extra static path to avoid comfy mechanism that loads every script in web. + if not PromptServer.instance.app.router.frozen: + try: + PromptServer.instance.app.add_routes( + [web.static("/kjweb_async", (Path(__file__).parent.absolute() / "kjweb_async").as_posix())] + ) + except Exception: + logging.exception("KJNodes: failed to register /kjweb_async static route") + + import asyncio + import os + import folder_paths + + @PromptServer.instance.routes.post("/kjnodes/model_mtimes") + async def kjnodes_model_mtimes(request): + # modified times for a combo's model files (Nodes 2.0 folder view date sort); only names already in a model folder listing + try: + values = (await request.json()).get("values") + except Exception: + values = None + if not isinstance(values, list): + return web.json_response({"error": "values must be a list"}, status=400) + wanted = {v for v in values[:50000] if isinstance(v, str)} + + def stat(): + # the combo list came from object_info, so its folder is already in the filename cache; pick the best match + folder, names = max(((name, wanted.intersection(entry[0])) for name, entry in list(folder_paths.filename_list_cache.items())), + key=lambda x: len(x[1]), default=(None, set())) + out = {} + for name in names: + try: + out[name] = os.path.getmtime(folder_paths.get_full_path(folder, name)) + except (OSError, TypeError): + pass + return out + + return web.json_response(await asyncio.to_thread(stat)) diff --git a/docs/hel-892/setget-reference/contract.json b/docs/hel-892/setget-reference/contract.json new file mode 100644 index 00000000..4374e179 --- /dev/null +++ b/docs/hel-892/setget-reference/contract.json @@ -0,0 +1,43 @@ +{ + "authority": "public_reference_only", + "verified_facts": { + "provider": "kijai/ComfyUI-KJNodes", + "commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18", + "registration": "WEB_DIRECTORY -> web/js/setgetnodes.js app.registerExtension/registerCustomNodes -> LiteGraph.registerNodeType", + "virtual": "both constructors set isVirtualNode=true; graphToPrompt omits virtual nodes", + "current_name": "single Constant widget; widgets_values[0] restored unchanged by LGraphNode.configure", + "lookup": "Get.getInputLink(slot) finds first SetNode with strict widgets[0].value === name in graph._nodes, then returns setter.inputs[slot] link", + "set_direct": "inherits LGraphNode.getInputLink(slot); same slot input link", + "frontend_chain": "app.graphToPrompt -> executionUtil.graphToPrompt -> ExecutableNodeDTO.resolveInput/resolveOutput -> virtual getInputLink -> setter input DTO resolveInput -> ultimate entity output", + "callbacks": "app wraps graph.configure with configuringGraphLevel; KJ onConnectionsChange and widget callbacks skip during configuringGraph; onConfigure paste rename requires !configuringGraph", + "previous_name": "Set.update may rename getters through previousName during editing callbacks; it is NOT Get.getInputLink lookup key; titles/labels are not lookup keys", + "scope": "upstream has ancestor/descendant traversal and cross-graph patch; exact current root lookup is separately visible in getInputLink; no scope isolation inferred from execution IDs", + "duplicates": "upstream same-root find returns first; reference rejects all duplicates", + "mode": "upstream can alter bypass Get mode while resolving prompt; reference rejects all nonzero modes without emulation", + "license": "KJ GPL-3.0, frontend GPL-3.0; full license texts and file notices preserved" + }, + "explicit_reference_assumptions": { + "missing_version": "only for exact KJ aux_id, select the pinned commit; not target proof", + "missing_provider": "rejected, including literal SetNode/GetNode aux_id", + "missing_frontend": "explicit 1.37.11 only; 1.48.6 requires exact declaration", + "composition": "unmodified pinned root-only KJ plus previously pinned VHS and core widget construction/serialization, before queue hooks; no UE or other override", + "supported_types": "saved concrete equal socket/link types only; no wildcard/union coercion or inference", + "names": "exact saved string; no trim/casefold/Unicode normalization; nonempty whitespace string is valid if exactly matched" + }, + "target_unknown": [ + "actual provider/version", + "UE behavior and extension overrides", + "models/files/history", + "queue-time hooks", + "execution equivalence" + ], + "not_supported": [ + "nested/cross-boundary SetGet", + "mute/bypass/loops", + "dynamic type inference", + "arbitrary KJ classes", + "98 other frontend cohort", + "production registration or eligibility" + ], + "rules": "sources.json rule_locations; exact line hits against full original byte SHA256" +} diff --git a/docs/hel-892/setget-reference/pyproject.toml b/docs/hel-892/setget-reference/pyproject.toml new file mode 100644 index 00000000..3b39a138 --- /dev/null +++ b/docs/hel-892/setget-reference/pyproject.toml @@ -0,0 +1,15 @@ +[project] +name = "comfyui-kjnodes" +description = "Various quality of life -nodes for ComfyUI, mostly just visual stuff to improve usability." +version = "1.5.3" +license = {file = "LICENSE"} +dependencies = ["pillow>=10.3.0", "color-matcher", "matplotlib"] + +[project.urls] +Repository = "https://github.com/kijai/ComfyUI-KJNodes" +# Used by Comfy Registry https://comfyregistry.org + +[tool.comfy] +PublisherId = "kijai" +DisplayName = "ComfyUI-KJNodes" +Icon = "https://avatars.githubusercontent.com/u/40791699" diff --git a/docs/hel-892/setget-reference/sources.json b/docs/hel-892/setget-reference/sources.json new file mode 100644 index 00000000..854a1e69 --- /dev/null +++ b/docs/hel-892/setget-reference/sources.json @@ -0,0 +1,500 @@ +{ + "sources": [ + { + "id": "kijai/ComfyUI-KJNodes@ab72eda7ffad6280422d71ab7d54d3fb87c0ba18:web/js/setgetnodes.js", + "commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18", + "raw_url": "https://raw.githubusercontent.com/kijai/ComfyUI-KJNodes/ab72eda7ffad6280422d71ab7d54d3fb87c0ba18/web/js/setgetnodes.js", + "local_file": "web__js__setgetnodes.js", + "sha256": "6d0b72bfb40f1fbfd60a7e06e6aafd4c6b0a49de35d39567d62383dd842b3274", + "retrieved_at": "2026-10-29T20:48:37.644443+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 1735 + ] + ], + "rule_locations": { + "function getGraphAncestors(graph)#101": [ + 101, + 101 + ], + "function findSetterByName(graph, name)#190": [ + 190, + 190 + ], + "function getLink(graph, linkId)#394": [ + 394, + 394 + ], + "class SetNode extends LGraphNode#571": [ + 571, + 571 + ], + "class GetNode extends LGraphNode#914": [ + 914, + 914 + ], + "this.isVirtualNode = true;#588": [ + 588, + 588 + ], + "this.isVirtualNode = true;#929": [ + 929, + 929 + ], + "this.properties[\"aux_id\"] = \"kijai/ComfyUI-KJNodes\"#587": [ + 587, + 587 + ], + "this.properties[\"aux_id\"] = \"kijai/ComfyUI-KJNodes\"#928": [ + 928, + 928 + ], + "this.addWidget(#590": [ + 590, + 590 + ], + "this.addWidget(#956": [ + 956, + 956 + ], + "this.addInput(#606": [ + 606, + 606 + ], + "this.addOutput(#607": [ + 607, + 607 + ], + "this.addOutput(#1008": [ + 1008, + 1008 + ], + "if (app.configuringGraph) return;#617": [ + 617, + 617 + ], + "if (app.configuringGraph) return;#1022": [ + 1022, + 1022 + ], + "onConfigure()#770": [ + 770, + 770 + ], + "onConfigure()#1105": [ + 1105, + 1105 + ], + "this.properties.previousName = this.widgets[0].value;#601": [ + 601, + 601 + ], + "this.properties.previousName = this.widgets[0].value;#677": [ + 677, + 677 + ], + "const name = checkForPreviousName#813": [ + 813, + 813 + ], + "getInputLink(slot)#1121": [ + 1121, + 1121 + ], + "n => n.type === 'SetNode' && n.widgets[0].value === name#1127": [ + 1127, + 1127 + ], + "LiteGraph.registerNodeType(\"SetNode\", SetNode)#906": [ + 906, + 906 + ], + "LiteGraph.registerNodeType(\"GetNode\", GetNode)#1228": [ + 1228, + 1228 + ], + "app.graphToPrompt = async function#1589": [ + 1589, + 1589 + ] + } + }, + { + "id": "kijai/ComfyUI-KJNodes@ab72eda7ffad6280422d71ab7d54d3fb87c0ba18:web/js/utility.js", + "commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18", + "raw_url": "https://raw.githubusercontent.com/kijai/ComfyUI-KJNodes/ab72eda7ffad6280422d71ab7d54d3fb87c0ba18/web/js/utility.js", + "local_file": "web__js__utility.js", + "sha256": "edb48d89ed89c9aea0cde2ace1d70034383561cd02124d42e17c3eaa2fcc7177", + "retrieved_at": "2026-10-29T20:48:38.034567+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 291 + ] + ], + "rule_locations": {} + }, + { + "id": "kijai/ComfyUI-KJNodes@ab72eda7ffad6280422d71ab7d54d3fb87c0ba18:__init__.py", + "commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18", + "raw_url": "https://raw.githubusercontent.com/kijai/ComfyUI-KJNodes/ab72eda7ffad6280422d71ab7d54d3fb87c0ba18/__init__.py", + "local_file": "__init__.py", + "sha256": "72469fb7da7bbf9e23d327fdc7870ed4c6ee7d8a39e29e212c70bb9b8873f641", + "retrieved_at": "2026-10-29T20:48:38.252708+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 458 + ] + ], + "rule_locations": { + "WEB_DIRECTORY = \"./web\"#415": [ + 415, + 415 + ] + } + }, + { + "id": "kijai/ComfyUI-KJNodes@ab72eda7ffad6280422d71ab7d54d3fb87c0ba18:pyproject.toml", + "commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18", + "raw_url": "https://raw.githubusercontent.com/kijai/ComfyUI-KJNodes/ab72eda7ffad6280422d71ab7d54d3fb87c0ba18/pyproject.toml", + "local_file": "pyproject.toml", + "sha256": "3c84ba5c3d134af053b3d832a67e616d25fcbc4e97b9d906ca608986aabd5b58", + "retrieved_at": "2026-10-29T20:48:38.627867+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 15 + ] + ], + "rule_locations": {} + }, + { + "id": "kijai/ComfyUI-KJNodes@ab72eda7ffad6280422d71ab7d54d3fb87c0ba18:LICENSE", + "commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18", + "raw_url": "https://raw.githubusercontent.com/kijai/ComfyUI-KJNodes/ab72eda7ffad6280422d71ab7d54d3fb87c0ba18/LICENSE", + "local_file": "LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "retrieved_at": "2026-10-29T20:48:38.849665+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 674 + ] + ], + "rule_locations": {} + }, + { + "id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/config/comfyApi.ts", + "commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/config/comfyApi.ts", + "local_file": "1.37.11__src__config__comfyApi.ts", + "sha256": "231459674610af5d15df37f79bbc27f29cfcefa938c338e54a42d59b130f69dc", + "retrieved_at": "2026-10-29T20:48:39.267718+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 43 + ] + ], + "rule_locations": {} + }, + { + "id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:build/plugins/comfyAPIPlugin.ts", + "commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/build/plugins/comfyAPIPlugin.ts", + "local_file": "1.37.11__build__plugins__comfyAPIPlugin.ts", + "sha256": "3b57d35aa3cff3d4099c8e30e888e017f87803f3d5d64231346191073f7c204a", + "retrieved_at": "2026-10-29T20:48:39.659975+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 118 + ] + ], + "rule_locations": { + "window.comfyAPI.${moduleName}.${name}#57": [ + 57, + 57 + ], + "window.comfyAPI.${moduleName}.${name}#59": [ + 59, + 59 + ] + } + }, + { + "id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/scripts/app.ts", + "commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/scripts/app.ts", + "local_file": "1.37.11__src__scripts__app.ts", + "sha256": "e57985f7d365abb035bc2fc755a8f5b10efbca97a7dcb5b2a4a05bcbc78b9d5c", + "retrieved_at": "2026-10-29T20:48:40.175830+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 1744 + ] + ], + "rule_locations": { + "app.configuringGraphLevel++#721": [ + 721, + 721 + ] + } + }, + { + "id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/lib/litegraph/src/LGraphNode.ts", + "commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/lib/litegraph/src/LGraphNode.ts", + "local_file": "1.37.11__src__lib__litegraph__src__LGraphNode.ts", + "sha256": "706225a8a06cd7929f9e04fe2388bcdb8f158cdac756c65c45657c020ab7b319", + "retrieved_at": "2026-10-29T20:48:40.702689+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 4198 + ] + ], + "rule_locations": { + "widget.value = info.widgets_values[i++]#872": [ + 872, + 872 + ], + "this.onConfigure?.(info)#880": [ + 880, + 880 + ], + "getInputLink(slot: number)#1159": [ + 1159, + 1159 + ] + } + }, + { + "id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts", + "commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts", + "local_file": "1.37.11__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts", + "sha256": "fd2e19a6b8f4369e6e97d79f407cc1bec130feec9d6d3c979cc03b0a556f249f", + "retrieved_at": "2026-10-29T20:48:41.102250+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 408 + ] + ], + "rule_locations": { + "const virtualLink = this.node.getInputLink(slot)#291": [ + 291, + 291 + ], + "return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)#307": [ + 307, + 307 + ] + } + }, + { + "id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/utils/executionUtil.ts", + "commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/utils/executionUtil.ts", + "local_file": "1.37.11__src__utils__executionUtil.ts", + "sha256": "4e51bc54e35cb7ac9bb7cba418a74ccdd5974f640b9b088aa4ae7668f746ab36", + "retrieved_at": "2026-10-29T20:48:41.524838+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 150 + ] + ], + "rule_locations": { + "node.isVirtualNode ||#78": [ + 78, + 78 + ] + } + }, + { + "id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:LICENSE", + "commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/LICENSE", + "local_file": "1.37.11__LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "retrieved_at": "2026-10-29T20:48:41.966937+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 674 + ] + ], + "rule_locations": {} + }, + { + "id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:src/config/comfyApi.ts", + "commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/src/config/comfyApi.ts", + "local_file": "1.48.6__src__config__comfyApi.ts", + "sha256": "439d45da4c437ec06ddf27a3d301905f678113bf0341b674a235417d1e60ab9c", + "retrieved_at": "2026-10-29T20:48:42.376174+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 35 + ] + ], + "rule_locations": {} + }, + { + "id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:build/plugins/comfyAPIPlugin.ts", + "commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/build/plugins/comfyAPIPlugin.ts", + "local_file": "1.48.6__build__plugins__comfyAPIPlugin.ts", + "sha256": "2bb4aaf83f40b6ac06604188fbc34c26e8616c3e0be223eb09f0ae68a96d60c6", + "retrieved_at": "2026-10-29T20:48:42.779241+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 123 + ] + ], + "rule_locations": { + "window.comfyAPI.${moduleName}.${name}#61": [ + 61, + 61 + ], + "window.comfyAPI.${moduleName}.${name}#63": [ + 63, + 63 + ] + } + }, + { + "id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:src/scripts/app.ts", + "commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/src/scripts/app.ts", + "local_file": "1.48.6__src__scripts__app.ts", + "sha256": "e274c5f4420e8aefdacf1a716296ee7ae4c9079e77578272d3eeef05350e4c71", + "retrieved_at": "2026-10-29T20:48:43.166322+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 2260 + ] + ], + "rule_locations": { + "app.configuringGraphLevel++#855": [ + 855, + 855 + ] + } + }, + { + "id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:src/lib/litegraph/src/LGraphNode.ts", + "commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/src/lib/litegraph/src/LGraphNode.ts", + "local_file": "1.48.6__src__lib__litegraph__src__LGraphNode.ts", + "sha256": "7d312ebe5182c4c69d45b5d5e4434dfd42405f72455310886acded76ce1d60ed", + "retrieved_at": "2026-10-29T20:48:43.577670+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 4360 + ] + ], + "rule_locations": { + "widget.value = info.widgets_values[i++]#991": [ + 991, + 991 + ], + "this.onConfigure?.(info)#1007": [ + 1007, + 1007 + ], + "getInputLink(slot: number)#1296": [ + 1296, + 1296 + ] + } + }, + { + "id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts", + "commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts", + "local_file": "1.48.6__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts", + "sha256": "64baa71b46bd67440b032e18e4d9aebb67a6cc135fe7c4509ae1b5bc25acc2a3", + "retrieved_at": "2026-10-29T20:48:44.175734+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 429 + ] + ], + "rule_locations": { + "const virtualLink = this.node.getInputLink(slot)#312": [ + 312, + 312 + ], + "return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)#328": [ + 328, + 328 + ] + } + }, + { + "id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:src/utils/executionUtil.ts", + "commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/src/utils/executionUtil.ts", + "local_file": "1.48.6__src__utils__executionUtil.ts", + "sha256": "264e11395f28880603e7f9fe36d2e61c74cd59d6d88be990225cce8510e3f816", + "retrieved_at": "2026-10-29T20:48:44.542997+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 160 + ] + ], + "rule_locations": { + "node.isVirtualNode ||#86": [ + 86, + 86 + ] + } + }, + { + "id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:LICENSE", + "commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d", + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/LICENSE", + "local_file": "1.48.6__LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "retrieved_at": "2026-10-29T20:48:44.932058+00:00", + "license": "GPL-3.0", + "lines": [ + [ + 1, + 674 + ] + ], + "rule_locations": {} + } + ] +} diff --git a/docs/hel-892/setget-reference/web__js__setgetnodes.js b/docs/hel-892/setget-reference/web__js__setgetnodes.js new file mode 100644 index 00000000..cc1fa250 --- /dev/null +++ b/docs/hel-892/setget-reference/web__js__setgetnodes.js @@ -0,0 +1,1735 @@ +const { app } = window.comfyAPI.app; +import { connectById } from "./utility.js"; + +// originally based on diffus3's SetGet: https://github.com/diffus3/ComfyUI-extensions + +// Nodes that allow you to hide connections for cleaner graphs + +let _typeColorMap; +function setColorAndBgColor(node, type) { + if (!_typeColorMap) { + _typeColorMap = { + "DEFAULT": LGraphCanvas.node_colors.gray, + "MODEL": LGraphCanvas.node_colors.blue, + "LATENT": LGraphCanvas.node_colors.purple, + "VAE": LGraphCanvas.node_colors.red, + "WANVAE": LGraphCanvas.node_colors.red, + "CONDITIONING": LGraphCanvas.node_colors.brown, + "IMAGE": LGraphCanvas.node_colors.pale_blue, + "CLIP": LGraphCanvas.node_colors.yellow, + "FLOAT": LGraphCanvas.node_colors.green, + "MASK": { color: "#1c5715", bgcolor: "#1f401b"}, + "INT": { color: "#1b4669", bgcolor: "#29699c"}, + "CONTROL_NET": { color: "#156653", bgcolor: "#1c453b"}, + "NOISE": { color: "#2e2e2e", bgcolor: "#242121"}, + "GUIDER": { color: "#3c7878", bgcolor: "#1c453b"}, + "SAMPLER": { color: "#614a4a", bgcolor: "#3b2c2c"}, + "SIGMAS": { color: "#485248", bgcolor: "#272e27"}, + }; + } + const colors = _typeColorMap[type] || LGraphCanvas.node_colors?.gray; + if (colors) { + node.color = colors.color; + node.bgcolor = colors.bgcolor; + } +} +// LGraphEventMode values +const MODE_ALWAYS = 0; +const MODE_BYPASS = 4; +// graphToPrompt calls in progress; GetNode ignores bypass while > 0 +let _resolvingPrompt = 0; + +function getDisablePrefix() { + return app.ui.settings.getSettingValue("KJNodes.disablePrefix") ?? false; +} +function prefixedTitle(prefix, name) { + return (getDisablePrefix() ? "" : prefix + "_") + name; +} +function autoColor(node, type) { + if (!app.ui.settings.getSettingValue("KJNodes.nodeAutoColor")) return; + if (type === '*') { node.color = null; node.bgcolor = null; } + else setColorAndBgColor(node, type); +} +function addNodeToSelectedOrCursor(nodeType, side) { + const selected = Object.values(app.canvas.selected_nodes || {}); + if (selected.length > 0) { + for (const n of selected) window.kjNodes.addNode(nodeType, n, { side, offset: 30 }); + } else { + const canvas = app.canvas, graph = canvas.graph || app.graph; + const node = LiteGraph.createNode(nodeType); + if (!node) return; + node.pos = [canvas.graph_mouse[0], canvas.graph_mouse[1]]; + graph.add(node); + canvas.selectNode(node, false); + canvas.setDirty(true, true); + } +} +// Temporary map for paste rename coordination between Set and Get nodes. +// Key: old name, Value: new name. Cleared via setTimeout(0) after each paste cycle. +// This works because both onConfigure calls (Set + Get) fire synchronously within +// the same paste operation, before the timeout clears the entry. +const _pasteRenameMap = new Map(); + +let _forceShowAllLinks = false; + +function getShowLinksMode() { + if (_forceShowAllLinks) return "always"; + return app.ui.settings.getSettingValue("KJNodes.showSetGetLinks") ?? "never"; +} +const LGraphNode = LiteGraph.LGraphNode + +// Cross-graph traversal utilities with lexical scoping for subgraph support. +// Set nodes propagate downward: a Set in a parent graph is visible to all descendant subgraphs. +// Get nodes look upward: a Get searches its own graph first, then parent, then grandparent, etc. +// Duplicate names are allowed across unrelated (sibling) subgraphs. + +function findRootGraph(graph) { + if (!graph) return null; + return graph.rootGraph || graph; +} + +// Find which SubgraphNode in parentGraph wraps the given subgraph +function findSubgraphNodeFor(parentGraph, innerNode) { + if (!parentGraph?._nodes || !innerNode?.graph) return null; + for (const n of parentGraph._nodes) { + if (n.subgraph && n.subgraph === innerNode.graph) return n; + } + return null; +} + +// Walk from a subgraph up to root, returning [graph, parent, grandparent, ..., root] +function getGraphAncestors(graph) { + if (!graph) return []; + const root = findRootGraph(graph); + if (!root || graph === root) return [root]; + + const chain = [graph]; + const visited = new Set([graph]); + let current = graph; + // Walk up: find which SubgraphNode wraps current, then get its parent graph + while (current !== root) { + let found = false; + // Search root nodes + for (const n of root._nodes) { + if (n.subgraph === current) { + chain.push(root); + current = root; + found = true; + break; + } + } + if (found) break; + // Search sibling subgraphs (for nested subgraphs) + const subgraphs = root._subgraphs || root.subgraphs; + if (subgraphs) { + for (const sg of subgraphs.values()) { + if (sg === current || !sg._nodes) continue; + for (const n of sg._nodes) { + if (n.subgraph === current) { + if (visited.has(sg)) { found = false; break; } + visited.add(sg); + chain.push(sg); + current = sg; + found = true; + break; + } + } + if (found) break; + } + } + if (!found) { + // Can't find parent, add root as fallback + if (!chain.includes(root)) chain.push(root); + break; + } + } + return chain; +} + +// Get all descendant subgraphs of a graph (children, grandchildren, etc.) +function getGraphDescendants(graph, _visited) { + if (!graph?._nodes) return []; + const visited = _visited || new Set(); + if (visited.has(graph)) return []; + visited.add(graph); + const descendants = []; + for (const n of graph._nodes) { + if (n.subgraph && !visited.has(n.subgraph)) { + descendants.push(n.subgraph); + descendants.push(...getGraphDescendants(n.subgraph, visited)); + } + } + return descendants; +} + +// Collect nodes of a type from specific graphs +function collectNodesOfType(graphs, type) { + const results = []; + for (const g of graphs) { + if (!g?._nodes) continue; + for (const node of g._nodes) { + if (node.type === type) results.push({ node, graph: g }); + } + } + return results; +} + +// Find all nodes of type across ALL graphs (root + all subgraphs). Used for global operations. +function findAllNodesOfType(graph, type) { + const root = findRootGraph(graph); + if (!root) return []; + const allGraphs = [root]; + const subgraphs = root._subgraphs || root.subgraphs; + if (subgraphs) { + for (const sg of subgraphs.values()) allGraphs.push(sg); + } + return collectNodesOfType(allGraphs, type); +} + +// Scoped setter lookup: search current graph, then ancestors (look up). +function findSetterByName(graph, name) { + if (!name) return null; + for (const g of getGraphAncestors(graph)) { + if (!g?._nodes) continue; + for (const node of g._nodes) { + if (node.type === 'SetNode' && node.widgets[0].value === name) { + return { node, graph: g }; + } + } + } + return null; +} + +// Scoped getter lookup: search current graph + descendants (propagate down). +function findGettersByName(graph, name) { + if (!name) return []; + const graphs = [graph, ...getGraphDescendants(graph)]; + return collectNodesOfType(graphs, 'GetNode') + .filter(entry => entry.node.widgets[0].value === name); +} + +// Get all visible SetNode names for a GetNode's combo dropdown. +// Shows names from current graph + ancestors (what's in scope). +// Also builds a source map for getOptionLabel. This module-level variable is safe +// because the values getter and getOptionLabel run in the same synchronous render pass. +let _setNameSourceMap = new Map(); + +function getVisibleSetNames(graph, filterType) { + const sourceMap = new Map(); + const ancestors = getGraphAncestors(graph); + const entries = collectNodesOfType(ancestors, 'SetNode'); + for (const e of entries) { + const name = e.node.widgets[0].value; + if (!name) continue; + if (filterType && filterType !== '*') { + const setType = e.node.inputs[0]?.type; + if (setType && setType !== '*') { + const filterTypes = String(filterType).split(","); + if (!filterTypes.some(ft => ft === setType || setType.split(",").includes(ft))) continue; + } + } + if (!sourceMap.has(name)) { + sourceMap.set(name, e.graph === graph ? "local" : "parent"); + } + } + _setNameSourceMap = sourceMap; + return [...sourceMap.keys()].sort(); +} + +// Force every GetNode (root + subgraphs) to swap its widget.options reference so Vue re-reads values. +function refreshAllGetNodeCombos(graph) { + const root = findRootGraph(graph); + if (!root) return; + const allGraphs = [root]; + const subgraphs = root._subgraphs || root.subgraphs; + if (subgraphs) { + for (const sg of subgraphs.values()) allGraphs.push(sg); + } + for (const g of allGraphs) { + if (!g?._nodes) continue; + for (const node of g._nodes) { + if (node.type === 'GetNode') node._refreshComboOptions?.(); + } + } +} + +// Exposed globally for use in contextmenu.js +window.kjNodes = window.kjNodes || {}; +window.kjNodes.convertOutputsToSetGet = convertOutputsToSetGet; +window.kjNodes.snapshotSelectedNodes = snapshotSelectedNodes; +function convertOutputsToSetGet(graph, node) { + if (!graph || !node) return; + for (let slotIdx = 0; slotIdx < node.outputs.length; slotIdx++) { + const output = node.outputs[slotIdx]; + if (!output.links || output.links.length === 0) continue; + + const linkType = output.type || "*"; + const linkName = output.name || linkType; + + // Collect targets and link IDs to remove, skipping existing Set/Get nodes + const targets = []; + const linksToRemove = []; + for (const linkId of [...output.links]) { + const link = getLink(graph, linkId); + if (link) { + const targetNode = graph.getNodeById(link.target_id); + if (targetNode && targetNode.type !== 'SetNode' && targetNode.type !== 'GetNode') { + targets.push({ targetId: link.target_id, targetSlot: link.target_slot }); + linksToRemove.push(linkId); + } + } + } + if (targets.length === 0) continue; + + // Create Set node + const setNode = LiteGraph.createNode("SetNode"); + if (!setNode) continue; + setNode.pos = [ + node.pos[0] + node.size[0] + 30, + node.pos[1] + slotIdx * 60 + ]; + graph.add(setNode); + setNode.flags.collapsed = true; + + for (const linkId of linksToRemove) graph.removeLink(linkId); + + // Connect source → Set node input + node.connect(slotIdx, setNode, 0); + + // Set the name widget + setNode.widgets[0].value = linkName; + setNode.title = prefixedTitle("Set", linkName); + setNode.validateName(graph); + const finalName = setNode.widgets[0].value; + setNode.properties.previousName = finalName; + + // Create a Get node for each target + for (const target of targets) { + const targetNode = graph.getNodeById(target.targetId); + if (!targetNode) continue; + + const getNode = LiteGraph.createNode("GetNode"); + if (!getNode) continue; + getNode.pos = [ + targetNode.pos[0] - getNode.size[0] - 30, + targetNode.pos[1] + ]; + graph.add(getNode); + getNode.flags.collapsed = true; + + getNode.widgets[0].value = finalName; + getNode.onRename(); + + getNode.connect(0, targetNode, target.targetSlot); + } + } + app.canvas.setDirty(true, true); +} + +// Snapshot selection immediately (before right-click changes it) +function snapshotSelectedNodes(node, typeFilter) { + const selected = Object.values(app.canvas.selected_nodes || {}); + // Always include the right-clicked node, even if selection state is inconsistent + const nodeSet = new Set(selected); + nodeSet.add(node); + let nodes = [...nodeSet]; + if (typeFilter) nodes = nodes.filter(n => n.type === typeFilter); + return nodes; +} + +// Tracks nodes flagged with has_errors so they can be cleared on the next alert. +// Always cleared before repopulating, so it only holds nodes from the most recent alert. +const _errorNodes = new Set(); +function showAlert(message, nodes) { + const nodeList = nodes ? (Array.isArray(nodes) ? nodes : [nodes]) : []; + const nodeInfo = nodeList.map(n => + `${n.title || n.type} [${Math.round(n.pos[0])}, ${Math.round(n.pos[1])}]` + ).join(', '); + if (nodeList.length) { + // Clear previous error flags + for (const n of _errorNodes) n.has_errors = false; + _errorNodes.clear(); + setTimeout(() => { + for (const n of nodeList) { + n.has_errors = true; + _errorNodes.add(n); + } + app.canvas?.setDirty(true, true); + }, 100); + } + app.extensionManager.toast.add({ + severity: 'warn', + summary: "KJ Set/Get", + detail: nodeInfo ? `${message} — ${nodeInfo}` : message, + life: 5000, + }); +} +function convertAllSetGetToLinks(graph) { + if (!graph) return; + const rootGraph = findRootGraph(graph); + + // First pass: handle cross-graph pairs (must run before same-graph + // because converting cross-graph creates real links that replace + // the Set/Get, and same-graph pass would miss the removed nodes) + const allSetEntries = findAllNodesOfType(rootGraph, 'SetNode'); + for (const { node: setNode, graph: setGraph } of [...allSetEntries]) { + const name = setNode.widgets[0].value; + if (!name) continue; + const allGetEntries = findGettersByName(rootGraph, name); + const crossGraphGetters = allGetEntries.filter(e => e.graph !== setGraph); + if (crossGraphGetters.length > 0) { + convertCrossGraphSetGet(setNode, setGraph, crossGraphGetters); + } + } + + // Second pass: handle remaining same-graph pairs + for (const { node: setNode, graph: g } of [...findAllNodesOfType(rootGraph, 'SetNode')]) { + convertSetGetToLinks(g, setNode); + } +} + +// Compat shim: older frontends may lack graph.getLink(), and _links may be a Map or +// plain object depending on the litegraph version. The == null check catches both null +// and undefined intentionally. +function getLink(graph, linkId) { + if (linkId == null) return null; + if (graph.getLink) return graph.getLink(linkId); + return graph._links instanceof Map ? graph._links.get(linkId) : graph._links?.[linkId] ?? null; +} + +// Collect {targetId, targetSlot} from an output slot's links +function collectOutputConnections(graph, output) { + const connections = []; + if (output?.links) { + for (const linkId of [...output.links]) { + const link = getLink(graph, linkId); + if (link) connections.push({ targetId: link.target_id, targetSlot: link.target_slot }); + } + } + return connections; +} + +function convertCrossGraphSetGet(setNode, setGraph, crossGraphGetters) { + // Find what's connected to the SetNode's input + const setInput = setNode.inputs[0]; + if (setInput.link == null) return; + const sourceLink = getLink(setGraph, setInput.link); + if (!sourceLink) return; + const sourceNode = setGraph.getNodeById(sourceLink.origin_id); + if (!sourceNode) return; + const sourceSlot = sourceLink.origin_slot; + const linkType = setNode.inputs[0].type || '*'; + + for (const { node: getter, graph: getterGraph } of crossGraphGetters) { + // Collect getter's downstream connections before removing it + const connections = collectOutputConnections(getterGraph, getter.outputs[0]); + if (connections.length === 0) { + getterGraph.remove(getter); + continue; + } + + // Determine direction and create SubgraphInput or SubgraphOutput + const rootGraph = findRootGraph(setGraph); + const sgNodeForGetter = findSubgraphNodeFor(rootGraph, getter); + const sgNodeForSetter = findSubgraphNodeFor(rootGraph, setNode); + + if (sgNodeForGetter && setGraph === rootGraph) { + // Set in root, Get in subgraph → create SubgraphInput + const subgraph = sgNodeForGetter.subgraph; + const inputName = setNode.widgets[0].value || linkType; + const newInput = subgraph.addInput(inputName, linkType); + const inputIndex = subgraph.inputs.indexOf(newInput); + + // Connect source → SubgraphNode's new input in root graph + sourceNode.connect(sourceSlot, sgNodeForGetter, inputIndex); + + // Inside subgraph: connect SubgraphInput slot → getter's targets + for (const conn of connections) { + if (conn.targetId === subgraph.outputNode?.id) { + // GetNode fed a SubgraphOutput — bypass it and connect source directly in parent graph. + const sgNodeOutput = sgNodeForGetter.outputs[conn.targetSlot]; + if (sgNodeOutput?.links) { + for (const parentLinkId of [...sgNodeOutput.links]) { + const parentLink = getLink(rootGraph, parentLinkId); + if (parentLink) { + const parentTarget = rootGraph.getNodeById(parentLink.target_id); + if (parentTarget) { + sourceNode.connect(sourceSlot, parentTarget, parentLink.target_slot); + } + } + } + } + // Remove the now-unnecessary SubgraphOutput + const sgOutput = subgraph.outputs[conn.targetSlot]; + if (sgOutput) { + subgraph.removeOutput(sgOutput); + } + } else { + const targetNode = getterGraph.getNodeById(conn.targetId); + if (targetNode) { + newInput.connect(targetNode.inputs[conn.targetSlot], targetNode); + } + } + } + + // If no connections used the SubgraphInput, remove it + if (newInput.linkIds.length === 0) { + subgraph.removeInput(newInput); + } + + getterGraph.remove(getter); + + } else if (sgNodeForSetter && getterGraph === rootGraph) { + // Set in subgraph, Get in root → create SubgraphOutput + const subgraph = sgNodeForSetter.subgraph; + const outputName = setNode.widgets[0].value || linkType; + const newOutput = subgraph.addOutput(outputName, linkType); + const outputIndex = subgraph.outputs.indexOf(newOutput); + + // Inside subgraph: connect source output → SubgraphOutput slot + newOutput.connect(sourceNode.outputs[sourceSlot], sourceNode); + + // In root graph: connect SubgraphNode's new output → getter's targets + for (const conn of connections) { + const targetNode = getterGraph.getNodeById(conn.targetId); + if (targetNode) { + sgNodeForSetter.connect(outputIndex, targetNode, conn.targetSlot); + } + } + + getterGraph.remove(getter); + + } else { + // Both in different subgraphs (sibling) — would need both input and output + // Skip for now, too complex + console.warn(`KJNodes: Cannot convert cross-graph Set/Get "${setNode.widgets[0].value}" between sibling subgraphs`); + } + } + + // Remove SetNode if all its getters have been handled (check if any same-graph getters remain) + const remainingGetters = setGraph._nodes.filter( + n => n.type === 'GetNode' && n.widgets[0].value === setNode.widgets[0].value + ); + if (remainingGetters.length === 0) { + setGraph.remove(setNode); + } +} + +function convertSetGetToLinks(graph, setNode) { + if (!graph || !setNode) return; + + const name = setNode.widgets[0].value; + let sameGraphGetters = []; + if (name) { + const allGetters = findGettersByName(graph, name); + const crossGetters = []; + for (const entry of allGetters) { + if (entry.graph === graph) sameGraphGetters.push(entry.node); + else crossGetters.push(entry); + } + if (crossGetters.length > 0) { + convertCrossGraphSetGet(setNode, graph, crossGetters); + } + } + + // Find the source connected to the Set node's input + const setInput = setNode.inputs[0]; + if (setInput.link == null) return; + const sourceLink = getLink(graph, setInput.link); + if (!sourceLink) return; + const sourceId = sourceLink.origin_id; + // Source may be the subgraph input boundary, which isn't in graph._nodes + if (!graph.getNodeById(sourceId) && sourceId !== graph.inputNode?.id) return; + const sourceSlot = sourceLink.origin_slot; + + // Collect all consumer connections from Get nodes and SetNode's own output passthrough + const connections = []; + for (const getter of sameGraphGetters) { + connections.push(...collectOutputConnections(graph, getter.outputs[0])); + } + connections.push(...collectOutputConnections(graph, setNode.outputs[0])); + + // Remove all Get nodes (this also removes their links) + for (const getter of sameGraphGetters) { + graph.remove(getter); + } + // Remove the Set node + graph.remove(setNode); + + // Create direct links from source to each consumer + for (const conn of connections) { + connectById(graph, sourceId, sourceSlot, conn.targetId, conn.targetSlot); + } + + app.canvas?.setDirty(true, true); +} + +// region SetNode +app.registerExtension({ + name: "KJNodes.SetNode", + registerCustomNodes() { + class SetNode extends LGraphNode { + static title = "Set"; + static category = "KJNodes"; + serialize_widgets = true; + drawConnection = false; + slotColor = "#FFF"; + canvas = app.canvas; + + constructor(title) { + super(title) + if (!this.properties) { + this.properties = { + "previousName": "" + }; + } + this.properties["Node name for S&R"] = "SetNode"; + this.properties["aux_id"] = "kijai/ComfyUI-KJNodes"; + this.isVirtualNode = true; // This node is purely frontend and does not impact the resulting prompt so should not be serialized + + this.addWidget( + "text", + "Constant", + '', + () => { + if (!this.graph || app.configuringGraph) return; + this.validateName(this.graph); + if (this.widgets[0].value !== '') { + this.title = prefixedTitle("Set", this.widgets[0].value); + } + this.update(); + this.properties.previousName = this.widgets[0].value; + }, + {} + ) + + this.addInput("*", "*"); + this.addOutput("*", '*'); + } + + onConnectionsChange( + slotType, + slot, + isChangeConnect, + link_info + ) { + // During graph load, slots are restored by configure — skip side effects + if (app.configuringGraph) return; + //On Disconnect + if (slotType === LiteGraph.INPUT && !isChangeConnect) { + const outputConnected = this.outputs[0]?.links?.length > 0; + if (outputConnected) { + this.inputs[slot].type = this.outputs[0].type; + this.inputs[slot].name = this.outputs[0].name; + } else { + this.inputs[slot].type = '*'; + this.inputs[slot].name = '*'; + this.outputs[0].type = '*'; + this.outputs[0].name = '*'; + this.title = "Set"; + this.color = null; + this.bgcolor = null; + } + this.update(); + } + if (slotType === LiteGraph.OUTPUT && !isChangeConnect) { + if (this.outputs && this.outputs[slot]) { + // Keep type if input has a real connection + const inputConnected = this.inputs[0]?.link != null; + if (inputConnected) { + this.outputs[slot].type = this.inputs[0].type; + this.outputs[slot].name = this.inputs[0].name; + } else { + this.inputs[0].type = '*'; + this.inputs[0].name = '*'; + this.outputs[slot].type = '*'; + this.outputs[slot].name = '*'; + this.color = null; + this.bgcolor = null; + } + } + } + //On Connect + if (link_info && this.graph && slotType === LiteGraph.INPUT && isChangeConnect) { + const resolve = link_info.resolve(this.graph) + const resolvedSlot = resolve?.subgraphInput ?? resolve?.output; + const type = resolvedSlot?.type; + if (type) { + if (this.title === "Set"){ + this.title = prefixedTitle("Set", type); + } + if (this.widgets[0].value === '' || this.widgets[0].value === '*'){ + // Determine the initial widget value based on naming setting + const namingMode = app.ui.settings.getSettingValue("KJNodes.setGetNaming") ?? "empty"; + if (namingMode !== "empty") { + const link = getLink(this.graph, this.inputs[0]?.link); + const sourceNode = link ? this.graph.getNodeById(link.origin_id) : null; + const slotName = sourceNode?.outputs?.[link?.origin_slot]?.name || type; + switch (namingMode) { + case "slot name": this.widgets[0].value = slotName; break; + case "slot name (lowercase)": this.widgets[0].value = slotName.toLowerCase(); break; + case "slot name (UPPERCASE)": this.widgets[0].value = slotName.toUpperCase(); break; + } + } + } + + this.validateName(this.graph); + this.properties.previousName = this.widgets[0].value; + this.inputs[0].type = type; + this.inputs[0].name = type; + this.outputs[0].type = type; + this.outputs[0].name = type; + + autoColor(this, type); + } else { + showAlert(`node ${this.title} input undefined.`, this) + } + } + if (link_info && this.graph && slotType === LiteGraph.OUTPUT && isChangeConnect) { + const inputType = this.inputs[0]?.type; + if (inputType && inputType !== '*') { + this.outputs[0].type = inputType; + this.outputs[0].name = inputType; + } else { + const resolve = link_info.resolve(this.graph); + const type = resolve?.input?.type; + if (type && type !== '*') { + this.inputs[0].type = type; + this.inputs[0].name = type; + this.outputs[0].type = type; + this.outputs[0].name = type; + autoColor(this, type); + } + } + } + + //Update either way + this.update(); + } + + // Returns true if the name was changed + validateName(graph, sameGraphOnly) { + let widgetValue = this.widgets[0].value; + + if (widgetValue !== '') { + let tries = 0; + const existingValues = new Set(); + + // sameGraphOnly: only check the immediate graph (for paste/clone) + // otherwise check full scope (own graph + ancestors) + const scopeGraphs = sameGraphOnly ? [graph] : getGraphAncestors(graph); + const scopedSetNodes = collectNodesOfType(scopeGraphs, 'SetNode'); + scopedSetNodes.forEach(entry => { + if (entry.node !== this) { + existingValues.add(entry.node.widgets[0].value); + } + }); + + const originalValue = widgetValue; + // Only strip _N suffix during paste to avoid FOO_0_1_2 accumulation. + // For manual renames, keep the full name as base (user may intend FOO_3). + const baseName = this._justAdded ? widgetValue.replace(/_\d+$/, '') : widgetValue; + while (existingValues.has(widgetValue)) { + widgetValue = baseName + "_" + tries; + tries++; + } + + this.widgets[0].value = widgetValue; + this.title = prefixedTitle("Set", widgetValue); + return widgetValue !== originalValue; + } + return false; + } + + clone() { + const cloned = super.clone(); + cloned.inputs[0].name = '*'; + cloned.inputs[0].type = '*'; + cloned.properties.previousName = ''; + cloned.size = cloned.computeSize(); + return cloned; + } + + onAdded() { + this._justAdded = true; + // Vue mode doesn't always re-extract GetNode options on SetNode add; skip during workflow load. + if (LiteGraph.vueNodesMode && this.graph && !app.configuringGraph) { + refreshAllGetNodeCombos(this.graph); + } + } + + onRemoved() { + // Only Vue mode needs the refresh — legacy re-reads the values getter on every click. + if (!LiteGraph.vueNodesMode) return; + const g = this.graph; + if (!g) return; + // Defer: onRemoved fires before _nodes is spliced, so getters still see this SetNode. + setTimeout(() => refreshAllGetNodeCombos(g), 0); + } + + onConfigure() { + // Only run paste logic when actually pasting, not during workflow load + if (this._justAdded && this.graph && !app.configuringGraph) { + const oldName = this.widgets[0].value; + this.validateName(this.graph, true); + this._justAdded = false; + const newName = this.widgets[0].value; + if (newName !== oldName) { + _pasteRenameMap.set(oldName, newName); + // Clear the map after this paste cycle + setTimeout(() => _pasteRenameMap.delete(oldName), 0); + } + // Reset type and color on paste — nothing is connected yet + if (this.inputs[0]?.link == null) { + this.inputs[0].type = '*'; + this.inputs[0].name = '*'; + this.outputs[0].type = '*'; + this.outputs[0].name = '*'; + this.color = null; + this.bgcolor = null; + } + } + this._justAdded = false; + } + + update() { + if (!this.graph) return; + + const getters = this.findGetters(this.graph); + getters.forEach(getter => { + getter.setType(this.inputs[0].type); + }); + + if (this.widgets[0].value && this.properties.previousName) { + const gettersWithPreviousName = this.findGetters(this.graph, true); + gettersWithPreviousName.forEach(getter => { + getter.setName(this.widgets[0].value); + }); + } + app.canvas?.setDirty(true, true); + } + + findGetters(graph, checkForPreviousName) { + const name = checkForPreviousName ? this.properties.previousName : this.widgets[0].value; + if (!name || name === '') return []; + // Scoped: searches own graph + descendant subgraphs + return findGettersByName(graph, name).map(entry => entry.node); + } + + getExtraMenuOptions(_, options) { + options.unshift( + { + content: this.drawConnection ? "Hide connections" : "Show connections", + callback: () => { + this.drawConnection = !this.drawConnection; + const linkType = this.inputs[0].type; + this.slotColor = this.canvas.default_connection_color_byType[linkType]; + this.canvas.setDirty(true, true); + }, + }, + { + content: "Hide all connections", + callback: () => { + for (const n of this.graph._nodes) { + if (n.type === "GetNode" || n.type === "SetNode") n.drawConnection = false; + } + this.canvas.setDirty(true, true); + }, + + }, + ); + options.unshift({ + content: "Convert to links", + callback: () => { + const graph = this.graph; + for (const n of snapshotSelectedNodes(this, 'SetNode')) convertSetGetToLinks(graph, n); + }, + }); + options.unshift({ + content: "Add paired GetNode", + callback: () => { + const graph = this.graph; + const getNode = LiteGraph.createNode("GetNode"); + if (!getNode) return; + getNode.pos = [this.pos[0] + this.size[0] + 30, this.pos[1]]; + graph.add(getNode); + // Set the widget value to match — this drives type, color, and connection + const name = this.widgets[0].value; + if (getNode.widgets?.[0]) { + getNode.widgets[0].value = name; + } + getNode.onRename?.(); + app.canvas.selectNode(getNode, false); + app.canvas.setDirty(true, true); + }, + }); + // Dynamically add a submenu for all getters + const allGettersForMenu = this.findGetters(this.graph); + if (allGettersForMenu.length) { + let gettersSubmenu = allGettersForMenu.map(getter => { + const sameGraph = getter.graph === this.graph; + const sgNode = !sameGraph ? findSubgraphNodeFor(this.graph, getter) : null; + const label = sameGraph + ? `${getter.title} id: ${getter.id}` + : `${getter.title} (in subgraph${sgNode ? ': ' + (sgNode.title || sgNode.type) : ''})`; + return { + content: label, + callback: () => { + if (sameGraph) { + this.canvas.centerOnNode(getter); + this.canvas.selectNode(getter, false); + } else if (sgNode) { + this.canvas.openSubgraph(sgNode.subgraph, sgNode); + // Center on the getter after entering the subgraph + setTimeout(() => { + this.canvas.centerOnNode(getter); + this.canvas.selectNode(getter, false); + }, 0); + } + this.canvas.setDirty(true, true); + }, + }; + }); + + options.unshift({ + content: "Getters", + has_submenu: true, + submenu: { + title: "GetNodes", + options: gettersSubmenu, + } + }); + } + } + } + + LiteGraph.registerNodeType("SetNode", SetNode); + }, +}); + +// region GetNode +app.registerExtension({ + name: "KJNodes.GetNode", + registerCustomNodes() { + class GetNode extends LGraphNode { + static title = "Get"; + static category = "KJNodes"; + serialize_widgets = true; + drawConnection = false; + currentSetter = null; + canvas = app.canvas; + + constructor(title) { + super(title) + if (!this.properties) { + this.properties = {}; + } + this.properties["Node name for S&R"] = "GetNode"; + this.properties["aux_id"] = "kijai/ComfyUI-KJNodes"; + this.isVirtualNode = true; // This node is purely frontend and does not impact the resulting prompt so should not be serialized + const comboOptions = { + getOptionLabel: (value) => { + if (!value) return ""; + const source = _setNameSourceMap.get(value); + if (!source || source === "local") return value; + return `${value} (${source})`; + }, + }; + Object.defineProperty(comboOptions, 'values', { + get: () => { + if (!this.graph) return []; + let filterType = null; + if (app.ui.settings.getSettingValue("KJNodes.filterGetNodeOptions") !== false + && this.outputs[0]?.links?.length) { + const linkId = this.outputs[0].links[0]; + const link = getLink(this.graph, linkId); + if (link) { + const targetNode = this.graph.getNodeById(link.target_id); + filterType = targetNode?.inputs?.[link.target_slot]?.type || null; + } + } + return getVisibleSetNames(this.graph, filterType); + }, + enumerable: true, + configurable: true + }); + const constantWidget = this.addWidget("combo", "Constant", "", () => { if (!app.configuringGraph) this.onRename(); }, comboOptions); + // Legacy-only fix: pass pre-labeled values to ContextMenu so the core filter shows the search input. + // Sidesteps ComboWidget's empty-array + getOptionLabel bug. Vue mode handles it natively. + const origOnClick = constantWidget.onClick?.bind(constantWidget); + constantWidget.onClick = (params) => { + if (LiteGraph.vueNodesMode) return origOnClick?.(params); + const { e, canvas, node } = params; + const x = e.canvasX - node.pos[0]; + const width = constantWidget.width || node.size[0]; + if (x < 40) return constantWidget.decrementValue({ e, node, canvas }); + if (x > width - 40) return constantWidget.incrementValue({ e, node, canvas }); + const rawValues = comboOptions.values; + const labels = rawValues.map(v => comboOptions.getOptionLabel(v) || v); + const menu = new LiteGraph.ContextMenu(labels, { + scale: Math.max(1, canvas.ds.scale), + event: e, + className: 'dark', + callback: (selectedLabel) => { + const idx = labels.indexOf(selectedLabel); + if (idx >= 0) constantWidget.setValue(rawValues[idx], { e, node, canvas }); + } + }); + // Color each entry's left border by its SetNode's type. + if (!_typeColorMap) setColorAndBgColor({}, ''); // ensure lazy map is initialized + const entries = menu.root?.querySelectorAll('.litemenu-entry'); + rawValues.forEach((name, i) => { + if (!entries?.[i]) return; + const setter = findSetterByName(this.graph, name); + const type = setter?.node?.inputs?.[0]?.type; + const c = _typeColorMap?.[type]; + const borderColor = canvas.default_connection_color_byType?.[type] + || LGraphCanvas.link_type_colors?.[type] + || (c && (c.groupcolor || c.bgcolor || c.color)) + || '#888'; + entries[i].style.borderLeft = `4px solid ${borderColor}`; + entries[i].style.paddingLeft = '8px'; + }); + }; + // Fresh options object (live getter preserved) + remove/re-add to force Vue re-extraction. + this._refreshComboOptions = () => { + const w = this.widgets?.[0]; + if (!w) return; + const newOpts = { getOptionLabel: comboOptions.getOptionLabel }; + Object.defineProperty(newOpts, 'values', + Object.getOwnPropertyDescriptor(comboOptions, 'values')); + w.options = newOpts; + const idx = this.widgets.indexOf(w); + if (idx >= 0) { + this.widgets.splice(idx, 1); + this.widgets.splice(idx, 0, w); + } + }; + this.addOutput("*", '*'); + } + + // A bypassed node passes its input through, but GetNode has no inputs, so a bypassed + // group would drop the value. While building the prompt, report BYPASS as ALWAYS. + get mode() { + const mode = super.mode; + return _resolvingPrompt > 0 && mode === MODE_BYPASS ? MODE_ALWAYS : mode; + } + set mode(value) { + super.mode = value; + } + + onConnectionsChange() { + if (app.configuringGraph) return; + this.validateLinks(); + } + + setName(name) { + this.widgets[0].value = name; + this.onRename(); + this.serialize(); + } + + onRename() { + const setter = this.findSetter(this.graph); + if (setter) { + this.setType(setter.inputs[0].type); + this.title = prefixedTitle("Get", setter.widgets[0].value); + } else { + this.setType('*'); + const name = this.widgets[0].value; + this.title = name ? prefixedTitle("Get", name) : "Get"; + } + app.canvas?.setDirty(true, true); + } + + clone() { + const cloned = super.clone(); + cloned.size = cloned.computeSize(); + return cloned; + } + + validateLinks() { + if (this.outputs[0].type !== '*' && this.outputs[0].links && this.graph) { + this.outputs[0].links.filter(linkId => { + const link = getLink(this.graph, linkId); + if (!link || !link.type) return false; + if (link.type === '*') return false; + const targetNode = this.graph.getNodeById(link.target_id); + const targetType = targetNode?.inputs?.[link.target_slot]?.type; + if (targetType === '*') return false; + if (targetType) { + const targetTypes = String(targetType).split(","); + if (targetTypes.includes(this.outputs[0].type)) return false; + } + return !link.type.split(",").includes(this.outputs[0].type); + }).forEach(linkId => { + this.graph.removeLink(linkId); + }); + } + } + + setType(type) { + this.outputs[0].name = type; + this.outputs[0].type = type; + this.validateLinks(); + autoColor(this, type); + } + + findSetter(graph) { + const name = this.widgets[0].value; + // Scoped: searches own graph first, then ancestors + const result = findSetterByName(graph, name); + return result ? result.node : undefined; + } + + goToSetter() { + if (!this.currentSetter) return; + const setterGraph = this.currentSetter.graph; + if (setterGraph && setterGraph !== this.graph) { + this.canvas.setGraph(setterGraph); + setTimeout(() => { + this.canvas.centerOnNode(this.currentSetter); + this.canvas.selectNode(this.currentSetter, false); + this.canvas.setDirty(true, true); + }, 0); + } else { + this.canvas.centerOnNode(this.currentSetter); + this.canvas.selectNode(this.currentSetter, false); + } + } + + onAdded() { + this._justAdded = true; + } + + onConfigure() { + if (this._justAdded && !app.configuringGraph) { + const name = this.widgets[0].value; + if (name) { + // Check if our paired SetNode was renamed during this paste + const newName = _pasteRenameMap.get(name); + if (newName) { + this.widgets[0].value = newName; + } + // Restore type/color from setter after paste + setTimeout(() => this.onRename(), 0); + } + } + this._justAdded = false; + } + + getInputLink(slot) { + // Same-graph: standard resolveOutput path. + // Cross-graph: handled by resolveVirtualOutput. + const name = this.widgets[0].value; + if (!name || name === '') return null; + const setter = this.graph?._nodes?.find( + n => n.type === 'SetNode' && n.widgets[0].value === name + ); + if (setter) { + const slotInfo = setter.inputs[slot]; + if (!slotInfo || slotInfo.link == null) return null; + return getLink(this.graph, slotInfo.link); + } + // Scoped lookup: no setter found in own graph or ancestors + if (name && !findSetterByName(this.graph, name)) { + showAlert("No SetNode found for " + name + "(" + this.type + ")", this); + } + return null; + } + + resolveVirtualOutput(slot) { + const name = this.widgets[0].value; + // Scoped lookup: own graph first, then ancestors + const result = findSetterByName(this.graph, name); + if (!result) return undefined; + + // Same graph — let the standard getInputLink path handle it + if (result.graph === this.graph) return undefined; + + // Warn if multiple SetNodes with this name exist in scope + const scopeGraphs = getGraphAncestors(this.graph); + const scopedSetters = collectNodesOfType(scopeGraphs, 'SetNode') + .filter(e => e.node.widgets[0].value === name); + if (scopedSetters.length > 1) { + showAlert(`Multiple SetNodes named "${name}" found in scope. Rename duplicates or use "Convert to links" to resolve`, [this, ...scopedSetters.map(e => e.node)]); + return undefined; + } + + const { node: setter, graph: setterGraph } = result; + const slotInfo = setter.inputs[slot]; + if (!slotInfo || slotInfo.link == null) return undefined; + + const link = getLink(setterGraph, slotInfo.link); + if (!link) return undefined; + + const sourceNode = setterGraph.getNodeById(link.origin_id); + if (!sourceNode) return undefined; + + return { node: sourceNode, slot: link.origin_slot }; + } + getExtraMenuOptions(_, options) { + this.currentSetter = this.findSetter(this.graph) + if (!this.currentSetter) return + const sameGraph = this.currentSetter.graph === this.graph; + if (sameGraph) { + let menuEntry = this.drawConnection ? "Hide connections" : "Show connections"; + options.unshift( + { + content: "Convert to links", + callback: () => { + const graph = this.graph; + const setters = new Set(snapshotSelectedNodes(this, 'GetNode') + .map(n => n.findSetter?.(graph)).filter(Boolean)); + for (const s of setters) convertSetGetToLinks(graph, s); + }, + }, + { + content: "Go to setter", + callback: () => { + this.goToSetter(); + }, + }, + { + content: menuEntry, + callback: () => { + if (!this.currentSetter) return; + const linkType = this.currentSetter.inputs[0].type; + // Toggle on the SetNode so the canvas-level hook draws it + this.currentSetter.drawConnection = !this.currentSetter.drawConnection; + this.currentSetter.slotColor = this.canvas.default_connection_color_byType[linkType]; + this.drawConnection = this.currentSetter.drawConnection; + this.canvas.setDirty(true, true); + }, + }, + ); + } else { + // Cross-graph setter — navigate to its graph + const setterGraph = this.currentSetter.graph; + const isRoot = setterGraph === findRootGraph(this.graph); + options.unshift( + { + content: `Go to setter (in ${isRoot ? 'parent graph' : 'subgraph'})`, + callback: () => { + const canvas = this.canvas; + canvas.setGraph(setterGraph); + setTimeout(() => { + canvas.centerOnNode(this.currentSetter); + canvas.selectNode(this.currentSetter, false); + canvas.setDirty(true, true); + }, 0); + }, + }, + ); + } + } + } + + LiteGraph.registerNodeType("GetNode", GetNode); + }, +}); + +// region UI: commands, keybindings, canvas menu, draw hook, settings +app.registerExtension({ + name: "KJNodes.SetGetUI", + settings: [ + { + id: "KJNodes.setGetNaming", + name: "Default SetNode widget value", + category: ["KJNodes", "Set & Get", "Default SetNode widget value"], + tooltip: "Initial Constant value when a Set node is first connected to a slot", + type: "combo", + options: ["empty", "slot name", "slot name (lowercase)", "slot name (UPPERCASE)"], + defaultValue: "empty", + }, + { + id: "KJNodes.showSetGetLinks", + name: "Show links", + category: ["KJNodes", "Set & Get", "Show links"], + tooltip: "When to show virtual links between Set/Get pairs", + type: "combo", + options: ["never", "selected", "always"], + defaultValue: "never", + onChange: () => app.canvas?.setDirty(true, true), + }, + { + id: "KJNodes.nodeAutoColor", + name: "Auto-color nodes", + category: ["KJNodes", "Set & Get", "Auto-color nodes"], + tooltip: "Automatically color Set/Get nodes based on their connection type", + type: "boolean", + defaultValue: true, + }, + { + id: "KJNodes.disablePrefix", + name: "Disable Set_/Get_ prefix", + category: ["KJNodes", "Set & Get", "Disable Set_/Get_ prefix"], + tooltip: "Prevents automatically adding Set_ and Get_ prefixes to node titles", + defaultValue: false, + type: "boolean", + }, + { + id: "KJNodes.shiftMiddleClickSetGet", + name: "Shift+middle-click creates Set/Get", + category: ["KJNodes", "Set & Get", "Shift+middle-click creates Set/Get"], + tooltip: "Shift+middle-click on a slot creates a connected SetNode (output) or GetNode (input) instead of Reroute", + type: "boolean", + defaultValue: true, + }, + { + id: "KJNodes.middleClickSetGet", + name: "Middle-click creates Set/Get", + category: ["KJNodes", "Set & Get", "Middle-click creates Set/Get"], + tooltip: "Middle-click on a slot creates Set/Get instead of Reroute (overrides core behavior)", + type: "boolean", + defaultValue: false, + }, + ], + commands: [ + { + id: "KJNodes.AddSetNodeToSelected", + label: "Add Set node to selected / at cursor", + function: () => addNodeToSelectedOrCursor("SetNode", "right"), + }, + { + id: "KJNodes.AddGetNodeAtCursor", + label: "Add Get node to selected / at cursor", + function: () => addNodeToSelectedOrCursor("GetNode", "left"), + }, + { + id: "KJNodes.ToggleForceShowSetGetLinks", + label: "Toggle force-show all Set/Get connections", + function: () => { + _forceShowAllLinks = !_forceShowAllLinks; + app.canvas.setDirty(true, true); + }, + }, + ], + keybindings: [ + { + commandId: "KJNodes.AddSetNodeToSelected", + combo: { key: "s", ctrl: true, shift: true }, + targetElementId: "graph-canvas", + }, + { + commandId: "KJNodes.AddGetNodeAtCursor", + combo: { key: "g", ctrl: true, shift: true }, + targetElementId: "graph-canvas", + }, + { + commandId: "KJNodes.ToggleForceShowSetGetLinks", + combo: { key: "l", ctrl: true, shift: true }, + targetElementId: "graph-canvas", + }, + ], + getCanvasMenuItems() { + return [ + { + content: "KJNodes", + has_submenu: true, + submenu: { + options: [ + { + content: "Convert outputs on all selected nodes to Set/Get", + callback: () => { + const selected = Object.values(app.canvas.selected_nodes || {}); + if (selected.length === 0) return; + for (const n of selected) convertOutputsToSetGet(n.graph, n); + }, + }, + { + content: "Convert selected Set/Get to links", + callback: () => { + const selected = Object.values(app.canvas.selected_nodes || {}); + const setNodes = selected.filter(n => n.type === 'SetNode'); + const getNodes = selected.filter(n => n.type === 'GetNode'); + for (const n of setNodes) convertSetGetToLinks(n.graph, n); + // Setter may live in an ancestor graph + const setters = new Set(getNodes.map(n => n.findSetter?.(n.graph)).filter(Boolean)); + for (const s of setters) convertSetGetToLinks(s.graph, s); + }, + }, + ], + }, + }, + ]; + }, + setup() { + // Double-click GetNode to jump to its SetNode (works in both legacy and Vue modes) + document.addEventListener("dblclick", (e) => { + // Don't interfere when a ContextMenu (e.g. combo dropdown) is open + if (document.querySelector(".litecontextmenu")) return; + const canvas = app.canvas; + if (!canvas) return; + const selected = Object.values(canvas.selected_nodes || {}); + if (selected.length !== 1) return; + const node = selected[0]; + if (node.type === "GetNode") { + node.currentSetter = node.findSetter(node.graph); + if (node.currentSetter) node.goToSetter(); + } + }); + // Suppress title rename on collapsed GetNodes so double-click navigates instead + document.addEventListener("litegraph:canvas", (e) => { + if (e.detail?.subType !== 'node-double-click') return; + const node = e.detail.node; + if (node?.type === "GetNode" && node.flags?.collapsed) { + e.stopImmediatePropagation(); + } + }); + + // Monkey-patch: no extension hook exists for filtering visible nodes. + // Keep Set/Get nodes with visible virtual connections in the visible set + // even when offscreen, so the link lines don't get clipped. + const originalComputeVisibleNodes = LGraphCanvas.prototype.computeVisibleNodes; + LGraphCanvas.prototype.computeVisibleNodes = function () { + const visible = originalComputeVisibleNodes.apply(this, arguments); + for (const node of this.graph._nodes) { + if ((node.type === "SetNode" || node.type === "GetNode") && node.drawConnection && !visible.includes(node)) { + visible.push(node); + } + } + return visible; + }; + + // Monkey-patch: no extension hook exists for custom canvas drawing. + // Draws virtual links between Set/Get pairs. + // Handles per-node "Show connections", "selected" mode, and "always" mode. + const origCanvasOnDrawBackground = app.canvas.onDrawBackground; + app.canvas.onDrawBackground = function(ctx, visibleArea) { + origCanvasOnDrawBackground?.call(this, ctx, visibleArea); + + const graph = this.graph || app.graph; + if (!graph?._nodes) return; + const mode = getShowLinksMode(); + + // Build set of selected Set/Get names for "selected" mode + let selectedNames = null; + if (mode === "selected") { + const sel = Object.values(this.selected_nodes || {}); + if (!sel.length) { + // No selection — still honor per-node drawConnection + if (!graph._nodes.some(n => n.type === 'SetNode' && n.drawConnection)) return; + } else { + selectedNames = new Set(); + for (const n of sel) { + if (n.type === 'SetNode' || n.type === 'GetNode') { + selectedNames.add(n.widgets?.[0]?.value ?? n.title); + } + } + if (!selectedNames.size && !graph._nodes.some(n => n.type === 'SetNode' && n.drawConnection)) return; + } + } else if (mode === "never") { + if (!graph._nodes.some(n => n.type === 'SetNode' && n.drawConnection)) return; + } + + // Collect all GetNodes once across current graph + descendants, grouped by name. + // This avoids re-discovering descendant graphs and re-scanning nodes per SetNode. + const gettersByName = new Map(); + const scopeGraphs = [graph, ...getGraphDescendants(graph)]; + for (const g of scopeGraphs) { + if (!g?._nodes) continue; + for (const node of g._nodes) { + if (node.type !== 'GetNode') continue; + const n = node.widgets?.[0]?.value; + if (!n) continue; + let list = gettersByName.get(n); + if (!list) { list = []; gettersByName.set(n, list); } + list.push(node); + } + } + + for (const setNode of graph._nodes) { + if (setNode.type !== 'SetNode') continue; + const name = setNode.widgets?.[0]?.value ?? setNode.title; + const showByMode = mode === "always" || (mode === "selected" && selectedNames?.has(name)); + if (!showByMode && !setNode.drawConnection) continue; + + const allGetters = gettersByName.get(name) || []; + const drawTargets = []; + const seenSubgraphs = new Set(); + for (const getter of allGetters) { + if (getter.graph === graph) { + drawTargets.push(getter); + } else { + const sgNode = findSubgraphNodeFor(graph, getter); + if (sgNode && !seenSubgraphs.has(sgNode)) { + seenSubgraphs.add(sgNode); + drawTargets.push(sgNode); + } + } + } + if (!drawTargets.length) continue; + + const linkType = setNode.inputs[0]?.type; + const slotColor = app.canvas.default_connection_color_byType?.[linkType] + || LGraphCanvas.link_type_colors?.[linkType] + || setNode.bgcolor + || (setNode.slotColor !== "#FFF" ? setNode.slotColor : null) || "#AAA"; + + const startPos = setNode.getConnectionPos(false, 0); + + for (const target of drawTargets) { + const endPos = target.getConnectionPos(true, 0); + const highlighted = setNode.is_selected || target.is_selected; + const color = highlighted ? "#FFF" : slotColor; + app.canvas.renderLink( + ctx, + startPos, + endPos, + null, + false, + null, + color, + LiteGraph.RIGHT, + LiteGraph.LEFT + ); + } + } + }; + + app.ui.settings.addSetting({ + id: "KJNodes.filterGetNodeOptions", + name: "Filter Get node options by type", + category: ["KJNodes", "Set & Get", "Filter Get node options by type"], + tooltip: "When a Get node is connected, only show Set nodes with compatible types in the dropdown", + type: "boolean", + defaultValue: true, + }); + app.ui.settings.addSetting({ + id: "KJNodes.convertAllSetGet", + name: "Convert ALL Set/Get to links", + category: ["KJNodes", "Set & Get", "Convert ALL Set/Get to links"], + tooltip: "Replaces all Set/Get node pairs with direct links, including across subgraph boundaries (irreversible)", + type: () => { + const btn = document.createElement("button"); + btn.textContent = "Convert ALL Set/Get to links"; + btn.style.cssText = "padding: 6px 12px; cursor: pointer;"; + btn.onclick = () => { + if (confirm("This will replace ALL Set/Get pairs with direct links. This is irreversible. Continue?")) { + convertAllSetGetToLinks(app.graph); + app.canvas?.setDirty(true, true); + app.extensionManager.toast.add({ + severity: 'info', + summary: "KJ Set/Get", + detail: "All Set/Get nodes converted to direct links", + life: 3000, + }); + } + }; + return btn; + }, + defaultValue: false, + }); + + // Middle-click Set/Get: let the core do slot hit detection, then intercept + // createDefaultNodeForSlot to create Set/Get instead of reroute. + let _fromMiddleClick = false; + let _lastMiddleClickShift = false; + const origProcessMiddle = LGraphCanvas.prototype._processMiddleButton; + LGraphCanvas.prototype._processMiddleButton = function(e, node) { + _fromMiddleClick = true; + _lastMiddleClickShift = !!e.shiftKey; + const wantSetGet = _lastMiddleClickShift + ? app.ui.settings.getSettingValue("KJNodes.shiftMiddleClickSetGet") ?? true + : app.ui.settings.getSettingValue("KJNodes.middleClickSetGet") ?? false; + const saved = LiteGraph.middle_click_slot_add_default_node; + if (wantSetGet) { + LiteGraph.middle_click_slot_add_default_node = true; + } else { + // Workaround: core slotDefaults.init() resets this flag to true + const coreSetting = app.ui.settings.getSettingValue("Comfy.Node.MiddleClickRerouteNode"); + if (coreSetting === false) LiteGraph.middle_click_slot_add_default_node = false; + } + const result = origProcessMiddle.call(this, e, node); + LiteGraph.middle_click_slot_add_default_node = saved; + return result; + }; + const origCreateDefault = LGraphCanvas.prototype.createDefaultNodeForSlot; + LGraphCanvas.prototype.createDefaultNodeForSlot = function(optPass) { + if (!_fromMiddleClick) return origCreateDefault.call(this, optPass); + _fromMiddleClick = false; + const wantSetGet = _lastMiddleClickShift + ? app.ui.settings.getSettingValue("KJNodes.shiftMiddleClickSetGet") ?? true + : app.ui.settings.getSettingValue("KJNodes.middleClickSetGet") ?? false; + if (!wantSetGet) return origCreateDefault.call(this, optPass); + + const isFrom = optPass.nodeFrom && optPass.slotFrom !== null; + const sourceNode = isFrom ? optPass.nodeFrom : optPass.nodeTo; + const slotIndex = isFrom ? optPass.slotFrom : optPass.slotTo; + if (!sourceNode || slotIndex == null) return origCreateDefault.call(this, optPass); + const graph = this.graph || app.graph; + if (!graph) return origCreateDefault.call(this, optPass); + + const newNode = LiteGraph.createNode(isFrom ? "SetNode" : "GetNode"); + if (!newNode) return false; + const bounding = sourceNode.getBounding(); + newNode.pos = [ + isFrom ? bounding[0] + bounding[2] + 30 : bounding[0] - 200, + optPass.position?.[1] ?? bounding[1] + ]; + graph.add(newNode); + if (isFrom) sourceNode.connect(slotIndex, newNode, 0); + else newNode.connect(0, sourceNode, slotIndex); + graph.change(); + this.setDirty(true, true); + return true; + }; + } +}); + +// Counts graphToPrompt calls for bypassed GetNodes (see GetNode.mode), plus a temporary cross-subgraph Set/Get patch for +// frontends without resolveVirtualOutput; remove only the patch part when no longer needed. +app.registerExtension({ + name: "KJNodes.CrossGraphSetGet", + setup() { + let patched = false; + + const originalGraphToPrompt = app.graphToPrompt.bind(app); + app.graphToPrompt = async function(...args) { + if (!patched) { + try { + const subgraphNode = app.graph._nodes.find(n => typeof n.getInnerNodes === 'function'); + if (subgraphNode) { + const tempMap = new Map(); + const dtos = subgraphNode.getInnerNodes(tempMap, []); + if (dtos.length > 0) { + const proto = Object.getPrototypeOf(dtos[0]); + const DtoClass = proto.constructor; + const nativeSource = proto.resolveOutput.toString(); + const hasNativeSupport = nativeSource.includes('resolveVirtualOutput'); + console.log(`[KJNodes] Cross-graph Set/Get: frontend native support ${hasNativeSupport ? 'detected, skipping patch' : 'not found, applying patch'}`); + if (!hasNativeSupport) { + const origResolveOutput = proto.resolveOutput; + proto.resolveOutput = function(slot, type, visited) { + if (typeof this.node?.resolveVirtualOutput === 'function') { + const virtualSource = this.node.resolveVirtualOutput(slot); + if (virtualSource) { + const inputNodeDto = [...this.nodesByExecutionId.values()] + .find(dto => dto instanceof DtoClass && dto.node === virtualSource.node); + if (inputNodeDto) { + return inputNodeDto.resolveOutput(virtualSource.slot, type, visited); + } + throw new Error(`KJNodes: No DTO found for cross-graph source node [${virtualSource.node.id}]`); + } + } + return origResolveOutput.call(this, slot, type, visited); + }; + } + patched = true; + } + } + } catch (e) { + console.warn('[KJNodes] Failed to probe ExecutableNodeDTO for cross-graph patch:', e); + } + } + _resolvingPrompt++; + try { + return await originalGraphToPrompt(...args); + } finally { + _resolvingPrompt--; + } + }; + } +}); + +// Monkey-patch: no hook exists to extend the link context menu. +// Appends a "Convert to Set/Get" entry by counting DOM menus before/after +// the original call to find the newly created one. Fragile but unavoidable. +app.registerExtension({ + name: "KJNodes.LinkToSetGet", + setup() { + const originalShowLinkMenu = LGraphCanvas.prototype.showLinkMenu; + LGraphCanvas.prototype.showLinkMenu = function(segment, e, presentationLink) { + const menusBefore = document.querySelectorAll(".litecontextmenu").length; + const result = originalShowLinkMenu.apply(this, arguments); + + const graph = this.graph; + if (!graph) return result; + + // Get the full link object to access target info; a Reroute segment's id is a reroute id, not a link id + const linkId = presentationLink?.id ?? (segment.linkIds instanceof Set ? segment.linkIds.values().next().value : segment.id); + const link = getLink(graph, linkId); + if (!link || link.origin_id == null || link.target_id == null) return result; + + // Find the newly created context menu + const menus = document.querySelectorAll(".litecontextmenu"); + if (menus.length <= menusBefore) return result; + const lastMenu = menus[menus.length - 1]; + if (!lastMenu) return result; + + const entries = lastMenu.querySelector(".litemenu-entry")?.parentElement; + if (!entries) return result; + + // Create separator + const separator = document.createElement("div"); + separator.className = "litemenu-entry separator"; + entries.appendChild(separator); + + // Create menu entry + const menuItem = document.createElement("div"); + menuItem.className = "litemenu-entry submenu"; + menuItem.textContent = "Convert to Set/Get"; + entries.appendChild(menuItem); + + const canvas = this; + menuItem.addEventListener("click", function() { + // Close menu + lastMenu.remove(); + + // Subgraph IO boundaries aren't in graph._nodes + const originNode = graph.getNodeById(link.origin_id) + ?? (link.origin_id === graph.inputNode?.id ? graph.inputNode : null); + const targetNode = graph.getNodeById(link.target_id) + ?? (link.target_id === graph.outputNode?.id ? graph.outputNode : null); + if (!originNode || !targetNode) return; + + const outputSlot = originNode.outputs?.[link.origin_slot] ?? originNode.slots?.[link.origin_slot]; + const linkType = outputSlot?.type || "*"; + const linkName = outputSlot?.name || linkType; + + // Create Set node near the source + const setNode = LiteGraph.createNode("SetNode"); + if (!setNode) return; + setNode.pos = [ + originNode.pos[0] + originNode.size[0] + 30, + originNode.pos[1] + ]; + graph.add(setNode); + + // Create Get node near the target + const getNode = LiteGraph.createNode("GetNode"); + if (!getNode) return; + graph.add(getNode); + getNode.pos = [ + targetNode.pos[0] - getNode.size[0] - 30, + targetNode.pos[1] + ]; + + // Remove the original link + graph.removeLink(link.id); + + // Connect source -> Set node input + connectById(graph, link.origin_id, link.origin_slot, setNode.id, 0); + + // Set the name widget on the Set node + setNode.widgets[0].value = linkName; + setNode.title = prefixedTitle("Set", linkName); + setNode.validateName(graph); + setNode.properties.previousName = setNode.widgets[0].value; + + // Update Get node to match + const finalName = setNode.widgets[0].value; + getNode.widgets[0].value = finalName; + getNode.onRename(); + + // Connect Get node output -> target node input + connectById(graph, getNode.id, 0, link.target_id, link.target_slot); + + canvas.setDirty(true, true); + }); + + return result; + }; + } +}); diff --git a/docs/hel-892/setget-reference/web__js__utility.js b/docs/hel-892/setget-reference/web__js__utility.js new file mode 100644 index 00000000..4dcf3bf5 --- /dev/null +++ b/docs/hel-892/setget-reference/web__js__utility.js @@ -0,0 +1,291 @@ +const { app } = window.comfyAPI.app; + +// ─── General-purpose helpers shared across KJNodes JS ─── + +export function makeUUID() { + let dt = new Date().getTime() + const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = ((dt + Math.random() * 16) % 16) | 0 + dt = Math.floor(dt / 16) + return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16) + }) + return uuid +} + +export function chainCallback(object, property, callback) { + if (object == undefined) { + console.error("Tried to add callback to non-existant object") + return; + } + if (property in object) { + const callback_orig = object[property] + object[property] = function () { + const r = callback_orig.apply(this, arguments); + callback.apply(this, arguments); + return r + }; + } else { + object[property] = callback; + } +} + +export function hideWidgetForGood(node, widget, suffix = '') { + widget.origType = widget.type + widget.origComputeSize = widget.computeSize + widget.origSerializeValue = widget.serializeValue + widget.computeSize = () => [0, -4] + widget.type = "converted-widget" + suffix + if (widget.linkedWidgets) { + for (const w of widget.linkedWidgets) { + hideWidgetForGood(node, w, ':' + widget.name) + } + } +} + +// ─── Graph coordinate helpers ─── + +export function clientToCanvas(lgCanvas, clientX, clientY) { + const rect = lgCanvas.canvas.getBoundingClientRect(); + return [ + (clientX - rect.left) / lgCanvas.ds.scale - lgCanvas.ds.offset[0], + (clientY - rect.top) / lgCanvas.ds.scale - lgCanvas.ds.offset[1], + ]; +} + +export function getNodeAtPoint(graph, cx, cy) { + for (let i = graph._nodes.length - 1; i >= 0; i--) { + if (graph._nodes[i].isPointInside(cx, cy)) return graph._nodes[i]; + } + return null; +} + +export function typesCompatible(a, b) { + if (a === "*" || b === "*") return true; + if (a === b) return true; + if (typeof a !== "string" || typeof b !== "string") return false; + if (a.toUpperCase() === b.toUpperCase()) return true; + // ComfyUI accepts union types like "STRING,INT" — match if any token overlaps + if (a.includes(",") || b.includes(",")) { + const aTokens = a.toUpperCase().split(",").map(s => s.trim()).filter(Boolean); + const bTokens = b.toUpperCase().split(",").map(s => s.trim()).filter(Boolean); + if (aTokens.includes("*") || bTokens.includes("*")) return true; + return aTokens.some(t => bTokens.includes(t)); + } + return false; +} + +// ─── Slot position helper ─── +// Uses modern API (DOM-registered positions in Vue mode) with legacy fallback +export function getSlotPos(node, isInput, slotIdx) { + if (isInput && node.getInputPos) return node.getInputPos(slotIdx); + if (!isInput && node.getOutputPos) return node.getOutputPos(slotIdx); + const out = [0, 0]; + node.getConnectionPos(isInput, slotIdx, out); + return out; +} + +// Link by node id; subgraph IO nodes aren't in graph._nodes and have no connect(), so go through their slot objects +export function connectById(graph, originId, originSlot, targetId, targetSlot, afterRerouteId) { + const target = graph.getNodeById(targetId); + if (graph.inputNode && originId === graph.inputNode.id) { + const input = target?.inputs?.[targetSlot]; + return input ? graph.inputNode.slots[originSlot]?.connect(input, target, afterRerouteId) ?? null : null; + } + const origin = graph.getNodeById(originId); + if (!origin) return null; + if (graph.outputNode && targetId === graph.outputNode.id) { + const output = origin.outputs?.[originSlot]; + return output ? graph.outputNode.slots[targetSlot]?.connect(output, origin, afterRerouteId) ?? null : null; + } + return target ? origin.connect(originSlot, target, targetSlot, afterRerouteId) : null; +} + +// ─── Middle-click pan passthrough for DOM widgets ─── +// Allows panning the LiteGraph canvas via middle-click drag on any DOM element +export function addMiddleClickPan(element) { + const onMouseDown = (e) => { + if (e.button !== 1) return; + e.preventDefault(); + const ds = app.canvas?.ds; + if (!ds) return; + const startX = e.clientX, startY = e.clientY; + const startOffsetX = ds.offset[0], startOffsetY = ds.offset[1]; + const onMove = (me) => { + const scale = ds.scale || 1; // offset is graph-space; LiteGraph pans by (screen delta / scale) + ds.offset[0] = startOffsetX + (me.clientX - startX) / scale; + ds.offset[1] = startOffsetY + (me.clientY - startY) / scale; + app.canvas.setDirty(true, true); + }; + const onUp = () => { + document.removeEventListener('mousemove', onMove); + document.removeEventListener('mouseup', onUp); + }; + document.addEventListener('mousemove', onMove); + document.addEventListener('mouseup', onUp); + }; + element.addEventListener('mousedown', onMouseDown); + return () => element.removeEventListener('mousedown', onMouseDown); +} + +// The widget holding a loader's input file: Load Image "image", VHS-style "video", core Load Video "file" +const sourceFileWidget = (srcNode) => srcNode.widgets?.find((w) => w.name === "image" || w.name === "video" || (w.name === "file" && srcNode.comfyClass === "LoadVideo")); + +// ─── Resolve preview image/video from a connected source node ─── +// Walks the graph link to find what's connected to node.inputs[inputSlot] +// and returns { url, isVideo, videoEl } or null +export function resolveSourcePreview(node, inputSlot) { + if (!node.graph) return null; + const input = node.inputs?.[inputSlot]; + if (!input || input.link == null) return null; + const link = node.graph.links?.get(input.link); + if (!link) return null; + const srcNode = node.graph.getNodeById(link.origin_id); + if (!srcNode) return null; + + // Check for VHS-style video preview widget + const vpWidget = srcNode.widgets?.find((w) => w.name === "videopreview"); + if (vpWidget?.videoEl?.src) { + return { isVideo: true, videoEl: vpWidget.videoEl }; + } + + const w = sourceFileWidget(srcNode); + if (w?.value) { + let subfolder = "", fname = w.value; + const lastSlash = fname.lastIndexOf("/"); + if (lastSlash >= 0) { subfolder = fname.substring(0, lastSlash); fname = fname.substring(lastSlash + 1); } + const isVideo = w.name !== "image"; + const url = `/view?filename=${encodeURIComponent(fname)}&type=input&subfolder=${encodeURIComponent(subfolder)}`; + return { url, isVideo }; + } + + // Fallback: check node.imgs (set after execution) + if (srcNode.imgs?.length > 0 && srcNode.imgs[0].src) { + return { url: srcNode.imgs[0].src, isVideo: false }; + } + return null; +} + +// ─── Source input watcher ─── +// Watches IMAGE inputs for connection changes and source widget changes. +// Calls onChange(sources) when connections change or the source node's image/video widget changes. +// inputName: an input name, a predicate (input) => bool, or null for every IMAGE input. +// sources: array of { url, isVideo, videoEl, name } per connected matching input (name = that input's name). +// Returns a cleanup function. +export function watchImageInputs(node, inputName, onChange) { + let watchedWidgets = []; + const matches = (inp) => typeof inputName === "function" ? inputName(inp) : inputName ? inp.name === inputName : inp.type === "IMAGE"; + const matchingSlots = () => node.inputs.map((inp, i) => matches(inp) ? i : -1).filter(i => i >= 0); + + function unwatchWidgets() { + for (const { widget, origCb } of watchedWidgets) widget.callback = origCb; + watchedWidgets = []; + } + + function resolve() { + if (!node.inputs) return []; + return matchingSlots().map(i => { + const s = resolveSourcePreview(node, i); + return s && { ...s, name: node.inputs[i].name }; + }).filter(s => s); + } + + function watch() { + unwatchWidgets(); + if (!node.inputs || !node.graph) return; + const slots = matchingSlots(); + for (const slotIdx of slots) { + const input = node.inputs[slotIdx]; + if (!input || input.link == null) continue; + const link = node.graph.links?.get(input.link); + if (!link) continue; + const srcNode = node.graph.getNodeById(link.origin_id); + if (!srcNode) continue; + const w = sourceFileWidget(srcNode); + if (!w) continue; + const origCb = w.callback; + w.callback = function (...args) { + if (origCb) origCb.apply(this, args); + setTimeout(() => onChange(resolve()), 100); + }; + watchedWidgets.push({ widget: w, origCb }); + } + } + + chainCallback(node, "onConnectionsChange", function (type) { + // Only react to input connection changes, not output + if (type != null && type !== 1) return; + setTimeout(() => { + watch(); + onChange(resolve()); + }, 100); + }); + + chainCallback(node, "onRemoved", unwatchWidgets); + + return unwatchWidgets; +} + +// ─── Video frame capture ─── +// Draws the current frame of a video element to a fresh canvas at native resolution. +// If the video isn't decoded yet (readyState < 2), waits once for "loadeddata" before capturing. +// Calls callback(canvas) with the resulting canvas. Caller decides whether to use it directly +// (drawImage accepts canvas) or convert via toDataURL. +export function captureVideoFrame(videoEl, callback) { + const capture = () => { + if (!videoEl.videoWidth || !videoEl.videoHeight) return; + const c = document.createElement("canvas"); + c.width = videoEl.videoWidth; + c.height = videoEl.videoHeight; + c.getContext("2d").drawImage(videoEl, 0, 0); + callback(c); + }; + if (videoEl.readyState >= 2) { + capture(); + } else { + const onReady = () => { videoEl.removeEventListener("loadeddata", onReady); capture(); }; + videoEl.addEventListener("loadeddata", onReady); + } +} + +// ─── Bounding box hit test ─── +// Tests whether (mx, my) hits a corner handle or the interior of a rect defined by (x1, y1)–(x2, y2). +// Returns "resize-tl", "resize-tr", "resize-bl", "resize-br", "resize-t", "resize-b", "resize-l", "resize-r", "move", or null. +export function rectHitTest(mx, my, x1, y1, x2, y2, radius) { + const hit = (cx, cy) => Math.abs(mx - cx) < radius && Math.abs(my - cy) < radius; + // Corners first (higher priority) + if (hit(x1, y1)) return "resize-tl"; + if (hit(x2, y1)) return "resize-tr"; + if (hit(x1, y2)) return "resize-bl"; + if (hit(x2, y2)) return "resize-br"; + // Edges + if (mx >= x1 && mx <= x2 && Math.abs(my - y1) < radius) return "resize-t"; + if (mx >= x1 && mx <= x2 && Math.abs(my - y2) < radius) return "resize-b"; + if (my >= y1 && my <= y2 && Math.abs(mx - x1) < radius) return "resize-l"; + if (my >= y1 && my <= y2 && Math.abs(mx - x2) < radius) return "resize-r"; + // Interior + if (mx >= x1 && mx <= x2 && my >= y1 && my <= y2) return "move"; + return null; +} + +// Returns the appropriate CSS cursor for a bbox hit mode string. +export function cursorForBboxMode(mode) { + if (mode === "move") return "move"; + if (mode === "resize-tl" || mode === "resize-br") return "nwse-resize"; + if (mode === "resize-tr" || mode === "resize-bl") return "nesw-resize"; + if (mode === "resize-t" || mode === "resize-b") return "ns-resize"; + if (mode === "resize-l" || mode === "resize-r") return "ew-resize"; + return null; +} + +// ─── Wheel zoom passthrough for DOM widgets ─── +// Re-dispatches wheel events to the LiteGraph canvas for zoom +export function addWheelPassthrough(element) { + element.addEventListener("wheel", (e) => { + const gc = document.getElementById("graph-canvas"); + if (gc) { + gc.dispatchEvent(new WheelEvent(e.type, e)); + e.preventDefault(); + } + }, { passive: false }); +} +