dagward 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +165 -0
- package/dist/cli.js +89 -0
- package/dist/fileGraph.js +0 -0
- package/dist/folderGraph.js +38 -0
- package/dist/functionGraph.js +166 -0
- package/dist/graph.js +88 -0
- package/dist/project.js +37 -0
- package/dist/report.js +168 -0
- package/package.json +30 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# Dagward
|
|
2
|
+
|
|
3
|
+
**Deterministic architecture enforcement for the age of AI coding agents.**
|
|
4
|
+
|
|
5
|
+
> Your dependency graph should be a DAG. Dagward keeps it one — even when AI agents write the code.
|
|
6
|
+
|
|
7
|
+
AI agents write undisciplined code that compounds: more abstractions, more context, slower every session. Dagward enforces your rules deterministically and flips the compounding: cleaner structure, smaller context, faster and cheaper every session.
|
|
8
|
+
|
|
9
|
+
Dagward turns your architecture into something machines must obey:
|
|
10
|
+
|
|
11
|
+
- **Infer** — Scan your repo, get a draft of your actual module boundaries and dependency rules. Confirm instead of writing from scratch.
|
|
12
|
+
- **Enforce** — Every change is checked against the rules: as a Claude Code hook, pre-commit, and in CI. Checks are deterministic graph queries — no AI judging AI.
|
|
13
|
+
- **Feed back** — Violations return structured feedback the agent can act on: which rule, why it exists, how to fix. Agents correct themselves; humans stay out of the loop.
|
|
14
|
+
- **Exempt with intent** — Real architectures have exceptions. Annotated exemptions are versioned in git and become your team's architecture decision record.
|
|
15
|
+
|
|
16
|
+
**AI proposes rules. Humans approve them. Machines enforce them.** No line of code's compliance depends on a model's mood.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Quickstart
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
# 1. Infer your architecture (read-only, ~1 min on most repos)
|
|
24
|
+
npx dagward init
|
|
25
|
+
|
|
26
|
+
# 2. Review the draft — edit dagward.yml, then commit it
|
|
27
|
+
git add dagward.yml && git commit -m "chore: adopt architecture rules"
|
|
28
|
+
|
|
29
|
+
# 3. Check the whole repo
|
|
30
|
+
npx dagward check
|
|
31
|
+
|
|
32
|
+
# 4. Wire it into Claude Code (one command)
|
|
33
|
+
npx dagward install-hook claude-code
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
That's it. From now on, every edit an agent makes is checked against your rules the moment it lands — and violations are fed back to the agent in a format it can act on.
|
|
37
|
+
|
|
38
|
+
Requirements: Node.js ≥ 20, a TypeScript project with a `tsconfig.json`. Monorepos (npm/pnpm/yarn workspaces) are supported.
|
|
39
|
+
|
|
40
|
+
## What `init` produces
|
|
41
|
+
|
|
42
|
+
`dagward init` builds the full dependency graph using the TypeScript compiler API (real module resolution — `paths`, workspace deps, conditional exports), detects strongly connected components and layer structure, and writes two files:
|
|
43
|
+
|
|
44
|
+
- **`ARCHITECTURE.md`** — a human-readable snapshot of your system as it actually is: layers, module boundaries, existing cycles, and the edges that look accidental. Useful on its own, even if you never adopt the rules.
|
|
45
|
+
- **`dagward.yml`** — a draft rule file. Nothing is enforced until you review, edit, and commit it. Confirming is a 10-minute job; writing from scratch would take days.
|
|
46
|
+
|
|
47
|
+
## The rule file
|
|
48
|
+
|
|
49
|
+
Rules are declarative YAML — language-agnostic by design, and readable by both humans and agents. MVP supports three rule types:
|
|
50
|
+
|
|
51
|
+
```yaml
|
|
52
|
+
version: 1
|
|
53
|
+
|
|
54
|
+
layers: # topological order: earlier may not depend on later
|
|
55
|
+
- name: domain
|
|
56
|
+
match: "packages/domain/**"
|
|
57
|
+
- name: application
|
|
58
|
+
match: "packages/app/**"
|
|
59
|
+
- name: infrastructure
|
|
60
|
+
match: "packages/infra/**"
|
|
61
|
+
|
|
62
|
+
rules:
|
|
63
|
+
- id: no-cycles
|
|
64
|
+
type: no-cycles
|
|
65
|
+
level: package # package | file
|
|
66
|
+
rationale: >
|
|
67
|
+
Cycles between packages cause initialization-order bugs and make
|
|
68
|
+
modules impossible to extract or test in isolation.
|
|
69
|
+
|
|
70
|
+
- id: layering
|
|
71
|
+
type: layer-order # enforces the `layers` list above
|
|
72
|
+
ignore-type-imports: true
|
|
73
|
+
rationale: >
|
|
74
|
+
Domain logic must stay framework-free. Dependencies point inward.
|
|
75
|
+
|
|
76
|
+
- id: no-direct-db-from-api
|
|
77
|
+
type: forbidden-edge
|
|
78
|
+
from: "packages/api/**"
|
|
79
|
+
to: "packages/infra/db/**"
|
|
80
|
+
rationale: >
|
|
81
|
+
API handlers go through the repository layer (ADR-012, 2024-06).
|
|
82
|
+
Direct DB access bypassed row-level security once. Never again.
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`rationale` is not a comment — it is part of the enforcement. When an agent violates a rule, the rationale is included in the feedback, so the agent understands *why* and fixes the code instead of fighting the rule.
|
|
86
|
+
|
|
87
|
+
Type-only imports (`import type`) are tracked as a separate edge kind and can be exempted per rule — a type-level cycle is not a runtime cycle, and Dagward knows the difference.
|
|
88
|
+
|
|
89
|
+
## Checking
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
dagward check # full repo
|
|
93
|
+
dagward check --changed # only files changed since HEAD (fast path for hooks)
|
|
94
|
+
dagward check --format agent # structured JSON for agent consumption
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Checks are pure graph queries — cycle detection via strongly connected components, layer rules as reachability queries on the condensation. Deterministic, reproducible, milliseconds on the incremental path. No network calls, no LLM, no flakiness.
|
|
98
|
+
|
|
99
|
+
Exit code `0` = clean, `1` = violations, `2` = config error. That's your CI gate:
|
|
100
|
+
|
|
101
|
+
```yaml
|
|
102
|
+
# .github/workflows/architecture.yml
|
|
103
|
+
- run: npx dagward check --format github
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Agent feedback
|
|
107
|
+
|
|
108
|
+
With `--format agent`, a violation looks like this:
|
|
109
|
+
|
|
110
|
+
```json
|
|
111
|
+
{
|
|
112
|
+
"violations": [{
|
|
113
|
+
"rule": "no-direct-db-from-api",
|
|
114
|
+
"severity": "error",
|
|
115
|
+
"edge": {
|
|
116
|
+
"from": "packages/api/src/checkout.ts",
|
|
117
|
+
"to": "packages/infra/db/client.ts",
|
|
118
|
+
"kind": "value-import"
|
|
119
|
+
},
|
|
120
|
+
"rationale": "API handlers go through the repository layer (ADR-012, 2024-06). Direct DB access bypassed row-level security once. Never again.",
|
|
121
|
+
"fix_direction": "Import from packages/app/repositories instead, or add a repository method if none fits.",
|
|
122
|
+
"exemption_hint": "If this dependency is intentional, add an annotated exemption — see docs/exemptions.md."
|
|
123
|
+
}]
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
The Claude Code hook feeds this back automatically after each edit. In practice, agents fix their own violations on the next turn without human intervention.
|
|
128
|
+
|
|
129
|
+
## Exemptions
|
|
130
|
+
|
|
131
|
+
Real architectures have exceptions. Unexplained exceptions are how architectures rot — so every exemption requires a reason, and lives in git:
|
|
132
|
+
|
|
133
|
+
```yaml
|
|
134
|
+
exemptions:
|
|
135
|
+
- rule: layering
|
|
136
|
+
from: "packages/domain/src/legacy/pricing.ts"
|
|
137
|
+
to: "packages/infra/feature-flags/**"
|
|
138
|
+
reason: "Pre-dates the flag abstraction. Tracked in TICKET-4102."
|
|
139
|
+
added-by: "@yourname"
|
|
140
|
+
added: 2026-07-19
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Over time, your exemption log becomes something no wiki ever stays: an accurate, versioned record of every architectural decision and its debt.
|
|
144
|
+
|
|
145
|
+
## What Dagward is not
|
|
146
|
+
|
|
147
|
+
- **Not a linter.** Linters check code style within a file. Dagward checks the structure between files — the part no single diff reveals and no agent context window retains.
|
|
148
|
+
- **Not an AI reviewer.** Review bots use an LLM to judge LLM output — probabilistic opinions about probabilistic code. Dagward's enforcement is a graph query. Same input, same answer, every time.
|
|
149
|
+
- **Not a replacement for CI, tests, or review.** It is one more deterministic gate — the one specifically shaped for the failure mode AI agents actually have.
|
|
150
|
+
|
|
151
|
+
## Roadmap
|
|
152
|
+
|
|
153
|
+
- **v0.2 — MCP server**: read-only architecture tools (`check_change`, `query_dependencies`, `explain_rule`) so agents can consult the rules *before* writing code, and interactive rule inference inside your agent session.
|
|
154
|
+
- **v0.3 — Cursor hook**, watch mode, richer rule types (public-API surfaces, tag-based boundaries).
|
|
155
|
+
- **Later**: Python analyzer (same rule format, pluggable analyzer), team features (exemption approval flow, drift trends).
|
|
156
|
+
|
|
157
|
+
Multi-language support is a design constraint from day one: the rule format and engine are language-agnostic; only the analyzer is TypeScript-specific.
|
|
158
|
+
|
|
159
|
+
## Status
|
|
160
|
+
|
|
161
|
+
Early. Dagward currently guards its own repository and a handful of production monorepos. Expect sharp edges; expect fast fixes. Issues and violation war stories are equally welcome.
|
|
162
|
+
|
|
163
|
+
## License
|
|
164
|
+
|
|
165
|
+
Apache-2.0. The `Dagward` name and logo are trademarks of the project and are not covered by the code license.
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { parseArgs } from "node:util";
|
|
6
|
+
import { buildFileGraph } from "./fileGraph.js";
|
|
7
|
+
import { buildFolderGraph } from "./folderGraph.js";
|
|
8
|
+
import { buildFunctionGraph } from "./functionGraph.js";
|
|
9
|
+
import { serializeGraph } from "./graph.js";
|
|
10
|
+
import { ConfigError, loadProject } from "./project.js";
|
|
11
|
+
import { renderArchitectureMd } from "./report.js";
|
|
12
|
+
const HELP = `dagward — multi-level dependency graphs for TypeScript projects
|
|
13
|
+
|
|
14
|
+
Usage:
|
|
15
|
+
dagward graph [dir] [options] Analyze the project and write graphs + report
|
|
16
|
+
dagward init [dir] [options] Alias of \`graph\` (rule inference coming later)
|
|
17
|
+
|
|
18
|
+
Options:
|
|
19
|
+
--project <path> Explicit tsconfig.json (default: nearest to [dir])
|
|
20
|
+
--out <dir> Output directory (default: <dir>/dagward-out)
|
|
21
|
+
--help Show this help
|
|
22
|
+
--version Show version
|
|
23
|
+
|
|
24
|
+
Outputs: graph.folders.json, graph.files.json, graph.functions.json, ARCHITECTURE.md
|
|
25
|
+
|
|
26
|
+
Exit codes: 0 ok, 2 config error.`;
|
|
27
|
+
function version() {
|
|
28
|
+
const pkg = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
29
|
+
return pkg.version;
|
|
30
|
+
}
|
|
31
|
+
export function main(argv) {
|
|
32
|
+
const { values, positionals } = parseArgs({
|
|
33
|
+
args: argv,
|
|
34
|
+
options: {
|
|
35
|
+
project: { type: "string" },
|
|
36
|
+
out: { type: "string" },
|
|
37
|
+
help: { type: "boolean" },
|
|
38
|
+
version: { type: "boolean" },
|
|
39
|
+
},
|
|
40
|
+
allowPositionals: true,
|
|
41
|
+
});
|
|
42
|
+
if (values.help) {
|
|
43
|
+
console.log(HELP);
|
|
44
|
+
return 0;
|
|
45
|
+
}
|
|
46
|
+
if (values.version) {
|
|
47
|
+
console.log(version());
|
|
48
|
+
return 0;
|
|
49
|
+
}
|
|
50
|
+
const [command, dirArg] = positionals;
|
|
51
|
+
if (command !== "graph" && command !== "init") {
|
|
52
|
+
console.error(command ? `Unknown command: ${command}` : HELP);
|
|
53
|
+
return command ? 2 : 0;
|
|
54
|
+
}
|
|
55
|
+
if (command === "init") {
|
|
56
|
+
console.error("Note: `init` currently behaves like `graph`; rule inference is coming later.");
|
|
57
|
+
}
|
|
58
|
+
const targetDir = path.resolve(dirArg ?? ".");
|
|
59
|
+
const outDir = path.resolve(values.out ?? path.join(targetDir, "dagward-out"));
|
|
60
|
+
let project;
|
|
61
|
+
try {
|
|
62
|
+
project = loadProject(targetDir, values.project ? path.resolve(values.project) : undefined);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (error instanceof ConfigError) {
|
|
66
|
+
console.error(`Config error: ${error.message}`);
|
|
67
|
+
return 2;
|
|
68
|
+
}
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
console.error(`Analyzing ${project.sourceFiles.length} files (tsconfig at ${project.rootDir})`);
|
|
72
|
+
const { graph: files, skippedDynamicImports } = buildFileGraph(project);
|
|
73
|
+
const folders = buildFolderGraph(files);
|
|
74
|
+
const functions = buildFunctionGraph(project);
|
|
75
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
76
|
+
fs.writeFileSync(path.join(outDir, "graph.folders.json"), serializeGraph(folders));
|
|
77
|
+
fs.writeFileSync(path.join(outDir, "graph.files.json"), serializeGraph(files));
|
|
78
|
+
fs.writeFileSync(path.join(outDir, "graph.functions.json"), serializeGraph(functions));
|
|
79
|
+
fs.writeFileSync(path.join(outDir, "ARCHITECTURE.md"), renderArchitectureMd({ folders, files, functions, skippedDynamicImports, version: version() }));
|
|
80
|
+
for (const graph of [folders, files, functions]) {
|
|
81
|
+
const cycles = graph.cycles.length > 0 ? `${graph.cycles.length} cycle(s)!` : "no cycles";
|
|
82
|
+
console.error(` ${graph.level}: ${graph.nodes.length} nodes, ${graph.edges.length} edges, ${cycles}`);
|
|
83
|
+
}
|
|
84
|
+
console.error(`Wrote 4 files to ${outDir}`);
|
|
85
|
+
return 0;
|
|
86
|
+
}
|
|
87
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
88
|
+
process.exit(main(process.argv.slice(2)));
|
|
89
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { buildGraph } from "./graph.js";
|
|
3
|
+
function folderOf(fileId) {
|
|
4
|
+
const dir = path.posix.dirname(fileId);
|
|
5
|
+
return dir === "" ? "." : dir;
|
|
6
|
+
}
|
|
7
|
+
// Folders are the immediate parent of each file. Ancestor rollups are
|
|
8
|
+
// derivable by consumers from the path hierarchy; emitting every ancestor
|
|
9
|
+
// pair would manufacture phantom cycles at higher levels.
|
|
10
|
+
export function buildFolderGraph(fileGraph) {
|
|
11
|
+
const fileCounts = new Map();
|
|
12
|
+
for (const node of fileGraph.nodes) {
|
|
13
|
+
const folder = folderOf(node.id);
|
|
14
|
+
fileCounts.set(folder, (fileCounts.get(folder) ?? 0) + 1);
|
|
15
|
+
}
|
|
16
|
+
const merged = new Map();
|
|
17
|
+
for (const edge of fileGraph.edges) {
|
|
18
|
+
const from = folderOf(edge.from);
|
|
19
|
+
const to = folderOf(edge.to);
|
|
20
|
+
if (from === to)
|
|
21
|
+
continue;
|
|
22
|
+
// dynamic imports are runtime deps: fold into value at folder level
|
|
23
|
+
const kind = edge.kind === "type" ? "type" : "value";
|
|
24
|
+
const key = `${from} ${to} ${kind}`;
|
|
25
|
+
const existing = merged.get(key);
|
|
26
|
+
if (existing) {
|
|
27
|
+
existing.weight += edge.weight;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
merged.set(key, { from, to, kind, weight: edge.weight });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const nodes = [...fileCounts.entries()].map(([id, fileCount]) => ({
|
|
34
|
+
id,
|
|
35
|
+
fileCount,
|
|
36
|
+
}));
|
|
37
|
+
return buildGraph("folder", fileGraph.root, nodes, [...merged.values()]);
|
|
38
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { buildGraph } from "./graph.js";
|
|
3
|
+
import { relativeId } from "./project.js";
|
|
4
|
+
function className(node) {
|
|
5
|
+
const parent = node.parent;
|
|
6
|
+
if (ts.isClassDeclaration(parent) && parent.name)
|
|
7
|
+
return parent.name.text;
|
|
8
|
+
return undefined; // class expressions: skipped
|
|
9
|
+
}
|
|
10
|
+
function memberName(node) {
|
|
11
|
+
if (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name))
|
|
12
|
+
return node.name.text;
|
|
13
|
+
return undefined; // computed names: skipped
|
|
14
|
+
}
|
|
15
|
+
function collectFunctions(sourceFiles, rootDir) {
|
|
16
|
+
const registry = { fnIds: new Map(), declIds: new Map(), nodes: [] };
|
|
17
|
+
const seenIds = new Set();
|
|
18
|
+
const register = (fnNode, decls, id, sf) => {
|
|
19
|
+
registry.fnIds.set(fnNode, id);
|
|
20
|
+
for (const decl of decls)
|
|
21
|
+
registry.declIds.set(decl, id);
|
|
22
|
+
if (!seenIds.has(id)) {
|
|
23
|
+
seenIds.add(id);
|
|
24
|
+
const file = relativeId(rootDir, sf.fileName);
|
|
25
|
+
const { line } = sf.getLineAndCharacterOfPosition(fnNode.getStart(sf));
|
|
26
|
+
registry.nodes.push({ id, file, line: line + 1 });
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
for (const sf of sourceFiles) {
|
|
30
|
+
const fileId = relativeId(rootDir, sf.fileName);
|
|
31
|
+
const visit = (node) => {
|
|
32
|
+
if (ts.isFunctionDeclaration(node) && node.body) {
|
|
33
|
+
const name = node.name?.text ??
|
|
34
|
+
(node.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)
|
|
35
|
+
? "default"
|
|
36
|
+
: undefined);
|
|
37
|
+
if (name)
|
|
38
|
+
register(node, [node], `${fileId}#${name}`, sf);
|
|
39
|
+
}
|
|
40
|
+
else if (ts.isMethodDeclaration(node) && node.body) {
|
|
41
|
+
const cls = className(node);
|
|
42
|
+
const member = memberName(node);
|
|
43
|
+
if (cls && member)
|
|
44
|
+
register(node, [node], `${fileId}#${cls}.${member}`, sf);
|
|
45
|
+
}
|
|
46
|
+
else if ((ts.isGetAccessor(node) || ts.isSetAccessor(node)) && node.body) {
|
|
47
|
+
const cls = className(node);
|
|
48
|
+
const member = memberName(node);
|
|
49
|
+
if (cls && member)
|
|
50
|
+
register(node, [node], `${fileId}#${cls}.${member}`, sf);
|
|
51
|
+
}
|
|
52
|
+
else if (ts.isConstructorDeclaration(node) && node.body) {
|
|
53
|
+
const cls = className(node);
|
|
54
|
+
// ClassDeclaration mapped too, so `new C()` resolves to the ctor
|
|
55
|
+
if (cls)
|
|
56
|
+
register(node, [node, node.parent], `${fileId}#${cls}.constructor`, sf);
|
|
57
|
+
}
|
|
58
|
+
else if (ts.isVariableDeclaration(node) &&
|
|
59
|
+
ts.isIdentifier(node.name) &&
|
|
60
|
+
node.initializer &&
|
|
61
|
+
(ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer))) {
|
|
62
|
+
register(node.initializer, [node, node.initializer], `${fileId}#${node.name.text}`, sf);
|
|
63
|
+
}
|
|
64
|
+
ts.forEachChild(node, visit);
|
|
65
|
+
};
|
|
66
|
+
visit(sf);
|
|
67
|
+
}
|
|
68
|
+
return registry;
|
|
69
|
+
}
|
|
70
|
+
function isInImportOrExportClause(node) {
|
|
71
|
+
const parent = node.parent;
|
|
72
|
+
return (ts.isImportSpecifier(parent) ||
|
|
73
|
+
ts.isExportSpecifier(parent) ||
|
|
74
|
+
ts.isImportClause(parent) ||
|
|
75
|
+
ts.isNamespaceImport(parent) ||
|
|
76
|
+
ts.isImportEqualsDeclaration(parent));
|
|
77
|
+
}
|
|
78
|
+
// `: Greeter`, `typeof f`, `extends Base` are not function references
|
|
79
|
+
function isInTypePosition(node) {
|
|
80
|
+
const parent = node.parent;
|
|
81
|
+
return (ts.isTypeReferenceNode(parent) ||
|
|
82
|
+
ts.isTypeQueryNode(parent) ||
|
|
83
|
+
ts.isExpressionWithTypeArguments(parent) ||
|
|
84
|
+
ts.isQualifiedName(parent));
|
|
85
|
+
}
|
|
86
|
+
export function buildFunctionGraph(project) {
|
|
87
|
+
const { checker, rootDir, sourceFiles } = project;
|
|
88
|
+
const registry = collectFunctions(sourceFiles, rootDir);
|
|
89
|
+
const merged = new Map();
|
|
90
|
+
const syntheticModuleNodes = new Map();
|
|
91
|
+
const callerOf = (node, fileId) => {
|
|
92
|
+
for (let current = node.parent; current; current = current.parent) {
|
|
93
|
+
const id = registry.fnIds.get(current);
|
|
94
|
+
if (id)
|
|
95
|
+
return id;
|
|
96
|
+
}
|
|
97
|
+
const moduleId = `${fileId}#<module>`;
|
|
98
|
+
if (!syntheticModuleNodes.has(moduleId)) {
|
|
99
|
+
syntheticModuleNodes.set(moduleId, { id: moduleId, file: fileId, line: 1 });
|
|
100
|
+
}
|
|
101
|
+
return moduleId;
|
|
102
|
+
};
|
|
103
|
+
const resolveTarget = (call) => {
|
|
104
|
+
const signatureDecl = checker.getResolvedSignature(call)?.declaration;
|
|
105
|
+
if (signatureDecl) {
|
|
106
|
+
const id = registry.declIds.get(signatureDecl);
|
|
107
|
+
if (id)
|
|
108
|
+
return id;
|
|
109
|
+
}
|
|
110
|
+
let symbol = checker.getSymbolAtLocation(call.expression);
|
|
111
|
+
if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
|
|
112
|
+
symbol = checker.getAliasedSymbol(symbol);
|
|
113
|
+
}
|
|
114
|
+
for (const decl of symbol?.declarations ?? []) {
|
|
115
|
+
const id = registry.declIds.get(decl);
|
|
116
|
+
if (id)
|
|
117
|
+
return id;
|
|
118
|
+
}
|
|
119
|
+
return undefined; // interface methods, node_modules, dynamic dispatch: no edge
|
|
120
|
+
};
|
|
121
|
+
const addEdge = (from, to, kind, sf, at) => {
|
|
122
|
+
const key = `${from} ${to} ${kind}`;
|
|
123
|
+
const existing = merged.get(key);
|
|
124
|
+
if (existing) {
|
|
125
|
+
existing.weight++;
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
const { line } = sf.getLineAndCharacterOfPosition(at.getStart(sf));
|
|
129
|
+
merged.set(key, { from, to, kind, weight: 1, line: line + 1 });
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
for (const sf of sourceFiles) {
|
|
133
|
+
const fileId = relativeId(rootDir, sf.fileName);
|
|
134
|
+
const consumedCallees = new Set();
|
|
135
|
+
const visit = (node) => {
|
|
136
|
+
if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
|
|
137
|
+
consumedCallees.add(node.expression);
|
|
138
|
+
const target = resolveTarget(node);
|
|
139
|
+
if (target)
|
|
140
|
+
addEdge(callerOf(node, fileId), target, "call", sf, node);
|
|
141
|
+
}
|
|
142
|
+
else if (ts.isIdentifier(node) &&
|
|
143
|
+
!consumedCallees.has(node) &&
|
|
144
|
+
node.parent.name !== node &&
|
|
145
|
+
!isInImportOrExportClause(node) &&
|
|
146
|
+
!isInTypePosition(node)) {
|
|
147
|
+
// functions passed as values, e.g. arr.map(fn)
|
|
148
|
+
let symbol = checker.getSymbolAtLocation(node);
|
|
149
|
+
if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
|
|
150
|
+
symbol = checker.getAliasedSymbol(symbol);
|
|
151
|
+
}
|
|
152
|
+
for (const decl of symbol?.declarations ?? []) {
|
|
153
|
+
const id = registry.declIds.get(decl);
|
|
154
|
+
if (id) {
|
|
155
|
+
addEdge(callerOf(node, fileId), id, "reference", sf, node);
|
|
156
|
+
break;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
ts.forEachChild(node, visit);
|
|
161
|
+
};
|
|
162
|
+
visit(sf);
|
|
163
|
+
}
|
|
164
|
+
const nodes = [...registry.nodes, ...syntheticModuleNodes.values()];
|
|
165
|
+
return buildGraph("function", rootDir, nodes, [...merged.values()]);
|
|
166
|
+
}
|
package/dist/graph.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Iterative Tarjan: explicit frames so deep DFS chains on large repos
|
|
2
|
+
// don't overflow the call stack. Returns SCCs as arrays of node ids.
|
|
3
|
+
export function stronglyConnectedComponents(nodeIds, adjacency) {
|
|
4
|
+
const index = new Map();
|
|
5
|
+
const lowlink = new Map();
|
|
6
|
+
const onStack = new Set();
|
|
7
|
+
const stack = [];
|
|
8
|
+
const components = [];
|
|
9
|
+
let counter = 0;
|
|
10
|
+
for (const start of nodeIds) {
|
|
11
|
+
if (index.has(start))
|
|
12
|
+
continue;
|
|
13
|
+
const frames = [{ node: start, cursor: 0 }];
|
|
14
|
+
index.set(start, counter);
|
|
15
|
+
lowlink.set(start, counter);
|
|
16
|
+
counter++;
|
|
17
|
+
stack.push(start);
|
|
18
|
+
onStack.add(start);
|
|
19
|
+
while (frames.length > 0) {
|
|
20
|
+
const frame = frames[frames.length - 1];
|
|
21
|
+
const neighbors = adjacency.get(frame.node) ?? [];
|
|
22
|
+
if (frame.cursor < neighbors.length) {
|
|
23
|
+
const next = neighbors[frame.cursor++];
|
|
24
|
+
if (!index.has(next)) {
|
|
25
|
+
index.set(next, counter);
|
|
26
|
+
lowlink.set(next, counter);
|
|
27
|
+
counter++;
|
|
28
|
+
stack.push(next);
|
|
29
|
+
onStack.add(next);
|
|
30
|
+
frames.push({ node: next, cursor: 0 });
|
|
31
|
+
}
|
|
32
|
+
else if (onStack.has(next)) {
|
|
33
|
+
lowlink.set(frame.node, Math.min(lowlink.get(frame.node), index.get(next)));
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
frames.pop();
|
|
38
|
+
const parent = frames[frames.length - 1];
|
|
39
|
+
if (parent) {
|
|
40
|
+
lowlink.set(parent.node, Math.min(lowlink.get(parent.node), lowlink.get(frame.node)));
|
|
41
|
+
}
|
|
42
|
+
if (lowlink.get(frame.node) === index.get(frame.node)) {
|
|
43
|
+
const component = [];
|
|
44
|
+
let popped;
|
|
45
|
+
do {
|
|
46
|
+
popped = stack.pop();
|
|
47
|
+
onStack.delete(popped);
|
|
48
|
+
component.push(popped);
|
|
49
|
+
} while (popped !== frame.node);
|
|
50
|
+
components.push(component.sort());
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return components;
|
|
56
|
+
}
|
|
57
|
+
// A component is a cycle if it has >1 node, or a single node with a self-edge.
|
|
58
|
+
export function findCycles(nodes, edges) {
|
|
59
|
+
const adjacency = new Map();
|
|
60
|
+
for (const edge of edges) {
|
|
61
|
+
let targets = adjacency.get(edge.from);
|
|
62
|
+
if (!targets)
|
|
63
|
+
adjacency.set(edge.from, (targets = []));
|
|
64
|
+
targets.push(edge.to);
|
|
65
|
+
}
|
|
66
|
+
const selfLoops = new Set(edges.filter((e) => e.from === e.to).map((e) => e.from));
|
|
67
|
+
const components = stronglyConnectedComponents(nodes.map((n) => n.id), adjacency);
|
|
68
|
+
return components
|
|
69
|
+
.filter((c) => c.length > 1 || selfLoops.has(c[0]))
|
|
70
|
+
.sort((a, b) => b.length - a.length || a[0].localeCompare(b[0]))
|
|
71
|
+
.map((c, i) => ({ id: i, nodes: c }));
|
|
72
|
+
}
|
|
73
|
+
// Sorted nodes/edges, no timestamps: output is diffable and deep-comparable.
|
|
74
|
+
export function buildGraph(level, root, nodes, edges) {
|
|
75
|
+
const sortedNodes = [...nodes].sort((a, b) => a.id.localeCompare(b.id));
|
|
76
|
+
const sortedEdges = [...edges].sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to) || a.kind.localeCompare(b.kind));
|
|
77
|
+
return {
|
|
78
|
+
version: 1,
|
|
79
|
+
level,
|
|
80
|
+
root,
|
|
81
|
+
nodes: sortedNodes,
|
|
82
|
+
edges: sortedEdges,
|
|
83
|
+
cycles: findCycles(sortedNodes, sortedEdges),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
export function serializeGraph(graph) {
|
|
87
|
+
return JSON.stringify(graph, null, 2) + "\n";
|
|
88
|
+
}
|
package/dist/project.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import ts from "typescript";
|
|
3
|
+
export class ConfigError extends Error {
|
|
4
|
+
}
|
|
5
|
+
export function relativeId(rootDir, fileName) {
|
|
6
|
+
return path.relative(rootDir, fileName).split(path.sep).join("/");
|
|
7
|
+
}
|
|
8
|
+
export function loadProject(searchDir, explicitConfig) {
|
|
9
|
+
const configPath = explicitConfig ?? ts.findConfigFile(searchDir, ts.sys.fileExists, "tsconfig.json");
|
|
10
|
+
if (!configPath || !ts.sys.fileExists(configPath)) {
|
|
11
|
+
throw new ConfigError(`No tsconfig.json found from ${searchDir}`);
|
|
12
|
+
}
|
|
13
|
+
const host = {
|
|
14
|
+
...ts.sys,
|
|
15
|
+
onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
|
|
16
|
+
throw new ConfigError(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
const parsed = ts.getParsedCommandLineOfConfigFile(configPath, undefined, host);
|
|
20
|
+
if (!parsed)
|
|
21
|
+
throw new ConfigError(`Failed to parse ${configPath}`);
|
|
22
|
+
const program = ts.createProgram({
|
|
23
|
+
rootNames: parsed.fileNames,
|
|
24
|
+
options: parsed.options,
|
|
25
|
+
projectReferences: parsed.projectReferences,
|
|
26
|
+
});
|
|
27
|
+
const sourceFiles = program
|
|
28
|
+
.getSourceFiles()
|
|
29
|
+
.filter((sf) => !sf.isDeclarationFile && !program.isSourceFileFromExternalLibrary(sf));
|
|
30
|
+
return {
|
|
31
|
+
program,
|
|
32
|
+
checker: program.getTypeChecker(),
|
|
33
|
+
options: parsed.options,
|
|
34
|
+
rootDir: path.dirname(configPath),
|
|
35
|
+
sourceFiles,
|
|
36
|
+
};
|
|
37
|
+
}
|
package/dist/report.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { stronglyConnectedComponents } from "./graph.js";
|
|
2
|
+
// Layer depth on the condensation of the folder graph: layer 0 depends on
|
|
3
|
+
// nothing; layer N depends only on layers < N. Cyclic groups share a depth.
|
|
4
|
+
function folderLayers(folders) {
|
|
5
|
+
const sccs = stronglyConnectedComponents(folders.nodes.map((n) => n.id), edgesToAdjacency(folders));
|
|
6
|
+
const componentOf = new Map();
|
|
7
|
+
sccs.forEach((scc, i) => scc.forEach((id) => componentOf.set(id, i)));
|
|
8
|
+
const deps = new Map(sccs.map((_, i) => [i, new Set()]));
|
|
9
|
+
for (const edge of folders.edges) {
|
|
10
|
+
const from = componentOf.get(edge.from);
|
|
11
|
+
const to = componentOf.get(edge.to);
|
|
12
|
+
if (from !== to)
|
|
13
|
+
deps.get(from).add(to);
|
|
14
|
+
}
|
|
15
|
+
const depth = new Map();
|
|
16
|
+
const resolve = (component) => {
|
|
17
|
+
const known = depth.get(component);
|
|
18
|
+
if (known !== undefined)
|
|
19
|
+
return known;
|
|
20
|
+
let d = 0;
|
|
21
|
+
for (const dep of deps.get(component))
|
|
22
|
+
d = Math.max(d, resolve(dep) + 1);
|
|
23
|
+
depth.set(component, d);
|
|
24
|
+
return d;
|
|
25
|
+
};
|
|
26
|
+
const layers = new Map();
|
|
27
|
+
sccs.forEach((scc, i) => {
|
|
28
|
+
const d = resolve(i);
|
|
29
|
+
if (!layers.has(d))
|
|
30
|
+
layers.set(d, []);
|
|
31
|
+
layers.get(d).push(...scc);
|
|
32
|
+
});
|
|
33
|
+
for (const members of layers.values())
|
|
34
|
+
members.sort();
|
|
35
|
+
return layers;
|
|
36
|
+
}
|
|
37
|
+
function edgesToAdjacency(graph) {
|
|
38
|
+
const adjacency = new Map();
|
|
39
|
+
for (const edge of graph.edges) {
|
|
40
|
+
if (!adjacency.has(edge.from))
|
|
41
|
+
adjacency.set(edge.from, []);
|
|
42
|
+
adjacency.get(edge.from).push(edge.to);
|
|
43
|
+
}
|
|
44
|
+
return adjacency;
|
|
45
|
+
}
|
|
46
|
+
function fanCounts(graph) {
|
|
47
|
+
const counts = new Map();
|
|
48
|
+
const entry = (id) => {
|
|
49
|
+
if (!counts.has(id))
|
|
50
|
+
counts.set(id, { fanIn: 0, fanOut: 0 });
|
|
51
|
+
return counts.get(id);
|
|
52
|
+
};
|
|
53
|
+
for (const node of graph.nodes)
|
|
54
|
+
entry(node.id);
|
|
55
|
+
for (const edge of graph.edges) {
|
|
56
|
+
entry(edge.from).fanOut++;
|
|
57
|
+
entry(edge.to).fanIn++;
|
|
58
|
+
}
|
|
59
|
+
return counts;
|
|
60
|
+
}
|
|
61
|
+
function cyclesSection(lines, graph, label, cap) {
|
|
62
|
+
if (graph.cycles.length === 0)
|
|
63
|
+
return;
|
|
64
|
+
const shown = cap ? graph.cycles.slice(0, cap) : graph.cycles;
|
|
65
|
+
lines.push(`### ${label} cycles (${graph.cycles.length})`, "");
|
|
66
|
+
for (const cycle of shown) {
|
|
67
|
+
lines.push(`- **Cycle ${cycle.id}** (${cycle.nodes.length} nodes): ${cycle.nodes.join(" ⇄ ")}`);
|
|
68
|
+
if (graph.level === "file") {
|
|
69
|
+
const members = new Set(cycle.nodes);
|
|
70
|
+
for (const edge of graph.edges) {
|
|
71
|
+
if (members.has(edge.from) && members.has(edge.to) && edge.from !== edge.to) {
|
|
72
|
+
lines.push(` - \`${edge.from}:${edge.line ?? "?"}\` → \`${edge.to}\` (${edge.kind})`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (cap && graph.cycles.length > cap) {
|
|
78
|
+
lines.push(`- … ${graph.cycles.length - cap} more (see JSON output)`);
|
|
79
|
+
}
|
|
80
|
+
lines.push("");
|
|
81
|
+
}
|
|
82
|
+
export function renderArchitectureMd(input) {
|
|
83
|
+
const { folders, files, functions } = input;
|
|
84
|
+
const lines = [];
|
|
85
|
+
lines.push("# Architecture Review", "");
|
|
86
|
+
lines.push(`Project root: \`${folders.root}\``, "");
|
|
87
|
+
lines.push("| Level | Nodes | Edges | Cycles |");
|
|
88
|
+
lines.push("|---|---:|---:|---:|");
|
|
89
|
+
for (const graph of [folders, files, functions]) {
|
|
90
|
+
lines.push(`| ${graph.level} | ${graph.nodes.length} | ${graph.edges.length} | ${graph.cycles.length} |`);
|
|
91
|
+
}
|
|
92
|
+
lines.push("");
|
|
93
|
+
lines.push("## Folder layering", "");
|
|
94
|
+
lines.push("Layer 0 depends on nothing; each layer depends only on lower layers.", "Folders in a cycle share a layer.", "");
|
|
95
|
+
const fans = fanCounts(folders);
|
|
96
|
+
const fileCount = new Map(folders.nodes.map((n) => [n.id, n.fileCount ?? 0]));
|
|
97
|
+
lines.push("| Layer | Folder | Files | Fan-in | Fan-out |");
|
|
98
|
+
lines.push("|---:|---|---:|---:|---:|");
|
|
99
|
+
const layers = folderLayers(folders);
|
|
100
|
+
for (const depth of [...layers.keys()].sort((a, b) => a - b)) {
|
|
101
|
+
for (const folder of layers.get(depth)) {
|
|
102
|
+
const fan = fans.get(folder);
|
|
103
|
+
lines.push(`| ${depth} | \`${folder}\` | ${fileCount.get(folder)} | ${fan.fanIn} | ${fan.fanOut} |`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
lines.push("");
|
|
107
|
+
const anyCycles = folders.cycles.length + files.cycles.length + functions.cycles.length > 0;
|
|
108
|
+
lines.push("## Cycles", "");
|
|
109
|
+
if (anyCycles) {
|
|
110
|
+
cyclesSection(lines, folders, "Folder");
|
|
111
|
+
cyclesSection(lines, files, "File");
|
|
112
|
+
cyclesSection(lines, functions, "Function", 20);
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
lines.push("None found at any level. Your dependency graph is a DAG. 🎉", "");
|
|
116
|
+
}
|
|
117
|
+
lines.push("## Notable edges", "");
|
|
118
|
+
const heaviest = [...folders.edges].sort((a, b) => b.weight - a.weight).slice(0, 10);
|
|
119
|
+
if (heaviest.length > 0) {
|
|
120
|
+
lines.push("### Heaviest cross-folder dependencies", "");
|
|
121
|
+
lines.push("| From | To | Kind | File edges |");
|
|
122
|
+
lines.push("|---|---|---|---:|");
|
|
123
|
+
for (const edge of heaviest) {
|
|
124
|
+
lines.push(`| \`${edge.from}\` | \`${edge.to}\` | ${edge.kind} | ${edge.weight} |`);
|
|
125
|
+
}
|
|
126
|
+
lines.push("");
|
|
127
|
+
}
|
|
128
|
+
const fileFans = fanCounts(files);
|
|
129
|
+
const hubs = [...fileFans.entries()]
|
|
130
|
+
.filter(([, fan]) => fan.fanIn > 0)
|
|
131
|
+
.sort((a, b) => b[1].fanIn - a[1].fanIn)
|
|
132
|
+
.slice(0, 10);
|
|
133
|
+
if (hubs.length > 0) {
|
|
134
|
+
lines.push("### Most depended-on files (hubs)", "");
|
|
135
|
+
lines.push("| File | Fan-in | Fan-out |");
|
|
136
|
+
lines.push("|---|---:|---:|");
|
|
137
|
+
for (const [id, fan] of hubs) {
|
|
138
|
+
lines.push(`| \`${id}\` | ${fan.fanIn} | ${fan.fanOut} |`);
|
|
139
|
+
}
|
|
140
|
+
lines.push("");
|
|
141
|
+
}
|
|
142
|
+
const pairKinds = new Map();
|
|
143
|
+
for (const edge of folders.edges) {
|
|
144
|
+
const key = `${edge.from} → ${edge.to}`;
|
|
145
|
+
if (!pairKinds.has(key))
|
|
146
|
+
pairKinds.set(key, new Set());
|
|
147
|
+
pairKinds.get(key).add(edge.kind);
|
|
148
|
+
}
|
|
149
|
+
const typeOnlyPairs = [...pairKinds.entries()]
|
|
150
|
+
.filter(([, kinds]) => kinds.size === 1 && kinds.has("type"))
|
|
151
|
+
.map(([pair]) => pair)
|
|
152
|
+
.slice(0, 10);
|
|
153
|
+
if (typeOnlyPairs.length > 0) {
|
|
154
|
+
lines.push("### Folder pairs connected only by type imports", "");
|
|
155
|
+
lines.push("These couplings vanish at runtime — candidates for clean decoupling.", "");
|
|
156
|
+
for (const pair of typeOnlyPairs)
|
|
157
|
+
lines.push(`- \`${pair}\``);
|
|
158
|
+
lines.push("");
|
|
159
|
+
}
|
|
160
|
+
if (input.skippedDynamicImports > 0) {
|
|
161
|
+
lines.push(`> Note: ${input.skippedDynamicImports} dynamic import(s) with non-literal specifiers ` +
|
|
162
|
+
"could not be resolved and are not in the graph.", "");
|
|
163
|
+
}
|
|
164
|
+
lines.push("---", "");
|
|
165
|
+
lines.push(`Generated by dagward v${input.version}. Machine-readable graphs: ` +
|
|
166
|
+
"`graph.folders.json`, `graph.files.json`, `graph.functions.json`.");
|
|
167
|
+
return lines.join("\n") + "\n";
|
|
168
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "dagward",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Deterministic architecture review for TypeScript projects: dependency graphs at folder, file, and function level.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/kanglei1130/dagward.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/kanglei1130/dagward#readme",
|
|
11
|
+
"bugs": "https://github.com/kanglei1130/dagward/issues",
|
|
12
|
+
"keywords": ["architecture", "dependency-graph", "dag", "typescript", "lint", "ai-agents"],
|
|
13
|
+
"type": "module",
|
|
14
|
+
"engines": { "node": ">=20" },
|
|
15
|
+
"bin": { "dagward": "dist/cli.js" },
|
|
16
|
+
"files": ["dist"],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc -p tsconfig.json",
|
|
19
|
+
"prepare": "npm run build",
|
|
20
|
+
"test": "vitest run",
|
|
21
|
+
"prepublishOnly": "npm run build && npm test"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"typescript": "^5.5.0"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@types/node": "^20.0.0",
|
|
28
|
+
"vitest": "^2.0.0"
|
|
29
|
+
}
|
|
30
|
+
}
|