Agent skill that turns natural language, code, Terraform/K8s, SQL, OpenAPI, AsyncAPI, Protobuf and GraphQL sources into editable, tested draw.io architecture diagrams: incremental sync, multi-view projection, drift diff, CI architecture tests, whiteboard derasterize, interactive HTML/PPTX/Mermaid exports.
Python agent-skillsarchitecturearchitecture-diagramasyncapibpmnc4-modelclaude-codediagramdiagrams-as-codedrawioflowchartgithub-actionsgraphqlimage-to-diagramkubernetesmcp-serverprotobufsysmlterraformuml
feat: add GraphQL SDL importer (graphqlerd.py) (#121)
Parman Mohammadalizadeh8b36e466600f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 23eb601..210923e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,19 @@ on [Keep a Changelog](https://keepachangelog.com/), and the project followssemantic-ish versioning (the `metadata.version` field in`skills/drawio-skill/SKILL.md`).+## [Unreleased]++### Added++- **GraphQL importer** (`graphqlerd.py`): parse GraphQL SDL (`.graphql` / `.gql`)+ or an introspection JSON dump into an entity type diagram. One node per+ `type`, `interface`, `input`, `enum`, `union` or custom `scalar`, listing each+ field with its type and marking `@deprecated`, with source provenance, edges+ for field references, `implements` and union membership, dimmed enum and+ scalar leaves, and optional grouping by source schema file. Wired into+ `diagramctl.py build` (auto-detected from `.graphql` / `.gql`) and the MCP+ server.+## [3.3.0] - 2026-09-12### Addeddiff --git a/README.md b/README.mdindex 268aa96..5235333 100644--- a/README.md+++ b/README.md@@ -31,7 +31,7 @@ A skill that turns natural language and real system sources into maintainable `.- **Visualize a codebase** — import graphs for Python / JS-TS / Go / Rust and Python class hierarchies, with Graphviz placement, transitive reduction, and nested module containers- **IaC and live infrastructure** — Terraform, Kubernetes, and docker-compose configs become diagrams with official AWS / Azure / GCP / K8s icons; snapshot what's *actually deployed* from `terraform show -json`, `docker inspect`, or `kubectl get -o json`-- **Schemas and pipelines** — SQL DDL → ER diagram, OpenAPI/Swagger → API diagram coloured by HTTP method, AsyncAPI → event-driven architecture diagram, Protocol Buffers → message/service diagram, GitHub Actions / GitLab CI → pipeline DAG+- **Schemas and pipelines** — SQL DDL → ER diagram, OpenAPI/Swagger → API diagram coloured by HTTP method, AsyncAPI → event-driven architecture diagram, Protocol Buffers → message/service diagram, GraphQL SDL → entity type diagram, GitHub Actions / GitLab CI → pipeline DAG- **Deterministic engines** — sequence diagrams with computed lifelines and activation bars; multi-page C4 models with click-to-drill-down@@ -201,7 +201,7 @@ The full toolbox, grouped by stage:| Stage | Tools || --- | --- |-| **Import** | 15 extractors: **Python · JS/TS · Go · Rust** import graphs, **Python class inheritance**, **Terraform / Kubernetes / docker-compose** with official cloud icons, **live** infra from `terraform show -json` / `docker inspect` / `kubectl get -o json`, **SQL DDL → ERD**, **OpenAPI → API diagram** (coloured by HTTP method), **AsyncAPI → event-driven architecture diagram**, **Protobuf → message/service diagram**, **GitHub Actions + GitLab CI → DAG** |+| **Import** | 16 extractors: **Python · JS/TS · Go · Rust** import graphs, **Python class inheritance**, **Terraform / Kubernetes / docker-compose** with official cloud icons, **live** infra from `terraform show -json` / `docker inspect` / `kubectl get -o json`, **SQL DDL → ERD**, **OpenAPI → API diagram** (coloured by HTTP method), **AsyncAPI → event-driven architecture diagram**, **Protobuf → message/service diagram**, **GraphQL SDL → entity type diagram**, **GitHub Actions + GitLab CI → DAG** || **Compare & evolve** | `drawiodiff.py` colour-codes drift between two diagrams or two live snapshots (added=green, removed=red, changed=orange); `timelapse.py` replays git history as an HTML player; `prdiff.py` renders PR diffs in CI || **Repurpose** | `explain.py` → Markdown, `drawiohtml.py` → pan/zoom/search HTML viewer, `drawio2pptx.py` → deck, `svgflow.py` → animated SVG, `drawio2mermaid.py` → diagrams-as-code, `runbook.py` → clickable triage app, `compress.py` → exec summary with drill-down, `buildup.py` → self-drawing player, `tubemap.py` → metro map || **Restyle & enrich** | `restyle.py` applies presets by hue remap, `relabel.py` produces translated twins with layout untouched, `heatmap.py` shades nodes from a metrics CSV/JSON, `edgeports.py` un-stacks edges at shape boundaries |diff --git a/README_CN.md b/README_CN.mdindex 30d72ab..df31986 100644--- a/README_CN.md+++ b/README_CN.md@@ -198,7 +198,7 @@ python3 scripts/drawiohtml.py architecture.drawio -o architecture.html| 阶段 | 工具 || --- | --- |-| **导入** | 15 个提取器:**Python · JS/TS · Go / Rust** 导入关系图、**Python 类继承**、**Terraform / Kubernetes / docker-compose**(官方云图标)、从 `terraform show -json` / `docker inspect` / `kubectl get -o json` 提取的**实时**基础设施、**SQL DDL → ER 图**、**OpenAPI → API 图**(按 HTTP 方法着色)、**AsyncAPI → 事件驱动架构图**、**Protobuf → 消息/服务图**、**GitHub Actions + GitLab CI → DAG** |+| **导入** | 16 个提取器:**Python · JS/TS · Go / Rust** 导入关系图、**Python 类继承**、**Terraform / Kubernetes / docker-compose**(官方云图标)、从 `terraform show -json` / `docker inspect` / `kubectl get -o json` 提取的**实时**基础设施、**SQL DDL → ER 图**、**OpenAPI → API 图**(按 HTTP 方法着色)、**AsyncAPI → 事件驱动架构图**、**Protobuf → 消息/服务图**、**GraphQL SDL → 实体类型图**、**GitHub Actions + GitLab CI → DAG** || **对比与演进** | `drawiodiff.py` 用颜色标出两张图或两个实时快照的漂移(新增=绿、删除=红、变更=橙);`timelapse.py` 把 git 历史重放成 HTML 播放器;`prdiff.py` 在 CI 里渲染 PR diff || **二次利用** | `explain.py` → Markdown,`drawiohtml.py` → 平移缩放搜索的 HTML 查看器,`drawio2pptx.py` → 演示稿,`svgflow.py` → 动画 SVG,`drawio2mermaid.py` → diagrams-as-code,`runbook.py` → 点击式排查应用,`compress.py` → 可下钻的高管摘要,`buildup.py` → 自动绘制播放器,`tubemap.py` → 地铁图 || **换肤与增强** | `restyle.py` 按色相重映射应用预设,`relabel.py` 布局不动地生成翻译变体,`heatmap.py` 按指标 CSV/JSON 给节点上色,`edgeports.py` 解开形状边界上堆叠的连线 |diff --git a/skills/drawio-skill/SKILL.md b/skills/drawio-skill/SKILL.mdindex 7fd0e29..6967de4 100644--- a/skills/drawio-skill/SKILL.md+++ b/skills/drawio-skill/SKILL.md@@ -1,6 +1,6 @@---name: drawio-skill-description: Create, edit, synchronize, inspect, test, and publish editable draw.io diagrams. Use when the user explicitly requests draw.io/diagrams.net, needs a polished architecture, ERD, UML, sequence, C4, SysML, BPMN, network, swimlane, ML, or infrastructure diagram, wants code/IaC/SQL/OpenAPI/AsyncAPI/Protobuf converted into a diagram, or wants an existing diagram queried, reviewed, diffed, restyled, kept in sync, or made interactive. Prefer Mermaid/PlantUML elsewhere when the requested artifact is diagrams-as-code rather than an editable draw.io file.+description: Create, edit, synchronize, inspect, test, and publish editable draw.io diagrams. Use when the user explicitly requests draw.io/diagrams.net, needs a polished architecture, ERD, UML, sequence, C4, SysML, BPMN, network, swimlane, ML, or infrastructure diagram, wants code/IaC/SQL/OpenAPI/AsyncAPI/Protobuf/GraphQL converted into a diagram, or wants an existing diagram queried, reviewed, diffed, restyled, kept in sync, or made interactive. Prefer Mermaid/PlantUML elsewhere when the requested artifact is diagrams-as-code rather than an editable draw.io file.license: MITallowed-tools: [Bash, Read, Write, WebFetch]metadata: {"openclaw":{"requires":{"anyBins":["python3"]},"emoji":"📐","os":["darwin","linux","win32"],"install":[{"id":"brew-drawio","kind":"brew","formula":"drawio","bins":["drawio"],"label":"Install draw.io for native exports","os":["darwin"],"optional":true},{"id":"brew-graphviz","kind":"brew","formula":"graphviz","bins":["dot"],"label":"Install Graphviz for automatic layout","os":["darwin"],"optional":true}]},"hermes":{"tags":["drawio","diagram","architecture","visualization","uml"],"category":"design","requires_tools":["python3"],"related_skills":["mermaid","excalidraw","plantuml"]},"author":"Agents365-ai","version":"3.3.0","homepage":"https://github.com/Agents365-ai/drawio-skill","compatibility":"Core IR, XML, sync, query, test, review, and Story workflows need Python 3 only; native export needs draw.io; Graphviz is optional.","platforms":["macos","linux","windows"]}@@ -22,6 +22,7 @@ and accessible publishing over a shared Diagram IR.| Large graph (~15+ nodes) that needs automatic layout | Use `autolayout.py`; read `references/autolayout.md` before passing any `--layout` value || Code, Terraform, K8s, compose, SQL, OpenAPI, AsyncAPI, or CI source | Use `diagramctl.py build`; read `references/diagram-ir.md` || Protocol Buffers schema (.proto) | Use `protoimports.py` or `diagramctl.py build`; read `references/toolbox.md` |+| GraphQL SDL schema (.graphql/.gql) or introspection JSON | Use `graphqlerd.py` or `diagramctl.py build`; read `references/toolbox.md` || Running cluster/stack/cloud (actual state, not declared config) | Read `references/live-infra.md`, then use `tfstate.py`, `dockerimports.py`, or `k8simports.py -` || Update a generated diagram without losing manual layout | Use `diagramctl.py sync`; read `references/diagram-ir.md` || Executive/system/deployment/data-flow/security views | Use `diagramctl.py views`; read `references/diagram-ir.md` |diff --git a/skills/drawio-skill/references/cookbook.md b/skills/drawio-skill/references/cookbook.mdindex 38c787d..184fb62 100644--- a/skills/drawio-skill/references/cookbook.md+++ b/skills/drawio-skill/references/cookbook.md@@ -144,6 +144,14 @@ Show RPC methods on the service nodes, group by proto package, and link request/and referenced field types. Output PNG + editable .drawio.```+## GraphQL schema type diagram++```text+Turn our GraphQL SDL under ./schema into an entity type diagram.+Show each type's fields with their types, link field references and implements,+group by schema file, and dim the enums. Output PNG + editable .drawio.+```+## ML / deep-learning model```textdiff --git a/skills/drawio-skill/references/diagram-ir.md b/skills/drawio-skill/references/diagram-ir.mdindex 3d37e00..0ee7823 100644--- a/skills/drawio-skill/references/diagram-ir.md+++ b/skills/drawio-skill/references/diagram-ir.md@@ -56,8 +56,8 @@ python3 scripts/diagramctl.py query architecture.drawio --from internet --to ord````build --from auto` recognizes Diagram IR/graph JSON, SQL, OpenAPI, AsyncAPI,-Protobuf, compose, Kubernetes YAML, and common repository markers. Use an-explicit `--from` when the source is ambiguous.+Protobuf, GraphQL, compose, Kubernetes YAML, and common repository markers. Use+an explicit `--from` when the source is ambiguous.## Reconcile instead of regeneratediff --git a/skills/drawio-skill/references/mcp.md b/skills/drawio-skill/references/mcp.mdindex 744d462..0ae452f 100644--- a/skills/drawio-skill/references/mcp.md+++ b/skills/drawio-skill/references/mcp.md@@ -30,7 +30,7 @@ call shells out to `scripts/diagramctl.py`, the same CLI the skill uses.| Tool | Maps to | Purpose || --- | --- | --- || `doctor` | `diagramctl doctor` | Check python/draw.io/Graphviz availability without launching anything |-| `build` | `build` | Code / IaC / SQL / OpenAPI / AsyncAPI / Protobuf / graph / IR → editable `.drawio` (+ optional IR) |+| `build` | `build` | Code / IaC / SQL / OpenAPI / AsyncAPI / Protobuf / GraphQL / graph / IR → editable `.drawio` (+ optional IR) || `sync` | `sync` | Incremental re-sync of a diagram from its changed source, preserving manual layout || `views` | `views` | Project an IR file into linked executive/system/deployment/dataflow/security pages || `architecture_test` | `test` | Deterministic architecture contract rules (policy YAML/JSON); `isError` mirrors the CI exit code |diff --git a/skills/drawio-skill/references/toolbox.md b/skills/drawio-skill/references/toolbox.mdindex d1583c0..488f951 100644--- a/skills/drawio-skill/references/toolbox.md+++ b/skills/drawio-skill/references/toolbox.md@@ -1,6 +1,6 @@# Toolbox — every bundled script, by use-case-A map of the 41 focused tools, the unified `diagramctl.py` orchestrator+A map of the 42 focused tools, the unified `diagramctl.py` orchestrator(and its MCP server wrapper), and itsinternal `diagram_ir.py` model grouped by what you're trying to do. Theper-task routing table in `SKILL.md` says *when* to reach for each; this says@@ -45,6 +45,7 @@ Use focused scripts directly when you need their narrow interface; use| an OpenAPI / Swagger spec | an API diagram (by method) | `openapiimports` || an AsyncAPI 2 / 3 spec | an event-driven architecture diagram | `asyncapiimports` || a Protocol Buffers (.proto) schema | a message/service diagram | `protoimports` |+| a GraphQL SDL schema | an entity type diagram | `graphqlerd` || CI workflows (GH Actions / GitLab) | the pipeline as a DAG | `ciimports` || a diagram + a metrics file | it coloured by the data | `heatmap` || a sequence of interactions | a UML sequence diagram | `seqlayout` |@@ -92,6 +93,7 @@ All emit graph JSON → `autolayout.py`.- **`openapiimports.py`** — OpenAPI 3 / Swagger 2 spec → API diagram: one node per operation (coloured by HTTP method) + one per component schema, with edges to the schemas each operation uses and between nested schemas. `--group` by tag.- **`asyncapiimports.py`** — AsyncAPI 2 / 3 spec → event-driven architecture diagram: channel, publish/subscribe operation, and payload-schema nodes with provenance. `--group` by operation tag, channel tag, or channel prefix.- **`protoimports.py`** — Protocol Buffers (`.proto`) → message/service diagram: one node per message, service (with RPC methods), or enum; edges for referenced message field types and service request/response types. `--group` by proto package.+- **`graphqlerd.py`** — GraphQL SDL (`.graphql` / `.gql`) or an introspection dump → entity type diagram: one node per `type`, `interface`, `input`, `enum`, `union` or custom `scalar`, listing its fields with types and marking `@deprecated`; edges for field references, `implements` and union membership. Enums and custom scalars are dimmed. `--group` by source schema file.## 4. Live infrastructure → diagram (actually running)diff --git a/skills/drawio-skill/scripts/diagramctl.py b/skills/drawio-skill/scripts/diagramctl.pyindex 9398296..9b200a1 100644--- a/skills/drawio-skill/scripts/diagramctl.py+++ b/skills/drawio-skill/scripts/diagramctl.py@@ -53,6 +53,7 @@ IMPORTERS = {"openapi": "openapiimports.py","asyncapi": "asyncapiimports.py","proto": "protoimports.py",+ "graphql": "graphqlerd.py","ci": "ciimports.py",}CODE_IMPORTERS = {"python", "javascript", "js", "go", "rust", "pyclasses"}@@ -92,14 +93,18 @@ def detect_source(path):return "javascript"if (p / ".github" / "workflows").exists() or (p / ".gitlab-ci.yml").exists():return "ci"- # Last, because a .proto file is often one schema inside a project whose- # own language markers above describe the repository better.+ # Last, because a .proto or .graphql file is often one schema inside a+ # project whose own language markers above describe the repository better.if list(p.rglob("*.proto")):return "proto"+ if list(p.rglob("*.graphql")) or list(p.rglob("*.gql")):+ return "graphql"return "python"suffix = p.suffix.lower()if suffix == ".proto":return "proto"+ if suffix in {".graphql", ".gql"}:+ return "graphql"if suffix == ".sql":return "sql"if suffix in {".tf", ".tfvars"}:@@ -175,6 +180,7 @@ def importer_ir(source, source_type, group=False):"openapi","asyncapi","proto",+ "graphql",}:cmd.insert(-2, "--group")proc = subprocess.run(cmd, text=True, capture_output=True)@@ -516,7 +522,7 @@ def parser():p = sub.add_parser("build",help="build a draw.io from IR, graph JSON, code, IaC, SQL, OpenAPI, "- "AsyncAPI or Protobuf",+ "AsyncAPI, Protobuf or GraphQL",)p.add_argument("source")p.add_argument("-o", "--output", required=True)diff --git a/skills/drawio-skill/scripts/diagramctl_mcp.py b/skills/drawio-skill/scripts/diagramctl_mcp.pyindex 93df2c2..71a0d3a 100644--- a/skills/drawio-skill/scripts/diagramctl_mcp.py+++ b/skills/drawio-skill/scripts/diagramctl_mcp.py@@ -54,7 +54,8 @@ TOOLS = ["name": "build","description": ("Build an editable .drawio diagram from code, IaC, SQL, OpenAPI, "- "AsyncAPI, Protobuf, compose, a graph JSON, or an existing IR file. "+ "AsyncAPI, Protobuf, GraphQL, compose, a graph JSON, or an existing IR "+ "file. ""Auto-detects the ""source type. Returns a JSON report and writes the .drawio (and ""optionally the IR JSON)."@@ -67,7 +68,7 @@ TOOLS = ["type": "string","description": "Override auto-detection ""(python|javascript|go|rust|pyclasses|terraform|kubernetes|"- "compose|sql|openapi|asyncapi|proto|ci|graph|ir|drawio)",+ "compose|sql|openapi|asyncapi|proto|graphql|ci|graph|ir|drawio)",},"group": {"type": "boolean",diff --git a/skills/drawio-skill/scripts/graphqlerd.py b/skills/drawio-skill/scripts/graphqlerd.pynew file mode 100644index 0000000..2d88a2e--- /dev/null+++ b/skills/drawio-skill/scripts/graphqlerd.py@@ -0,0 +1,432 @@+#!/usr/bin/env python3+"""Turn a GraphQL SDL schema into an entity type diagram as autolayout graph JSON.++Parses ``.graphql`` / ``.gql`` SDL (file or directory) or an introspection JSON+dump into one node per ``type`` / ``interface`` / ``input`` / ``enum`` /+``union`` / custom ``scalar``, listing each field with its type, and edges for+field references, ``implements`` and union membership.++Feeds autolayout.py:+ python3 graphqlerd.py ./schema --group -o graph.json+ python3 autolayout.py graph.json -o schema.drawio++The SDL parser is stdlib-only (no graphql-core). It understands descriptions,+comments, field arguments with defaults, list and non-null wrappers, directives+and ``extend``. Anything it does not recognise is skipped rather than guessed at,+so the worst case is a missing field, never a wrong edge.++Usage: python3 graphqlerd.py <file.graphql-or-dir-or-introspection.json>+ [-o graph.json] [--direction TB|LR] [--group] [--no-types]+"""+import argparse+import glob+import json+import os+import re+import sys++OBJECT_STYLE = (+ "rounded=1;whiteSpace=wrap;html=1;align=left;verticalAlign=top;"+ "spacingLeft=8;spacingTop=6;fillColor=#dae8fc;strokeColor=#6c8ebf;"+)+INTERFACE_STYLE = (+ "rounded=1;whiteSpace=wrap;html=1;align=left;verticalAlign=top;"+ "spacingLeft=8;spacingTop=6;fillColor=#e1d5e7;strokeColor=#9673a6;"+)+INPUT_STYLE = (+ "rounded=1;whiteSpace=wrap;html=1;align=left;verticalAlign=top;"+ "spacingLeft=8;spacingTop=6;fillColor=#d5e8d4;strokeColor=#82b366;"+)+UNION_STYLE = (+ "rounded=1;whiteSpace=wrap;html=1;align=left;verticalAlign=top;"+ "spacingLeft=8;spacingTop=6;fillColor=#ffe6cc;strokeColor=#d79b00;"+)+# Enums and custom scalars are leaves. The issue asks for them unlinked or+# dimmed; dimming keeps the field references visible while letting the object+# types carry the diagram.+LEAF_STYLE = (+ "rounded=1;whiteSpace=wrap;html=1;align=left;verticalAlign=top;"+ "spacingLeft=8;spacingTop=6;fillColor=#f5f5f5;strokeColor=#b3b3b3;"+ "fontColor=#666666;"+)++REF_EDGE = (+ "edgeStyle=orthogonalEdgeStyle;html=1;rounded=0;fontSize=10;"+ "dashed=1;endArrow=open;strokeColor=#6c8ebf;"+)+# UML realization, the conventional arrow for "implements".+IMPLEMENTS_EDGE = (+ "edgeStyle=orthogonalEdgeStyle;html=1;rounded=0;fontSize=10;"+ "dashed=1;endArrow=block;endFill=0;strokeColor=#9673a6;"+)+MEMBER_EDGE = (+ "edgeStyle=orthogonalEdgeStyle;html=1;rounded=0;fontSize=10;"+ "endArrow=open;strokeColor=#d79b00;"+)++STYLES = {+ "type": OBJECT_STYLE,+ "interface": INTERFACE_STYLE,+ "input": INPUT_STYLE,+ "union": UNION_STYLE,+ "enum": LEAF_STYLE,+ "scalar": LEAF_STYLE,+}++# The five built-in scalars never become nodes; a schema that references Int+# everywhere would otherwise bury the type graph under one hub.+BUILTIN_SCALARS = {"Int", "Float", "String", "Boolean", "ID"}++KINDS = ("type", "interface", "input", "enum", "union", "scalar")++_DEF = re.compile(+ r"^[ \t]*(?:extend[ \t]+)?(type|interface|input|enum|union|scalar)[ \t]+"+ r"([A-Za-z_][A-Za-z0-9_]*)",+ re.M,+)+_DEPRECATED = re.compile(r"@deprecated\b")+++def strip_ignored(text):+ """Blank out block strings, quoted strings and comments, preserving offsets.++ Every removed character is replaced by a space (newlines kept), so byte+ offsets and therefore line numbers stay correct for the caller.+ """+ out = list(text)+ i, n = 0, len(text)++ def blank(start, end):+ for j in range(start, min(end, n)):+ if out[j] != "\n":+ out[j] = " "++ while i < n:+ ch = text[i]+ if text.startswith('"""', i):+ end = text.find('"""', i + 3)+ end = n if end == -1 else end + 3+ blank(i, end)+ i = end+ elif ch == '"':+ j = i + 1+ while j < n and text[j] != '"':+ j += 2 if text[j] == "\\" else 1+ blank(i, j + 1)+ i = j + 1+ elif ch == "#":+ end = text.find("\n", i)+ end = n if end == -1 else end+ blank(i, end)+ i = end+ else:+ i += 1+ return "".join(out)+++def match_block(text, open_idx):+ """Index just past the brace block that opens at ``open_idx``."""+ depth, i = 0, open_idx+ while i < len(text):+ if text[i] == "{":+ depth += 1+ elif text[i] == "}":+ depth -= 1+ if depth == 0:+ return i + 1+ i += 1+ return len(text)+++def split_fields(body):+ """Split a block body into field-sized chunks on top-level newlines/commas."""+ items, depth, cur = [], 0, []+ for ch in body:+ if ch in "([{":+ depth += 1+ elif ch in ")]}":+ depth -= 1+ if depth == 0 and ch in "\n,":+ items.append("".join(cur))+ cur = []+ else:+ cur.append(ch)+ items.append("".join(cur))+ return items+++def base_type(type_ref):+ """`[Thing!]!` -> `Thing`."""+ return type_ref.replace("[", "").replace("]", "").replace("!", "").strip()+++def parse_field(chunk):+ """A field chunk -> (name, type_ref, deprecated) or None."""+ stripped = chunk.strip()+ if not stripped:+ return None+ m = re.match(r"([A-Za-z_][A-Za-z0-9_]*)\s*", stripped)+ if not m:+ return None+ name = m.group(1)+ rest = stripped[m.end():]+ if rest.startswith("("):+ close = 0+ for idx, ch in enumerate(rest):+ if ch == "(":+ close += 1+ elif ch == ")":+ close -= 1+ if close == 0:+ rest = rest[idx + 1:].lstrip()+ break+ else:+ return None+ if not rest.startswith(":"):+ return None+ type_part = rest[1:].split("@")[0].strip()+ if not type_part:+ return None+ return name, type_part, bool(_DEPRECATED.search(rest))+++def parse_sdl(text, file_path=""):+ """SDL -> list of definition dicts."""+ clean = strip_ignored(text)+ defs = []+ for m in _DEF.finditer(clean):+ kind, name = m.group(1), m.group(2)+ line = clean.count("\n", 0, m.start()) + 1+ entry = {+ "kind": kind,+ "name": name,+ "file": file_path,+ "line": line,+ "fields": [],+ "implements": [],+ "members": [],+ }+ tail = clean[m.end():]+ if kind == "union":+ eq = tail.find("=")+ stop = tail.find("\n\n")+ segment = tail[eq + 1: stop if stop != -1 else len(tail)] if eq != -1 else ""+ # A union body can wrap, but a following definition ends it.+ nxt = re.search(r"^[ \t]*(?:extend[ \t]+)?(?:%s)\b" % "|".join(KINDS),+ segment, re.M)+ if nxt:+ segment = segment[: nxt.start()]+ entry["members"] = [p.strip() for p in segment.split("|") if p.strip()]+ elif kind != "scalar":+ impl = re.match(r"[^\{\n]*", tail).group(0)+ if "implements" in impl:+ after = impl.split("implements", 1)[1].split("@")[0]+ entry["implements"] = [+ p.strip() for p in re.split(r"[&,]", after) if p.strip()+ ]+ brace = tail.find("{")+ if brace != -1:+ end = match_block(clean, m.end() + brace)+ body = clean[m.end() + brace + 1: end - 1]+ body_start = m.end() + brace + 1+ if kind == "enum":+ for chunk in split_fields(body):+ value = chunk.strip().split("@")[0].strip()+ if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", value):+ entry["fields"].append(+ (value, "", bool(_DEPRECATED.search(chunk)))+ )+ else:+ offset = 0+ for chunk in split_fields(body):+ field = parse_field(chunk)+ if field:+ fline = clean.count("\n", 0, body_start + offset) + 1+ entry["fields"].append(field + (fline,))+ offset += len(chunk) + 1+ defs.append(entry)+ return defs+++def parse_introspection(payload, file_path=""):+ """An introspection JSON dump -> the same definition dicts as parse_sdl."""+ schema = payload.get("data", payload).get("__schema")+ if not isinstance(schema, dict):+ raise ValueError("no __schema key found")+ kind_map = {+ "OBJECT": "type",+ "INTERFACE": "interface",+ "INPUT_OBJECT": "input",+ "ENUM": "enum",+ "UNION": "union",+ "SCALAR": "scalar",+ }++ def render(ref):+ if not isinstance(ref, dict):+ return ""+ kind = ref.get("kind")+ if kind == "NON_NULL":+ return render(ref.get("ofType")) + "!"+ if kind == "LIST":+ return "[" + render(ref.get("ofType")) + "]"+ return ref.get("name") or ""++ defs = []+ for t in schema.get("types") or []:+ name = t.get("name") or ""+ kind = kind_map.get(t.get("kind"))+ # An introspection dump always lists the five builtin scalars and the+ # __-prefixed meta types. Neither is part of the schema being drawn.+ if not kind or name.startswith("__") or name in BUILTIN_SCALARS:+ continue+ entry = {+ "kind": kind,+ "name": name,+ "file": file_path,+ "line": 0,+ "fields": [],+ "implements": [i.get("name") for i in (t.get("interfaces") or []) if i.get("name")],+ "members": [u.get("name") for u in (t.get("possibleTypes") or []) if u.get("name")],+ }+ for f in (t.get("fields") or []) + (t.get("inputFields") or []):+ entry["fields"].append(+ (f.get("name") or "", render(f.get("type")), bool(f.get("isDeprecated")), 0)+ )+ for v in t.get("enumValues") or []:+ entry["fields"].append((v.get("name") or "", "", bool(v.get("isDeprecated")), 0))+ defs.append(entry)+ return defs+++def esc(text):+ """Escape HTML metacharacters for draw.io's html=1 labels.++ Without it a field type such as `[Item!]!` renders fine but a description+ containing `<` is swallowed as an unknown HTML tag.+ """+ return (+ text.replace("&", "&")+ .replace("<", "<")+ .replace(">", ">")+ .replace('"', """)+ )+++def compute_dimensions(lines):+ width = max(160, -(-max(7 * len(l) + 30 for l in lines) // 10) * 10)+ height = max(50, -(-(30 + 18 * len(lines)) // 10) * 10)+ return width, height+++def build(defs, group=False, direction="TB", show_types=True):+ """Definition dicts -> autolayout graph JSON."""+ nodes, edges, seen_edges = [], [], set()+ known = {d["name"] for d in defs}++ def add_edge(src, dst, style, label=""):+ key = (src, dst, label)+ if src != dst and dst in known and key not in seen_edges:+ seen_edges.add(key)+ edges.append({"source": src, "target": dst, "style": style, "label": label})++ for d in defs:+ name = d["name"]+ lines = ["«%s»\n%s" % (d["kind"], name) if d["kind"] != "type" else name, "—"]+ if d["kind"] == "union":+ lines.extend(d["members"] or ["(no members)"])+ elif d["kind"] == "scalar":+ lines.append("(custom scalar)")+ elif d["fields"]:+ for field in d["fields"]:+ fname, ftype, deprecated = field[0], field[1], field[2]+ text = fname if not ftype or not show_types else "%s: %s" % (fname, ftype)+ lines.append(text + (" (deprecated)" if deprecated else ""))+ else:+ lines.append("(no fields)")++ width, height = compute_dimensions(lines)+ node = {+ "id": name,+ "label": esc("\n".join(lines)),+ "style": STYLES[d["kind"]],+ "width": width,+ "height": height,+ "provenance": {"path": d["file"], "line": d["line"]},+ }+ if group and d["file"]:+ node["group"] = os.path.splitext(os.path.basename(d["file"]))[0]+ nodes.append(node)++ for iface in d["implements"]:+ add_edge(name, iface, IMPLEMENTS_EDGE, "implements")+ for member in d["members"]:+ add_edge(name, member, MEMBER_EDGE)+ for field in d["fields"]:+ target = base_type(field[1])+ if target and target not in BUILTIN_SCALARS:+ add_edge(name, target, REF_EDGE, field[0])++ return {"direction": direction, "nodes": nodes, "edges": edges}+++def main():+ ap = argparse.ArgumentParser(description="GraphQL SDL -> entity type diagram graph JSON.")+ ap.add_argument("path", help=".graphql/.gql file, a directory, or introspection JSON")+ ap.add_argument("-o", "--output", help="output JSON path (default: stdout)")+ ap.add_argument("--direction", default="TB", choices=["TB", "LR"])+ ap.add_argument("--group", action="store_true",+ help="group types by the schema file they came from")+ ap.add_argument("--no-types", action="store_true",+ help="list field names only (hide the GraphQL types)")+ args = ap.parse_args()++ if os.path.isfile(args.path):+ files = [args.path]+ elif os.path.isdir(args.path):+ files = sorted(+ p for pattern in ("*.graphql", "*.gql")+ for p in glob.glob(os.path.join(args.path, "**", pattern), recursive=True)+ )+ else:+ sys.exit("error: %s not found" % args.path)++ if not files:+ sys.exit("error: no .graphql or .gql files found under %s" % args.path)++ defs = []+ for path in files:+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-python+ with open(path, encoding="utf-8", errors="replace") as fh:+ raw = fh.read()+ if path.endswith(".json"):+ try:+ defs.extend(parse_introspection(json.loads(raw), file_path=path))+ except (ValueError, AttributeError) as exc:+ sys.exit("error: %s is not an introspection dump (%s)" % (path, exc))+ else:+ defs.extend(parse_sdl(raw, file_path=path))++ if not defs:+ sys.exit("error: no GraphQL type definitions found under %s" % args.path)++ graph = build(defs, group=args.group, direction=args.direction,+ show_types=not args.no_types)+ text = json.dumps(graph, indent=2, ensure_ascii=False)+ if args.output:+ # pi-lens-ignore: ast-grep:unchecked-throwing-call-python+ with open(args.output, "w", encoding="utf-8") as fh:+ fh.write(text)+ sys.stderr.write("wrote %s\n" % args.output)+ else:+ sys.stdout.write(text)++ counts = {}+ for d in defs:+ counts[d["kind"]] = counts.get(d["kind"], 0) + 1+ summary = ", ".join("%d %ss" % (counts[k], k) for k in KINDS if k in counts)+ sys.stderr.write("%s, %d edges\n" % (summary, len(graph["edges"])))+++if __name__ == "__main__":+ main()diff --git a/tests/test_graphqlerd.py b/tests/test_graphqlerd.pynew file mode 100644index 0000000..1d63386--- /dev/null+++ b/tests/test_graphqlerd.py@@ -0,0 +1,332 @@+import importlib.util+import json+import os+import subprocess+import sys+import tempfile+import textwrap+import unittest++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+SCRIPT = os.path.join(ROOT, "skills", "drawio-skill", "scripts", "graphqlerd.py")+DIAGRAMCTL = os.path.join(ROOT, "skills", "drawio-skill", "scripts", "diagramctl.py")+sys.path.insert(0, os.path.dirname(DIAGRAMCTL))+++def load_bundled(name):+ """Load a bundled script by path (the scripts directory is not a package)."""+ path = os.path.join(os.path.dirname(DIAGRAMCTL), name + ".py")+ spec = importlib.util.spec_from_file_location(name, path)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++diagramctl = load_bundled("diagramctl")+++def load_importer():+ spec = importlib.util.spec_from_file_location("graphqlerd", SCRIPT)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++SCHEMA = textwrap.dedent(+ '''+ """The node interface."""+ interface Node {+ id: ID!+ }++ """+ A description block whose text is not schema:+ type Ghost {+ boo: String+ }+ """+ # type Phantom { boo: String }+ type Product implements Node & Timestamped @key(fields: "id") {+ id: ID!+ name: String!+ price: Money!+ status: Status+ reviews(first: Int = 10, after: String): [Review!]!+ legacyCode: String @deprecated(reason: "use sku")+ }++ type Review implements Node {+ id: ID!+ author: User+ }++ interface Timestamped {+ createdAt: DateTime!+ }++ type User implements Node {+ id: ID!+ email: String!+ }++ input ProductFilter {+ status: Status+ minPrice: Money+ }++ enum Status {+ DRAFT+ PUBLISHED+ ARCHIVED @deprecated+ }++ union SearchResult = Product | Review | User++ scalar DateTime+ scalar Money+ '''+)+++class TestGraphqlErdParsing(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.importer = load_importer()+ cls.defs = cls.importer.parse_sdl(SCHEMA, file_path="catalog.graphql")+ cls.by_name = {d["name"]: d for d in cls.defs}++ def test_every_definition_kind_is_recognised(self):+ kinds = {}+ for d in self.defs:+ kinds.setdefault(d["kind"], []).append(d["name"])+ self.assertEqual(sorted(kinds["type"]), ["Product", "Review", "User"])+ self.assertEqual(sorted(kinds["interface"]), ["Node", "Timestamped"])+ self.assertEqual(kinds["input"], ["ProductFilter"])+ self.assertEqual(kinds["enum"], ["Status"])+ self.assertEqual(kinds["union"], ["SearchResult"])+ self.assertEqual(sorted(kinds["scalar"]), ["DateTime", "Money"])++ def test_a_definition_inside_a_description_or_comment_is_not_parsed(self):+ # Both decoys start at the beginning of their line, so the definition+ # scan would match them if strip_ignored had not blanked the block+ # string and the comment first.+ self.assertNotIn("Ghost", self.by_name)+ self.assertNotIn("Phantom", self.by_name)++ def test_field_arguments_are_stripped_from_the_type(self):+ fields = dict((f[0], f[1]) for f in self.by_name["Product"]["fields"])+ self.assertEqual(fields["reviews"], "[Review!]!")++ def test_list_and_non_null_wrappers_reduce_to_the_base_type(self):+ self.assertEqual(self.importer.base_type("[Review!]!"), "Review")+ self.assertEqual(self.importer.base_type("String"), "String")++ def test_deprecated_is_marked_on_fields_and_enum_values(self):+ fields = dict((f[0], f[2]) for f in self.by_name["Product"]["fields"])+ self.assertTrue(fields["legacyCode"])+ self.assertFalse(fields["name"])+ values = dict((f[0], f[2]) for f in self.by_name["Status"]["fields"])+ self.assertTrue(values["ARCHIVED"])+ self.assertFalse(values["DRAFT"])++ def test_multiple_interfaces_are_captured(self):+ self.assertEqual(self.by_name["Product"]["implements"], ["Node", "Timestamped"])++ def test_union_members_are_captured(self):+ self.assertEqual(+ self.by_name["SearchResult"]["members"], ["Product", "Review", "User"]+ )++ def test_enum_values_are_read_as_values_not_fields(self):+ self.assertEqual(+ [f[0] for f in self.by_name["Status"]["fields"]],+ ["DRAFT", "PUBLISHED", "ARCHIVED"],+ )++ def test_line_numbers_survive_comment_stripping(self):+ # strip_ignored replaces ignored text with spaces rather than deleting+ # it, so a provenance line still points at the real source line.+ lines = SCHEMA.splitlines()+ for name in ("Product", "Status", "SearchResult"):+ line = self.by_name[name]["line"]+ self.assertIn(name, lines[line - 1])+++class TestGraphqlErdGraph(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.importer = load_importer()+ defs = cls.importer.parse_sdl(SCHEMA, file_path="catalog.graphql")+ cls.graph = cls.importer.build(defs)+ cls.edges = set(+ (e["source"], e["target"], e["label"]) for e in cls.graph["edges"]+ )++ def test_implements_produces_an_edge(self):+ self.assertIn(("Product", "Node", "implements"), self.edges)+ self.assertIn(("Product", "Timestamped", "implements"), self.edges)++ def test_field_reference_produces_an_edge_labelled_with_the_field(self):+ self.assertIn(("Product", "Review", "reviews"), self.edges)+ self.assertIn(("Review", "User", "author"), self.edges)++ def test_union_membership_produces_an_edge(self):+ self.assertIn(("SearchResult", "Product", ""), self.edges)++ def test_builtin_scalars_never_become_nodes_or_edges(self):+ ids = set(n["id"] for n in self.graph["nodes"])+ self.assertFalse(ids & {"ID", "String", "Int", "Float", "Boolean"})+ targets = set(t for _, t, _ in self.edges)+ self.assertFalse(targets & {"ID", "String", "Int", "Float", "Boolean"})++ def test_custom_scalars_do_become_nodes_and_are_dimmed(self):+ by_id = dict((n["id"], n) for n in self.graph["nodes"])+ self.assertIn("Money", by_id)+ self.assertEqual(by_id["Money"]["style"], self.importer.LEAF_STYLE)+ self.assertIn(("Product", "Money", "price"), self.edges)++ def test_enum_nodes_are_dimmed_rather_than_unlinked(self):+ by_id = dict((n["id"], n) for n in self.graph["nodes"])+ self.assertEqual(by_id["Status"]["style"], self.importer.LEAF_STYLE)+ self.assertIn(("Product", "Status", "status"), self.edges)++ def test_every_node_carries_provenance(self):+ for node in self.graph["nodes"]:+ self.assertEqual(node["provenance"]["path"], "catalog.graphql")+ self.assertGreater(node["provenance"]["line"], 0)++ def test_labels_escape_html_metacharacters(self):+ defs = self.importer.parse_sdl("type A { f: B }\ntype B { g: String }")+ graph = self.importer.build(defs)+ for node in graph["nodes"]:+ self.assertNotIn("<", node["label"])++ def test_an_edge_to_an_unknown_type_is_dropped(self):+ defs = self.importer.parse_sdl("type A { missing: Nowhere }")+ self.assertEqual(self.importer.build(defs)["edges"], [])++ def test_no_types_hides_the_field_types(self):+ defs = self.importer.parse_sdl("type A { f: String }")+ graph = self.importer.build(defs, show_types=False)+ self.assertIn("\nf", graph["nodes"][0]["label"])+ self.assertNotIn("String", graph["nodes"][0]["label"])+++class TestGraphqlErdIntrospection(unittest.TestCase):+ PAYLOAD = {+ "data": {+ "__schema": {+ "types": [+ {+ "kind": "OBJECT",+ "name": "Product",+ "interfaces": [{"name": "Node"}],+ "fields": [+ {+ "name": "reviews",+ "type": {+ "kind": "LIST",+ "ofType": {"kind": "OBJECT", "name": "Review"},+ },+ "isDeprecated": False,+ },+ {+ "name": "old",+ "type": {"kind": "SCALAR", "name": "String"},+ "isDeprecated": True,+ },+ ],+ },+ {"kind": "INTERFACE", "name": "Node", "fields": []},+ {"kind": "OBJECT", "name": "Review", "fields": []},+ {"kind": "OBJECT", "name": "__Type", "fields": []},+ ]+ }+ }+ }++ @classmethod+ def setUpClass(cls):+ cls.importer = load_importer()++ def test_introspection_types_map_to_the_same_definitions(self):+ defs = self.importer.parse_introspection(self.PAYLOAD, file_path="i.json")+ self.assertEqual(+ sorted((d["kind"], d["name"]) for d in defs),+ [("interface", "Node"), ("type", "Product"), ("type", "Review")],+ )++ def test_introspection_meta_types_are_skipped(self):+ defs = self.importer.parse_introspection(self.PAYLOAD)+ self.assertNotIn("__Type", [d["name"] for d in defs])++ def test_wrapped_types_are_rendered_back_to_sdl_notation(self):+ defs = self.importer.parse_introspection(self.PAYLOAD)+ product = [d for d in defs if d["name"] == "Product"][0]+ self.assertEqual(product["fields"][0][1], "[Review]")+ self.assertTrue(product["fields"][1][2])++ def test_builtin_scalars_from_an_introspection_dump_are_skipped(self):+ # A real dump always lists String/Int/ID/Boolean/Float as SCALAR types.+ # Keeping them would add five orphan nodes to every introspection run.+ payload = {+ "data": {+ "__schema": {+ "types": [+ {"kind": "SCALAR", "name": n}+ for n in ("String", "Int", "ID", "Boolean", "Float", "DateTime")+ ]+ }+ }+ }+ defs = self.importer.parse_introspection(payload)+ self.assertEqual([d["name"] for d in defs], ["DateTime"])++ def test_a_payload_without_a_schema_key_is_rejected(self):+ with self.assertRaises(ValueError):+ self.importer.parse_introspection({"data": {}})+++class TestGraphqlErdCli(unittest.TestCase):+ def _run(self, *args):+ return subprocess.run(+ [sys.executable, SCRIPT] + list(args),+ capture_output=True,+ text=True,+ check=True,+ )++ def test_directory_scan_groups_by_source_file(self):+ with tempfile.TemporaryDirectory() as d:+ with open(os.path.join(d, "catalog.graphql"), "w", encoding="utf-8") as fh:+ fh.write("type Product { id: ID! }\n")+ with open(os.path.join(d, "billing.gql"), "w", encoding="utf-8") as fh:+ fh.write("type Invoice { product: Product }\n")+ graph = json.loads(self._run(d, "--group").stdout)+ groups = dict((n["id"], n["group"]) for n in graph["nodes"])+ self.assertEqual(groups, {"Product": "catalog", "Invoice": "billing"})+ self.assertEqual(+ [(e["source"], e["target"]) for e in graph["edges"]], [("Invoice", "Product")]+ )++ def test_a_schema_with_no_definitions_exits_nonzero(self):+ with tempfile.TemporaryDirectory() as d:+ path = os.path.join(d, "empty.graphql")+ with open(path, "w", encoding="utf-8") as fh:+ fh.write("# nothing here\n")+ proc = subprocess.run(+ [sys.executable, SCRIPT, path], capture_output=True, text=True+ )+ self.assertNotEqual(proc.returncode, 0)++ def test_detect_source_recognises_a_graphql_directory(self):+ with tempfile.TemporaryDirectory() as d:+ with open(os.path.join(d, "schema.graphql"), "w", encoding="utf-8") as fh:+ fh.write("type Query { ok: Boolean }\n")+ self.assertEqual("graphql", diagramctl.detect_source(d))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex a49bf09..95cc94c 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -1598,6 +1598,29 @@ class TestImportersCli(unittest.TestCase):self.assertEqual(len(graph["edges"]), 2)self.assertEqual({n.get("group") for n in graph["nodes"]}, {"service.v1"})+ def test_graphqlerd_types_interfaces_and_enums(self):+ sdl = (+ "interface Node { id: ID! }\n"+ "type Product implements Node {\n"+ " id: ID!\n"+ " status: Status\n"+ " reviews(first: Int): [Review!]!\n"+ "}\n"+ "type Review { body: String }\n"+ "enum Status { DRAFT PUBLISHED }\n"+ )+ with tempfile.TemporaryDirectory() as d:+ p = os.path.join(d, "catalog.graphql")+ self._write(p, sdl)+ graph = json.loads(run("graphqlerd.py", p, "--group").stdout)+ ids = {n["id"] for n in graph["nodes"]}+ self.assertEqual(ids, {"Node", "Product", "Review", "Status"})+ edges = {(e["source"], e["target"], e["label"]) for e in graph["edges"]}+ self.assertIn(("Product", "Node", "implements"), edges)+ self.assertIn(("Product", "Review", "reviews"), edges)+ self.assertIn(("Product", "Status", "status"), edges)+ self.assertEqual({n.get("group") for n in graph["nodes"]}, {"catalog"})+class TestDrawioHtml(unittest.TestCase):@classmethod