@krizaka/architecture 0.0.0-stage → 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 +42 -2
- package/package.json +53 -3
- package/src/c4.mjs +185 -0
- package/src/cli.mjs +40 -0
- package/src/files.mjs +87 -0
- package/src/imports.mjs +42 -0
- package/src/index.d.ts +38 -0
- package/src/index.mjs +2 -0
- package/src/order.mjs +5 -0
- package/src/scan.mjs +71 -0
- package/src/text.mjs +25 -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
CHANGED
|
@@ -1,3 +1,43 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @krizaka/architecture
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The C4 view of a repository, **generated from its code** (krizaka/.github#355, first slice; ADR-013: one source per rule set).
|
|
4
|
+
Dependency-free (Node built-ins), it runs on a local checkout and gives the same output wherever it runs, so the docs, krizaka.com and
|
|
5
|
+
the founder cockpit all show the architecture of the code, not of what is deployed.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx krizaka-architecture ../my-repo --out c4.json # the three levels
|
|
9
|
+
npx krizaka-architecture ../my-repo --level containers # one level, { level, nodes, edges }, on stdout
|
|
10
|
+
npx krizaka-architecture ../my-repo --out c4.json --text c4.md # plus the text version
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```js
|
|
14
|
+
import { buildC4, toText } from "@krizaka/architecture";
|
|
15
|
+
const c4 = buildC4("/path/to/checkout"); // { schema: "krizaka.c4/1", repo, levels: { context, containers, components } }
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## What is read
|
|
19
|
+
|
|
20
|
+
| Level | Nodes | Edges |
|
|
21
|
+
| :--- | :--- | :--- |
|
|
22
|
+
| `context` | the system (the repo) and what it reaches: external services, Krizaka libraries | system `reads` an external service, `uses` the libraries |
|
|
23
|
+
| `containers` | npm/yarn `workspaces` and `pnpm-workspace.yaml` packages (`app` or `library`; a Next.js, Expo, Vite, Express, Fastify or Hono dependency, or `apps/`, makes an app), Maven `<module>`s, or the root package alone | container `uses` another (a declared dependency or an import) and `reads` an external service |
|
|
24
|
+
| `components` | the first folder under `src/` (or the container root) of each container; `root` for loose files | component `imports` component (relative and `@/` imports), `uses` a container, `reads` an external service |
|
|
25
|
+
|
|
26
|
+
External services come from the **env declarations** (`lib/env.ts`, `env.ts`, `.env.example`) and `process.env.X` reads, by the org contexts
|
|
27
|
+
(`DATABASE_`, `AUTH_`, `MEDIA_`, `MAIL_`, `PUSH_`, `PAYMENTS_`, `REALTIME_`, `ABUSE_`, `OBSERVABILITY_`, `AI_`): a vendor is a value, so it never
|
|
28
|
+
appears (`MAIL_PROVIDER=mailgun` is « Mail provider »). `APP_` and `OPERATOR_` are the app's own settings, not external services.
|
|
29
|
+
|
|
30
|
+
Every node lists the **files behind it** (repo-relative, capped at 200, `fileCount` is the true number) and every edge the files that
|
|
31
|
+
cause it (capped at 20). Tests, stories, `node_modules`, `dist`, `.next`, `target` are left out. The output is deterministic (sorted, no date):
|
|
32
|
+
a diff of two runs is a diff of the architecture.
|
|
33
|
+
|
|
34
|
+
## Calling it from the cockpit (local, private)
|
|
35
|
+
|
|
36
|
+
The founder cockpit runs it per repo on the Mac and reads `{ nodes, edges, level }`:
|
|
37
|
+
|
|
38
|
+
```js
|
|
39
|
+
import { execFileSync } from "node:child_process";
|
|
40
|
+
const level = JSON.parse(execFileSync("npx", ["--yes", "@krizaka/architecture", repoPath, "--level", "containers"], { encoding: "utf8" }));
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Not in this package yet: SonarQube Architecture (intended architecture and deviations), and rendering on krizaka.com / the docs.
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@krizaka/architecture",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The C4 view of a repository, generated from its code: containers from the workspaces, components from the folders, the imports between them, the external services from the env declarations. Dependency-free, runs on a local checkout, writes JSON and a text version.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"krizaka",
|
|
7
|
+
"c4",
|
|
8
|
+
"architecture",
|
|
9
|
+
"dependencies"
|
|
10
|
+
],
|
|
11
|
+
"homepage": "https://ts.krizaka.com/architecture",
|
|
12
|
+
"bugs": "https://github.com/krizaka/krizaka-ts/issues",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/krizaka/krizaka-ts.git",
|
|
16
|
+
"directory": "packages/architecture"
|
|
17
|
+
},
|
|
18
|
+
"license": "Apache-2.0",
|
|
19
|
+
"author": "Krizaka (https://www.krizaka.com)",
|
|
20
|
+
"type": "module",
|
|
21
|
+
"main": "./src/index.mjs",
|
|
22
|
+
"types": "./src/index.d.ts",
|
|
23
|
+
"bin": {
|
|
24
|
+
"krizaka-architecture": "./src/cli.mjs"
|
|
25
|
+
},
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./src/index.d.ts",
|
|
29
|
+
"import": "./src/index.mjs"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"src",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"sideEffects": false,
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@types/node": "^22.10.0",
|
|
41
|
+
"eslint": "^9.39.0",
|
|
42
|
+
"@krizaka/config": "^0.14.0"
|
|
43
|
+
},
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=22"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"lint": "eslint . --max-warnings 0",
|
|
52
|
+
"typecheck": "node --check src/index.mjs",
|
|
53
|
+
"test": "node --test",
|
|
54
|
+
"check": "pnpm run lint && pnpm run test"
|
|
55
|
+
}
|
|
6
56
|
}
|
package/src/c4.mjs
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// The three C4 levels (context, containers, components) from the facts of a checkout: `{ level, nodes, edges }` each.
|
|
2
|
+
import { contextOf } from "./imports.mjs";
|
|
3
|
+
import { asc } from "./order.mjs";
|
|
4
|
+
import { componentOf, containerOfPath, scan } from "./scan.mjs";
|
|
5
|
+
|
|
6
|
+
export const SCHEMA = "krizaka.c4/1";
|
|
7
|
+
const FILE_CAP = 200;
|
|
8
|
+
const EDGE_FILE_CAP = 20;
|
|
9
|
+
const EXTERNALS = {
|
|
10
|
+
DATABASE: "Database",
|
|
11
|
+
AUTH: "Identity provider",
|
|
12
|
+
MEDIA: "Media storage and CDN",
|
|
13
|
+
MAIL: "Mail provider",
|
|
14
|
+
PUSH: "Push notifications",
|
|
15
|
+
PAYMENTS: "Payments provider",
|
|
16
|
+
REALTIME: "Realtime service",
|
|
17
|
+
ABUSE: "Abuse protection",
|
|
18
|
+
OBSERVABILITY: "Observability",
|
|
19
|
+
AI: "AI provider",
|
|
20
|
+
};
|
|
21
|
+
const LIBRARIES = "external:krizaka-libraries";
|
|
22
|
+
const byId = (a, b) => asc(a.id, b.id);
|
|
23
|
+
|
|
24
|
+
const node = (id, level, kind, name, extra = {}) => {
|
|
25
|
+
const files = [...new Set(extra.files ?? [])].sort(asc);
|
|
26
|
+
return { id, level, kind, name, description: extra.description ?? "", technology: extra.technology, files: files.slice(0, FILE_CAP), fileCount: extra.fileCount ?? files.length };
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** Edges merged by (from, to, label): the number of files behind it and the first of them. */
|
|
30
|
+
class Edges {
|
|
31
|
+
#map = new Map();
|
|
32
|
+
add(from, to, label, files) {
|
|
33
|
+
const key = `${from}|${to}|${label}`;
|
|
34
|
+
const edge = this.#map.get(key) ?? { from, to, label, count: 0, files: [] };
|
|
35
|
+
edge.count += files.length;
|
|
36
|
+
edge.files = [...new Set([...edge.files, ...files])].sort(asc).slice(0, EDGE_FILE_CAP);
|
|
37
|
+
this.#map.set(key, edge);
|
|
38
|
+
}
|
|
39
|
+
list() {
|
|
40
|
+
return [...this.#map.values()].sort((a, b) => `${a.from}|${a.to}|${a.label}`.localeCompare(`${b.from}|${b.to}|${b.label}`));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const containerId = (c) => `container:${c.name}`;
|
|
45
|
+
const componentId = (c, name) => `component:${c.name}/${name}`;
|
|
46
|
+
const externalId = (ctx) => `external:${ctx.toLowerCase()}`;
|
|
47
|
+
|
|
48
|
+
/** Env names by external context, with the declaring files, per container dir: `Map<dir, Map<context, { names, files }>>`. */
|
|
49
|
+
function putUse(use, dir, name, path) {
|
|
50
|
+
const ctx = contextOf(name);
|
|
51
|
+
if (!EXTERNALS[ctx]) return;
|
|
52
|
+
const byCtx = use.get(dir) ?? new Map();
|
|
53
|
+
const entry = byCtx.get(ctx) ?? { names: new Set(), files: new Set() };
|
|
54
|
+
entry.names.add(name);
|
|
55
|
+
entry.files.add(path);
|
|
56
|
+
byCtx.set(ctx, entry);
|
|
57
|
+
use.set(dir, byCtx);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function envUse(facts) {
|
|
61
|
+
const use = new Map();
|
|
62
|
+
for (const d of facts.declarations) d.names.forEach((n) => putUse(use, d.container, n, d.path));
|
|
63
|
+
for (const f of facts.files) f.envs.forEach((n) => putUse(use, f.container, n, f.path));
|
|
64
|
+
return use;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const externalNodes = (use) => {
|
|
68
|
+
const agg = new Map();
|
|
69
|
+
for (const byCtx of use.values()) {
|
|
70
|
+
for (const [ctx, { names, files }] of byCtx) {
|
|
71
|
+
const entry = agg.get(ctx) ?? { names: new Set(), files: new Set() };
|
|
72
|
+
names.forEach((n) => entry.names.add(n));
|
|
73
|
+
files.forEach((f) => entry.files.add(f));
|
|
74
|
+
agg.set(ctx, entry);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return [...agg].map(([ctx, { names, files }]) => node(externalId(ctx), "external", "external", EXTERNALS[ctx], { description: `Configured by ${[...names].sort(asc).join(", ")}`, files }));
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const workspaceByName = (containers) => new Map(containers.map((c) => [c.name, c]));
|
|
81
|
+
const isLibrary = (name, byName) => name.startsWith("@krizaka/") && !byName.has(name);
|
|
82
|
+
|
|
83
|
+
/** The workspace containers a file imports by package name, with the container the file belongs to. */
|
|
84
|
+
function importedContainers(facts, byName, file) {
|
|
85
|
+
const from = facts.containers.find((c) => c.dir === file.container);
|
|
86
|
+
return file.imports
|
|
87
|
+
.filter((i) => i.kind === "package" && byName.has(i.name) && i.name !== from.name)
|
|
88
|
+
.map((i) => ({ from, target: byName.get(i.name) }));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Container -> container edges (declared dependency or import) and container -> library/external edges. */
|
|
92
|
+
function containerEdges(facts, use) {
|
|
93
|
+
const edges = new Edges();
|
|
94
|
+
const byName = workspaceByName(facts.containers);
|
|
95
|
+
for (const c of facts.containers) {
|
|
96
|
+
for (const dep of c.deps) {
|
|
97
|
+
if (byName.has(dep) && dep !== c.name) edges.add(containerId(c), containerId(byName.get(dep)), "uses", [c.manifest]);
|
|
98
|
+
else if (isLibrary(dep, byName)) edges.add(containerId(c), LIBRARIES, "uses", [c.manifest]);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
for (const f of facts.files) importedContainers(facts, byName, f).forEach((to) => edges.add(containerId(to.from), containerId(to.target), "uses", [f.path]));
|
|
102
|
+
for (const [dir, byCtx] of use) {
|
|
103
|
+
const from = facts.containers.find((c) => c.dir === dir);
|
|
104
|
+
for (const [ctx, { files }] of byCtx) edges.add(containerId(from), externalId(ctx), "reads", [...files]);
|
|
105
|
+
}
|
|
106
|
+
return edges;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const libraryNode = (facts) => {
|
|
110
|
+
const byName = workspaceByName(facts.containers);
|
|
111
|
+
const used = new Set([...facts.containers.flatMap((c) => c.deps), ...facts.files.flatMap((f) => f.imports.filter((i) => i.kind === "package").map((i) => i.name))].filter((n) => isLibrary(n, byName)));
|
|
112
|
+
return used.size ? [node(LIBRARIES, "external", "external", "Krizaka libraries", { description: [...used].sort(asc).join(", ") })] : [];
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const containerNodes = (facts) => facts.containers.map((c) => {
|
|
116
|
+
const own = facts.files.filter((f) => f.container === c.dir).map((f) => f.path);
|
|
117
|
+
return node(containerId(c), "container", c.kind, c.name, { description: c.description, technology: c.technology, files: [c.manifest, ...own], fileCount: own.length + 1 });
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
const containerLevel = (facts, use) => {
|
|
121
|
+
const used = new Set([...use.values()].flatMap((m) => [...m.keys()]));
|
|
122
|
+
const externals = externalNodes(use).filter((n) => used.has(n.id.slice("external:".length).toUpperCase()));
|
|
123
|
+
return { level: "containers", nodes: [...containerNodes(facts), ...externals, ...libraryNode(facts)].sort(byId), edges: containerEdges(facts, use).list() };
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const contextLevel = (facts, use, containers) => {
|
|
127
|
+
const system = node(`system:${facts.repo}`, "system", "system", facts.repo, { description: `${facts.containers.length} container(s)`, files: facts.containers.map((c) => c.manifest) });
|
|
128
|
+
const edges = new Edges();
|
|
129
|
+
for (const e of containers.edges.filter((x) => x.to.startsWith("external:"))) edges.add(system.id, e.to, e.label, e.files);
|
|
130
|
+
const externals = containers.nodes.filter((n) => n.level === "external");
|
|
131
|
+
return { level: "context", nodes: [system, ...externals].sort(byId), edges: edges.list() };
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const componentNodes = (facts) => {
|
|
135
|
+
const groups = new Map();
|
|
136
|
+
for (const f of facts.files) {
|
|
137
|
+
const c = facts.containers.find((x) => x.dir === f.container);
|
|
138
|
+
const id = componentId(c, f.component);
|
|
139
|
+
const g = groups.get(id) ?? { c, name: f.component, files: [] };
|
|
140
|
+
g.files.push(f.path);
|
|
141
|
+
groups.set(id, g);
|
|
142
|
+
}
|
|
143
|
+
return [...groups].map(([id, g]) => node(id, "component", "component", g.name, { description: g.c.name, technology: g.c.technology, files: g.files }));
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/** The edge one import of a file draws from its component: to another container, or to another component of the same one. */
|
|
147
|
+
function importEdge(facts, byName, c, from, imp) {
|
|
148
|
+
if (imp.kind === "package") {
|
|
149
|
+
return byName.has(imp.name) && imp.name !== c.name ? [from, containerId(byName.get(imp.name)), "uses"] : undefined;
|
|
150
|
+
}
|
|
151
|
+
const target = containerOfPath(facts.containers, imp.target);
|
|
152
|
+
if (target?.dir !== c.dir) return undefined;
|
|
153
|
+
const to = componentId(c, componentOf(c, imp.target));
|
|
154
|
+
return to === from ? undefined : [from, to, "imports"];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function componentEdges(facts, use) {
|
|
158
|
+
const edges = new Edges();
|
|
159
|
+
const byName = workspaceByName(facts.containers);
|
|
160
|
+
for (const f of facts.files) {
|
|
161
|
+
const c = facts.containers.find((x) => x.dir === f.container);
|
|
162
|
+
const from = componentId(c, f.component);
|
|
163
|
+
for (const imp of f.imports) {
|
|
164
|
+
const edge = importEdge(facts, byName, c, from, imp);
|
|
165
|
+
if (edge) edges.add(...edge, [f.path]);
|
|
166
|
+
}
|
|
167
|
+
for (const n of f.envs.filter((name) => use.get(f.container)?.has(contextOf(name)))) edges.add(from, externalId(contextOf(n)), "reads", [f.path]);
|
|
168
|
+
}
|
|
169
|
+
return edges;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const componentLevel = (facts, use, containers) => {
|
|
173
|
+
const edges = componentEdges(facts, use).list();
|
|
174
|
+
const wanted = new Set(edges.flatMap((e) => [e.from, e.to]));
|
|
175
|
+
const refs = containers.nodes.filter((n) => wanted.has(n.id));
|
|
176
|
+
return { level: "components", nodes: [...componentNodes(facts), ...refs].sort(byId), edges };
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
/** The C4 view of a checkout: `{ schema, repo, levels: { context, containers, components } }`, deterministic. */
|
|
180
|
+
export function buildC4(root) {
|
|
181
|
+
const facts = scan(root);
|
|
182
|
+
const use = envUse(facts);
|
|
183
|
+
const containers = containerLevel(facts, use);
|
|
184
|
+
return { schema: SCHEMA, repo: facts.repo, levels: { context: contextLevel(facts, use, containers), containers, components: componentLevel(facts, use, containers) } };
|
|
185
|
+
}
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// krizaka-architecture <repo-path> [--out c4.json] [--level context|containers|components] [--text [file]]
|
|
3
|
+
// Without --out the JSON goes to stdout. With --level the file holds that level only: { level, nodes, edges }.
|
|
4
|
+
import { existsSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
|
|
7
|
+
import { buildC4, toText } from "./index.mjs";
|
|
8
|
+
|
|
9
|
+
const args = process.argv.slice(2);
|
|
10
|
+
const flag = (name) => {
|
|
11
|
+
const i = args.indexOf(`--${name}`);
|
|
12
|
+
if (i < 0) return undefined;
|
|
13
|
+
const value = args[i + 1];
|
|
14
|
+
return value && !value.startsWith("--") ? value : true;
|
|
15
|
+
};
|
|
16
|
+
const repoPath = args.find((a, i) => !a.startsWith("--") && !(args[i - 1] ?? "").startsWith("--"));
|
|
17
|
+
|
|
18
|
+
if (!repoPath || !existsSync(resolve(repoPath))) {
|
|
19
|
+
console.error("usage: krizaka-architecture <repo-path> [--out file.json] [--level context|containers|components] [--text [file.md]]");
|
|
20
|
+
process.exit(2);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const c4 = buildC4(resolve(repoPath));
|
|
24
|
+
const level = flag("level");
|
|
25
|
+
if (level && !c4.levels[level]) {
|
|
26
|
+
console.error(`unknown level "${level}": context, containers or components`);
|
|
27
|
+
process.exit(2);
|
|
28
|
+
}
|
|
29
|
+
const json = `${JSON.stringify(level ? c4.levels[level] : c4, null, 2)}\n`;
|
|
30
|
+
const out = flag("out");
|
|
31
|
+
const text = flag("text");
|
|
32
|
+
|
|
33
|
+
if (typeof out === "string") writeFileSync(resolve(out), json);
|
|
34
|
+
else if (text !== true) process.stdout.write(json);
|
|
35
|
+
if (typeof text === "string") writeFileSync(resolve(text), toText(c4));
|
|
36
|
+
else if (text === true) process.stdout.write(toText(c4));
|
|
37
|
+
if (typeof out === "string") {
|
|
38
|
+
const counts = Object.values(c4.levels).map((l) => l.nodes.length + " " + l.level + " node(s)").join(", ");
|
|
39
|
+
console.log(`${c4.repo}: ${counts} -> ${out}`);
|
|
40
|
+
}
|
package/src/files.mjs
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Reading a checkout: the files worth looking at and the workspace layout. Node built-ins only.
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { join, posix } from "node:path";
|
|
4
|
+
|
|
5
|
+
import { asc } from "./order.mjs";
|
|
6
|
+
|
|
7
|
+
const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", ".next", ".turbo", "coverage", "out", "target", ".open-next", ".expo", ".cache", ".venv"]);
|
|
8
|
+
const CODE = /\.(?:[cm]?[jt]sx?)$/;
|
|
9
|
+
const TEST = /(?:\.(?:test|spec|stories)\.[cm]?[jt]sx?$|(?:^|\/)(?:__tests__|test|tests|e2e|fixtures)\/)/;
|
|
10
|
+
const ENV_FILES = /^(?:env\.(?:[cm]?[jt]s)|\.env\.(?:example|sample|template))$/;
|
|
11
|
+
const MAX_BYTES = 1_000_000;
|
|
12
|
+
|
|
13
|
+
export const readText = (path) => {
|
|
14
|
+
try {
|
|
15
|
+
return statSync(path).size > MAX_BYTES ? "" : readFileSync(path, "utf8");
|
|
16
|
+
} catch {
|
|
17
|
+
return "";
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export const readJson = (path) => {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(readText(path));
|
|
24
|
+
} catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** Every code file and env declaration file of a checkout, as repo-relative paths with "/". Tests are listed apart. */
|
|
30
|
+
const listing = () => ({ code: [], tests: [], env: [] });
|
|
31
|
+
|
|
32
|
+
export function walk(root, rel = "", out = listing()) {
|
|
33
|
+
for (const entry of readdirSync(join(root, rel), { withFileTypes: true })) {
|
|
34
|
+
const path = rel ? `${rel}/${entry.name}` : entry.name;
|
|
35
|
+
if (entry.isDirectory()) {
|
|
36
|
+
if (!SKIP_DIRS.has(entry.name)) walk(root, path, out);
|
|
37
|
+
} else if (ENV_FILES.test(entry.name)) {
|
|
38
|
+
out.env.push(path);
|
|
39
|
+
} else if (CODE.test(entry.name)) {
|
|
40
|
+
(TEST.test(path) ? out.tests : out.code).push(path);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const yamlPackages = (yaml) => {
|
|
47
|
+
const lines = yaml.split("\n");
|
|
48
|
+
const start = lines.findIndex((l) => /^packages:\s*$/.test(l));
|
|
49
|
+
if (start < 0) return [];
|
|
50
|
+
const found = [];
|
|
51
|
+
for (const line of lines.slice(start + 1)) {
|
|
52
|
+
const m = /^\s*-\s*['"]?([^'"#\s]+)['"]?/.exec(line);
|
|
53
|
+
if (m) found.push(m[1]);
|
|
54
|
+
else if (/^\S/.test(line)) break;
|
|
55
|
+
}
|
|
56
|
+
return found;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const subdirs = (root, rel) => {
|
|
60
|
+
try {
|
|
61
|
+
return readdirSync(join(root, rel), { withFileTypes: true }).filter((e) => e.isDirectory() && !SKIP_DIRS.has(e.name)).map((e) => posix.join(rel, e.name));
|
|
62
|
+
} catch {
|
|
63
|
+
return [];
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const expand = (root, pattern) => {
|
|
68
|
+
const clean = pattern.replace(/^\.\//, "").replace(/\/\*\*$/, "/*").replace(/\/$/, "");
|
|
69
|
+
if (clean.includes("*") && !clean.endsWith("/*")) return [];
|
|
70
|
+
const dirs = clean.endsWith("/*") ? subdirs(root, clean.slice(0, -2)) : [clean];
|
|
71
|
+
return dirs.filter((d) => existsSync(join(root, d, "package.json")));
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/** The directories of the workspace packages (npm/yarn `workspaces` and pnpm-workspace.yaml); [] when the repo is not a workspace. */
|
|
75
|
+
export function workspaceDirs(root) {
|
|
76
|
+
const pkg = readJson(join(root, "package.json"));
|
|
77
|
+
const declared = Array.isArray(pkg?.workspaces) ? pkg.workspaces : (pkg?.workspaces?.packages ?? []);
|
|
78
|
+
const patterns = [...declared, ...yamlPackages(readText(join(root, "pnpm-workspace.yaml")))];
|
|
79
|
+
const excluded = new Set(patterns.filter((p) => p.startsWith("!")).flatMap((p) => expand(root, p.slice(1))));
|
|
80
|
+
return [...new Set(patterns.filter((p) => !p.startsWith("!")).flatMap((p) => expand(root, p)))].filter((d) => !excluded.has(d)).sort(asc);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The Maven modules listed by the root pom (one level), as repo-relative directories. */
|
|
84
|
+
export function mavenModules(root) {
|
|
85
|
+
const pom = readText(join(root, "pom.xml"));
|
|
86
|
+
return [...pom.matchAll(/<module>\s*([^<\s]+)\s*<\/module>/g)].map((m) => posix.normalize(m[1])).filter((d) => existsSync(join(root, d, "pom.xml"))).sort(asc);
|
|
87
|
+
}
|
package/src/imports.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// What a source file says about its neighbours: the modules it imports and the environment it reads.
|
|
2
|
+
import { posix } from "node:path";
|
|
3
|
+
|
|
4
|
+
import { asc } from "./order.mjs";
|
|
5
|
+
|
|
6
|
+
const SPECIFIERS = [
|
|
7
|
+
/(?:import|export)\s[^'"`;]*?from\s*['"]([^'"]+)['"]/g,
|
|
8
|
+
/import\s*['"]([^'"]+)['"]/g,
|
|
9
|
+
/(?:import|require)\(\s*['"]([^'"]+)['"]\s*\)/g,
|
|
10
|
+
];
|
|
11
|
+
const CONTEXTS = "APP|DATABASE|AUTH|MEDIA|MAIL|PUSH|PAYMENTS|REALTIME|ABUSE|OBSERVABILITY|AI|OPERATOR";
|
|
12
|
+
const ENV_NAME = new RegExp(String.raw`\b((?:NEXT_PUBLIC_)?(?:${CONTEXTS})_[A-Z0-9_]*[A-Z0-9])\b`, "g");
|
|
13
|
+
const ENV_ONLY = new RegExp(`^(?:NEXT_PUBLIC_)?(?:${CONTEXTS})_[A-Z0-9_]*[A-Z0-9]$`);
|
|
14
|
+
const PROCESS_ENV = /(?:process\.env|import\.meta\.env)\.([A-Z][A-Z0-9_]+)/g;
|
|
15
|
+
|
|
16
|
+
/** The module specifiers a source names, in source order. */
|
|
17
|
+
export const specifiersOf = (source) => SPECIFIERS.flatMap((re) => [...source.matchAll(re)]).sort((a, b) => a.index - b.index).map((m) => m[1]);
|
|
18
|
+
|
|
19
|
+
/** `@scope/name/sub` -> `@scope/name`; `name/sub` -> `name`; a relative, alias or built-in path -> undefined. */
|
|
20
|
+
export function packageOf(specifier) {
|
|
21
|
+
if (/^(?:[./]|@\/|~\/|node:)/.test(specifier)) return undefined;
|
|
22
|
+
const parts = specifier.split("/");
|
|
23
|
+
return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The repo path a relative (`./x`, `../x`) or root-alias (`@/x`, `~/x`) specifier points to, extension-less. */
|
|
27
|
+
export function localTarget(specifier, fromFile, containerDir) {
|
|
28
|
+
if (specifier.startsWith(".")) return posix.normalize(posix.join(posix.dirname(fromFile), specifier));
|
|
29
|
+
if (/^[@~]\//.test(specifier)) return posix.join(containerDir === "." ? "" : containerDir, specifier.slice(2));
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const strip = (names) => names.map((n) => n.replace(/^NEXT_PUBLIC_/, ""));
|
|
34
|
+
|
|
35
|
+
/** The env names of the declared contexts: every one a declaration file lists, only the ones a source file reads. */
|
|
36
|
+
export function envNamesOf(source, { declaration }) {
|
|
37
|
+
const found = declaration ? [...source.matchAll(ENV_NAME)].map((m) => m[1]) : [...source.matchAll(PROCESS_ENV)].map((m) => m[1]).filter((n) => ENV_ONLY.test(n));
|
|
38
|
+
return [...new Set(strip(found))].sort(asc);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The context of an env name (`MAIL_PROVIDER` -> `MAIL`). */
|
|
42
|
+
export const contextOf = (name) => name.split("_")[0];
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export type C4LevelName = "context" | "containers" | "components";
|
|
2
|
+
|
|
3
|
+
export interface C4Node {
|
|
4
|
+
id: string;
|
|
5
|
+
level: "system" | "container" | "component" | "external";
|
|
6
|
+
kind: "system" | "app" | "library" | "module" | "component" | "external";
|
|
7
|
+
name: string;
|
|
8
|
+
description: string;
|
|
9
|
+
technology?: string;
|
|
10
|
+
/** Repo-relative files behind the node (capped at 200; `fileCount` is the true number). */
|
|
11
|
+
files: string[];
|
|
12
|
+
fileCount: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface C4Edge {
|
|
16
|
+
from: string;
|
|
17
|
+
to: string;
|
|
18
|
+
/** `uses` (container depends on / imports another), `imports` (component to component), `reads` (env of an external service). */
|
|
19
|
+
label: "uses" | "imports" | "reads";
|
|
20
|
+
count: number;
|
|
21
|
+
files: string[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface C4Level {
|
|
25
|
+
level: C4LevelName;
|
|
26
|
+
nodes: C4Node[];
|
|
27
|
+
edges: C4Edge[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface C4 {
|
|
31
|
+
schema: "krizaka.c4/1";
|
|
32
|
+
repo: string;
|
|
33
|
+
levels: Record<C4LevelName, C4Level>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const SCHEMA: "krizaka.c4/1";
|
|
37
|
+
export function buildC4(repoPath: string): C4;
|
|
38
|
+
export function toText(c4: C4): string;
|
package/src/index.mjs
ADDED
package/src/order.mjs
ADDED
package/src/scan.mjs
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// The facts of a checkout: its containers (workspace packages or Maven modules), its source files with what each imports and reads.
|
|
2
|
+
import { basename, join, posix, resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
import { mavenModules, readJson, readText, walk, workspaceDirs } from "./files.mjs";
|
|
5
|
+
import { envNamesOf, localTarget, packageOf, specifiersOf } from "./imports.mjs";
|
|
6
|
+
|
|
7
|
+
const FRAMEWORKS = [["next", "Next.js", true], ["expo", "Expo", true], ["react-native", "React Native", true], ["vite", "Vite", true], ["express", "Express", true], ["fastify", "Fastify", true], ["hono", "Hono", true]];
|
|
8
|
+
|
|
9
|
+
const npmContainer = (root, dir) => {
|
|
10
|
+
const pkg = readJson(join(root, dir, "package.json")) ?? {};
|
|
11
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies };
|
|
12
|
+
const framework = FRAMEWORKS.find(([name]) => name in (pkg.dependencies ?? {}));
|
|
13
|
+
const app = /^apps?\//.test(dir) || Boolean(framework?.[2]) || Boolean(pkg.private && pkg.scripts?.start);
|
|
14
|
+
return { dir, name: pkg.name ?? (dir === "." ? basename(resolve(root)) : posix.basename(dir)), description: pkg.description ?? "", kind: app ? "app" : "library", technology: framework?.[1] ?? "TypeScript", deps: Object.keys(deps), manifest: posix.join(dir, "package.json") };
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const artifactIds = (xml) => [...xml.matchAll(/<artifactId>\s*([^<\s]+)\s*<\/artifactId>/g)].map((m) => m[1]);
|
|
18
|
+
|
|
19
|
+
const mavenContainer = (root, dir) => {
|
|
20
|
+
const pom = readText(join(root, dir, "pom.xml"));
|
|
21
|
+
const own = artifactIds(pom.replace(/<parent>[\s\S]*?<\/parent>/, "").replace(/<dependencies>[\s\S]*?<\/dependencies>/g, ""))[0];
|
|
22
|
+
const deps = [...pom.matchAll(/<dependency>([\s\S]*?)<\/dependency>/g)].flatMap((m) => artifactIds(m[1]).slice(0, 1));
|
|
23
|
+
return { dir, name: own ?? posix.basename(dir), description: (/<description>([^<]*)<\/description>/.exec(pom)?.[1] ?? "").trim(), kind: "module", technology: "Maven", deps, manifest: posix.join(dir, "pom.xml") };
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** The containers of a checkout: workspace packages, else Maven modules, else the root package itself. */
|
|
27
|
+
export function containersOf(root) {
|
|
28
|
+
const packages = workspaceDirs(root);
|
|
29
|
+
if (packages.length) return packages.map((d) => npmContainer(root, d));
|
|
30
|
+
const modules = mavenModules(root);
|
|
31
|
+
if (modules.length) return modules.map((d) => mavenContainer(root, d));
|
|
32
|
+
return readJson(join(root, "package.json")) ? [npmContainer(root, ".")] : [];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const insideOf = (dir, path) => (dir === "." ? path : path.slice(dir.length + 1));
|
|
36
|
+
|
|
37
|
+
/** The container a repo path belongs to: the deepest directory that contains it. */
|
|
38
|
+
export const containerOfPath = (containers, path) => [...containers].sort((a, b) => b.dir.length - a.dir.length).find((c) => c.dir === "." || path.startsWith(`${c.dir}/`));
|
|
39
|
+
|
|
40
|
+
/** The component of a path inside its container: the first folder under `src/` (or the container root), `root` for loose files. */
|
|
41
|
+
export function componentOf(container, path) {
|
|
42
|
+
const segments = insideOf(container.dir, path).replace(/^src\//, "").split("/");
|
|
43
|
+
return segments.length < 2 ? "root" : segments[0];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const factsOf = (root, containers, path) => {
|
|
47
|
+
const container = containerOfPath(containers, path);
|
|
48
|
+
if (!container) return undefined;
|
|
49
|
+
const source = readText(join(root, path));
|
|
50
|
+
const imports = specifiersOf(source).flatMap((spec) => {
|
|
51
|
+
const name = packageOf(spec);
|
|
52
|
+
if (name) return [{ kind: "package", name }];
|
|
53
|
+
const target = localTarget(spec, path, container.dir);
|
|
54
|
+
return target ? [{ kind: "local", target }] : [];
|
|
55
|
+
});
|
|
56
|
+
return { path, container: container.dir, component: componentOf(container, path), imports, envs: envNamesOf(source, { declaration: false }) };
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const declarationsOf = (root, containers, paths) => paths.flatMap((path) => {
|
|
60
|
+
const container = containerOfPath(containers, path);
|
|
61
|
+
return container ? [{ path, container: container.dir, names: envNamesOf(readText(join(root, path)), { declaration: true }) }] : [];
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
/** Everything the C4 levels are built from. */
|
|
65
|
+
export function scan(root) {
|
|
66
|
+
const repo = readJson(join(root, "package.json"))?.name ?? basename(resolve(root));
|
|
67
|
+
const containers = containersOf(root);
|
|
68
|
+
const found = walk(root);
|
|
69
|
+
const files = found.code.map((p) => factsOf(root, containers, p)).filter(Boolean);
|
|
70
|
+
return { repo, containers, files, declarations: declarationsOf(root, containers, found.env), testCount: found.tests.length };
|
|
71
|
+
}
|
package/src/text.mjs
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// The text version of the C4 view (every drawing carries one): a list of nodes and a list of relations per level.
|
|
2
|
+
const TITLES = { context: "System context", containers: "Containers", components: "Components" };
|
|
3
|
+
|
|
4
|
+
const brief = (text) => (text.length > 120 ? `${text.slice(0, 117).trimEnd()}...` : text);
|
|
5
|
+
|
|
6
|
+
const nodeLine = (n) => {
|
|
7
|
+
const what = [n.kind, n.technology].filter(Boolean).join(", ");
|
|
8
|
+
const about = n.description ? ": " + brief(n.description) : "";
|
|
9
|
+
const size = n.fileCount ? " [" + n.fileCount + " file(s)]" : "";
|
|
10
|
+
return `- ${n.name} (${what})${about}${size}`;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/** The edge lines, naming nodes rather than ids. */
|
|
14
|
+
function edgeLines(level) {
|
|
15
|
+
const name = new Map(level.nodes.map((n) => [n.id, n.name]));
|
|
16
|
+
return level.edges.map((e) => {
|
|
17
|
+
const files = e.count > 1 ? " (" + e.count + " files)" : "";
|
|
18
|
+
return `- ${name.get(e.from) ?? e.from} ${e.label} ${name.get(e.to) ?? e.to}${files}`;
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function toText(c4) {
|
|
23
|
+
const blocks = Object.values(c4.levels).map((level) => [`## ${TITLES[level.level]}`, "", ...level.nodes.map(nodeLine), "", ...(level.edges.length ? ["Relations", ...edgeLines(level)] : ["No relation found."]), ""].join("\n"));
|
|
24
|
+
return `# ${c4.repo}: C4 from the code\n\n${blocks.join("\n")}`;
|
|
25
|
+
}
|