@domain-first/project-structure 8.1.1 → 8.3.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.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/graph.js ADDED
@@ -0,0 +1,337 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import node_fs from "node:fs";
4
+ import node_os from "node:os";
5
+ import node_path from "node:path";
6
+ import { parseArgs } from "node:util";
7
+ import { File, ProjectRoot, outdatedConfigMessage, ConfigFile } from "./870.js";
8
+ import { readAliases, resolveSpecifier } from "./38.js";
9
+ import { namedImportFiles, wiring_layers, findWiredModules, wiredDependencyNames } from "./201.js";
10
+ const sharedKernel = 'shared-kernel';
11
+ const contextsOf = (contextsFolder)=>node_fs.existsSync(contextsFolder) ? node_fs.readdirSync(contextsFolder, {
12
+ withFileTypes: true
13
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
14
+ const projectGraph = (projectRoot, rootFolder)=>{
15
+ const root = node_path.resolve(projectRoot, rootFolder);
16
+ const contextsFolder = node_path.join(root, 'bounded-contexts');
17
+ const owners = [
18
+ sharedKernel,
19
+ ...contextsOf(contextsFolder)
20
+ ];
21
+ const ownerPath = (owner)=>owner === sharedKernel ? node_path.join(root, sharedKernel) : node_path.join(contextsFolder, owner);
22
+ const byWireFile = new Map();
23
+ const wired = [];
24
+ for (const owner of owners)for (const module of findWiredModules(ownerPath(owner))){
25
+ const node = {
26
+ id: `${owner}:${module.typeName}`,
27
+ owner,
28
+ typeName: module.typeName,
29
+ layer: module.layer,
30
+ implementations: module.implementations.map(({ className })=>className)
31
+ };
32
+ byWireFile.set(module.wireFile, node);
33
+ wired.push([
34
+ module,
35
+ node
36
+ ]);
37
+ }
38
+ const aliases = readAliases(projectRoot);
39
+ const edges = [];
40
+ for (const [module, node] of wired){
41
+ const source = new File(module.wireFile).data;
42
+ const imported = namedImportFiles(source, module.wireFile, (specifier, file)=>resolveSpecifier(specifier, file, aliases));
43
+ for (const { className } of module.implementations)for (const name of wiredDependencyNames(source, className)){
44
+ const file = imported.get(name);
45
+ const target = file && byWireFile.get(file);
46
+ if (target) edges.push({
47
+ from: node.id,
48
+ to: target.id,
49
+ implementation: className
50
+ });
51
+ }
52
+ }
53
+ return {
54
+ owners,
55
+ modules: wired.map(([, node])=>node),
56
+ edges
57
+ };
58
+ };
59
+ const sanitize = (value)=>value.replace(/[^A-Za-z0-9]/g, '_');
60
+ const quoted = (value)=>`"${value.replace(/"/g, '#quot;')}"`;
61
+ const ownerOf = (graph, id)=>graph.modules.find((module)=>module.id === id)?.owner;
62
+ const typeOf = (graph, id)=>graph.modules.find((module)=>module.id === id)?.typeName ?? id;
63
+ const contextMap = (graph, idPrefix = '')=>{
64
+ const nodeId = (value)=>`${idPrefix}${sanitize(value)}`;
65
+ const links = new Map();
66
+ for (const edge of graph.edges){
67
+ const from = ownerOf(graph, edge.from);
68
+ const to = ownerOf(graph, edge.to);
69
+ if (!from || !to || from === to) continue;
70
+ const key = `${from}\u0000${to}`;
71
+ const set = links.get(key) ?? new Set();
72
+ set.add(to === sharedKernel ? typeOf(graph, edge.to) : `${typeOf(graph, edge.from)} → ${typeOf(graph, edge.to)}`);
73
+ links.set(key, set);
74
+ }
75
+ const lines = [
76
+ 'flowchart LR'
77
+ ];
78
+ for (const owner of graph.owners)lines.push(owner === sharedKernel ? ` ${nodeId(owner)}[(${quoted(owner)})]` : ` ${nodeId(owner)}[${quoted(owner)}]`);
79
+ for (const [key, labels] of [
80
+ ...links
81
+ ].sort(([a], [b])=>a.localeCompare(b))){
82
+ const [from, to] = key.split('\u0000');
83
+ const label = [
84
+ ...labels
85
+ ].sort().join('<br/>');
86
+ lines.push(to === sharedKernel ? ` ${nodeId(from)} -.->|${quoted(label)}| ${nodeId(to)}` : ` ${nodeId(from)} -->|${quoted(label)}| ${nodeId(to)}`);
87
+ }
88
+ return lines.join('\n');
89
+ };
90
+ const ownerGraph = (graph, owner, idPrefix = '')=>{
91
+ const nodeId = (value)=>`${idPrefix}${sanitize(value)}`;
92
+ const own = graph.modules.filter((module)=>module.owner === owner);
93
+ const ownIds = new Set(own.map((module)=>module.id));
94
+ const edges = new Map();
95
+ for (const edge of graph.edges){
96
+ if (!ownIds.has(edge.from)) continue;
97
+ const key = `${edge.from}\u0000${edge.to}`;
98
+ const set = edges.get(key) ?? new Set();
99
+ set.add(edge.implementation);
100
+ edges.set(key, set);
101
+ }
102
+ const external = [
103
+ ...new Set([
104
+ ...edges.keys()
105
+ ].map((key)=>key.split('\u0000')[1]).filter((id)=>!ownIds.has(id)))
106
+ ].sort();
107
+ const lines = [
108
+ 'flowchart TB'
109
+ ];
110
+ const node = (id)=>`${nodeId(id)}[${quoted(typeOf(graph, id))}]`;
111
+ for (const layer of wiring_layers){
112
+ const members = own.filter((module)=>module.layer === layer);
113
+ if (members.length) {
114
+ lines.push(` subgraph ${nodeId(`${owner}_${layer}`)}[${quoted(layer)}]`);
115
+ for (const module of members)lines.push(` ${node(module.id)}`);
116
+ lines.push(' end');
117
+ }
118
+ }
119
+ for (const other of [
120
+ ...new Set(external.map((id)=>ownerOf(graph, id) ?? ''))
121
+ ]){
122
+ lines.push(` subgraph ${nodeId(`owner_${other}`)}[${quoted(other)}]`);
123
+ for (const id of external.filter((x)=>ownerOf(graph, x) === other))lines.push(` ${node(id)}`);
124
+ lines.push(' end');
125
+ }
126
+ for (const [key, implementations] of [
127
+ ...edges
128
+ ].sort(([a], [b])=>a.localeCompare(b))){
129
+ const [from, to] = key.split('\u0000');
130
+ const all = graph.modules.find((module)=>module.id === from)?.implementations.length ?? 0;
131
+ const label = implementations.size < all ? `|${quoted([
132
+ ...implementations
133
+ ].sort().join(', '))}|` : '';
134
+ lines.push(` ${nodeId(from)} -->${label} ${nodeId(to)}`);
135
+ }
136
+ return lines.join('\n');
137
+ };
138
+ const formatOfFile = (file)=>({
139
+ '.md': 'markdown',
140
+ '.mmd': 'mermaid',
141
+ '.mermaid': 'mermaid',
142
+ '.json': 'json',
143
+ '.html': 'html'
144
+ })[node_path.extname(file).toLowerCase()];
145
+ const escapeHtml = (value)=>value.replace(/[&<>"]/g, (char)=>({
146
+ '&': '&amp;',
147
+ '<': '&lt;',
148
+ '>': '&gt;',
149
+ '"': '&quot;'
150
+ })[char] ?? char);
151
+ const mermaidScript = 'https://cdn.jsdelivr.net/npm/mermaid@11.4.1/dist/mermaid.esm.min.mjs';
152
+ const graphHtml = (graph, title, owner)=>{
153
+ const sections = owner ? [
154
+ [
155
+ owner,
156
+ ownerGraph(graph, owner, 'c0_')
157
+ ]
158
+ ] : [
159
+ [
160
+ 'Bounded contexts',
161
+ contextMap(graph, 'c0_')
162
+ ],
163
+ ...graph.owners.filter((name)=>graph.modules.some((module)=>module.owner === name)).map((name, index)=>[
164
+ name,
165
+ ownerGraph(graph, name, `c${index + 1}_`)
166
+ ])
167
+ ];
168
+ return `<!doctype html>
169
+ <html lang="en">
170
+ <head>
171
+ <meta charset="utf-8">
172
+ <meta name="viewport" content="width=device-width, initial-scale=1">
173
+ <title>${escapeHtml(title)}</title>
174
+ <style>
175
+ body { margin: 0 auto; max-width: 1200px; padding: 24px 16px; font-family: ui-monospace, Menlo, Consolas, monospace; background: #fafaf7; color: #1d1d1b; }
176
+ h1 { font-size: 22px; } h2 { margin-top: 40px; font-size: 18px; border-bottom: 2px solid #1d1d1b; padding-bottom: 6px; }
177
+ .mermaid { overflow-x: auto; }
178
+ </style>
179
+ </head>
180
+ <body>
181
+ <h1>${escapeHtml(title)}</h1>
182
+ ${sections.map(([name, chart])=>`<h2>${escapeHtml(name)}</h2>\n<pre class="mermaid">\n${escapeHtml(chart)}\n</pre>`).join('\n')}
183
+ <script type="module">
184
+ import mermaid from '${mermaidScript}';
185
+ mermaid.initialize({ startOnLoad: false });
186
+ // One chart at a time: charts rendered together disturb each other's layout.
187
+ for (const node of document.querySelectorAll('.mermaid')) {
188
+ await mermaid.run({ nodes: [node] });
189
+ }
190
+ </script>
191
+ </body>
192
+ </html>
193
+ `;
194
+ };
195
+ const renderGraph = (graph, format, { owner, title = 'Project structure' } = {})=>{
196
+ if ('html' === format) return graphHtml(graph, title, owner);
197
+ if ('json' === format) {
198
+ const modules = owner ? graph.modules.filter((module)=>module.owner === owner) : graph.modules;
199
+ const ids = new Set(modules.map((module)=>module.id));
200
+ return JSON.stringify({
201
+ owners: owner ? [
202
+ owner
203
+ ] : graph.owners,
204
+ modules,
205
+ edges: owner ? graph.edges.filter((edge)=>ids.has(edge.from)) : graph.edges
206
+ });
207
+ }
208
+ const chart = owner ? ownerGraph(graph, owner) : contextMap(graph);
209
+ return 'markdown' === format ? `\`\`\`mermaid\n${chart}\n\`\`\`` : chart;
210
+ };
211
+ const help = `Usage: df-graph [--context <name>] [--json | --markdown | --html] [--out <file>]
212
+
213
+ Shows the project's structure as a Mermaid flowchart, read from the wiring.
214
+ Without options it prints the bounded contexts and the Shared Kernel, with
215
+ the cross-context ports that reach a neighbor's handlers (solid arrows) and
216
+ the use of the Shared Kernel (dashed arrows).
217
+
218
+ Options:
219
+ --context <name> the wired modules of one bounded context (or shared-kernel)
220
+ by layer, with their dependencies
221
+ --markdown wrap the chart in a \`\`\`mermaid block, e.g. for a README
222
+ --json the graph as JSON: owners, modules and dependencies
223
+ --html a page with the rendered charts (all contexts without
224
+ --context), opened in the browser; Mermaid loads from a CDN
225
+ --out <file> write to a file instead; the extension picks the format:
226
+ .md, .mmd/.mermaid, .json or .html
227
+ -h, --help show this help`;
228
+ const { values: values } = parseArgs({
229
+ options: {
230
+ help: {
231
+ type: 'boolean',
232
+ short: 'h',
233
+ default: false
234
+ },
235
+ context: {
236
+ type: 'string'
237
+ },
238
+ json: {
239
+ type: 'boolean',
240
+ default: false
241
+ },
242
+ markdown: {
243
+ type: 'boolean',
244
+ default: false
245
+ },
246
+ html: {
247
+ type: 'boolean',
248
+ default: false
249
+ },
250
+ out: {
251
+ type: 'string'
252
+ }
253
+ }
254
+ });
255
+ if (values.help) {
256
+ console.log(help);
257
+ process.exit(0);
258
+ }
259
+ const fail = (message)=>{
260
+ console.log(message);
261
+ process.exit(1);
262
+ };
263
+ const flagged = [
264
+ 'json',
265
+ 'markdown',
266
+ 'html'
267
+ ].filter((flag)=>values[flag]);
268
+ if (flagged.length > 1) fail('Choose one of --json, --markdown and --html.');
269
+ const fileFormat = void 0 === values.out ? void 0 : formatOfFile(values.out);
270
+ if (void 0 !== values.out && !fileFormat) fail('--out needs a .md, .mmd, .mermaid, .json or .html file.');
271
+ const flagFormat = flagged[0];
272
+ if (fileFormat && flagFormat && fileFormat !== flagFormat) fail(`--${flagFormat} doesn't match ${values.out}.`);
273
+ const graph_format = fileFormat ?? flagFormat ?? 'mermaid';
274
+ if (!ConfigFile.exists) fail('No domain-first.project-structure.config.json found: run df-init first to initialize the project.');
275
+ if (ConfigFile.outdated) fail(outdatedConfigMessage);
276
+ const config = ConfigFile.Instance.data;
277
+ if (!config.backend) fail('Backend is not configured: run df-init --section backend.');
278
+ if (!config.backend?.domainFirstPackages.includes('@domain-first/wire')) fail('df-graph reads the wiring: it needs @domain-first/wire.');
279
+ const graph_projectRoot = new ProjectRoot().path;
280
+ const graph_graph = projectGraph(graph_projectRoot, config.project.rootFolder);
281
+ const graph_owner = values.context;
282
+ if (void 0 !== graph_owner && !graph_graph.owners.includes(graph_owner)) fail(`Unknown context: ${graph_owner}. Known: ${graph_graph.owners.join(', ')}.`);
283
+ if (!graph_graph.modules.length) console.error(`No wired modules yet: generate some with df-scaffold (${sharedKernel} and bounded contexts are scanned).`);
284
+ const packageName = (()=>{
285
+ try {
286
+ return JSON.parse(node_fs.readFileSync(node_path.join(graph_projectRoot, 'package.json'), 'utf8')).name;
287
+ } catch {
288
+ return;
289
+ }
290
+ })();
291
+ const output = renderGraph(graph_graph, graph_format, {
292
+ owner: graph_owner,
293
+ title: [
294
+ packageName ?? node_path.basename(graph_projectRoot),
295
+ graph_owner
296
+ ].filter(Boolean).join(' / ')
297
+ });
298
+ const openInBrowser = (file)=>{
299
+ const [command, args] = 'darwin' === process.platform ? [
300
+ 'open',
301
+ [
302
+ file
303
+ ]
304
+ ] : 'win32' === process.platform ? [
305
+ 'cmd',
306
+ [
307
+ '/c',
308
+ 'start',
309
+ '',
310
+ file
311
+ ]
312
+ ] : [
313
+ 'xdg-open',
314
+ [
315
+ file
316
+ ]
317
+ ];
318
+ const child = spawn(command, args, {
319
+ stdio: 'ignore',
320
+ detached: true
321
+ });
322
+ child.on('error', ()=>console.log(`Open ${file} in a browser.`));
323
+ child.unref();
324
+ };
325
+ if (void 0 !== values.out) {
326
+ const file = node_path.resolve(values.out);
327
+ node_fs.mkdirSync(node_path.dirname(file), {
328
+ recursive: true
329
+ });
330
+ node_fs.writeFileSync(file, `${output}\n`);
331
+ console.log(`Wrote ${node_path.relative(process.cwd(), file) || file}.`);
332
+ } else if ('html' === graph_format) {
333
+ const file = node_path.join(node_os.tmpdir(), `df-graph-${(packageName ?? node_path.basename(graph_projectRoot)).replace(/[^\w-]+/g, '-')}${graph_owner ? `-${graph_owner}` : ''}.html`);
334
+ node_fs.writeFileSync(file, output);
335
+ console.log(`Wrote ${file}; opening it in the browser.`);
336
+ openInBrowser(file);
337
+ } else console.log(output);