@webpieces/nx-webpieces-rules 0.3.341 → 0.3.343
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/package.json +6 -6
- package/src/executors/generate/executor.js +10 -17
- package/src/executors/generate/executor.js.map +1 -1
- package/src/lib/graph-visualizer.d.ts +5 -4
- package/src/lib/graph-visualizer.js +12 -17
- package/src/lib/graph-visualizer.js.map +1 -1
- package/src/lib/runtime-graph.d.ts +12 -0
- package/src/lib/runtime-graph.js +120 -0
- package/src/lib/runtime-graph.js.map +1 -1
- package/src/lib/runtime-visualizer.js +21 -3
- package/src/lib/runtime-visualizer.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/nx-webpieces-rules",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.343",
|
|
4
4
|
"description": "Nx-specific webpieces validation rules and graph tooling. Bundles all @webpieces rule packages with Nx graph validators and an inference plugin.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -21,11 +21,11 @@
|
|
|
21
21
|
"README.md"
|
|
22
22
|
],
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@webpieces/ai-hook-rules": "0.3.
|
|
25
|
-
"@webpieces/code-rules": "0.3.
|
|
26
|
-
"@webpieces/eslint-rules": "0.3.
|
|
27
|
-
"@webpieces/pr-gate": "0.3.
|
|
28
|
-
"@webpieces/rules-config": "0.3.
|
|
24
|
+
"@webpieces/ai-hook-rules": "0.3.343",
|
|
25
|
+
"@webpieces/code-rules": "0.3.343",
|
|
26
|
+
"@webpieces/eslint-rules": "0.3.343",
|
|
27
|
+
"@webpieces/pr-gate": "0.3.343",
|
|
28
|
+
"@webpieces/rules-config": "0.3.343",
|
|
29
29
|
"madge": "8.0.0"
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
|
@@ -16,24 +16,17 @@ const graph_loader_1 = require("../../lib/graph-loader");
|
|
|
16
16
|
const graph_metadata_1 = require("../../lib/graph-metadata");
|
|
17
17
|
const api_scanner_1 = require("../../lib/api-usage/api-scanner");
|
|
18
18
|
const graph_visualizer_1 = require("../../lib/graph-visualizer");
|
|
19
|
-
const runtime_markers_1 = require("../../lib/runtime-markers");
|
|
20
19
|
const runtime_graph_1 = require("../../lib/runtime-graph");
|
|
21
|
-
const runtime_config_1 = require("../../lib/runtime-config");
|
|
22
20
|
const toError_1 = require("../../toError");
|
|
23
21
|
/**
|
|
24
|
-
* Generate the runtime microservice graph alongside the compile-time graph,
|
|
25
|
-
* one regenerate produces both committed files.
|
|
26
|
-
* runtime
|
|
22
|
+
* Generate the runtime microservice graph alongside the compile-time graph, from the SAME source
|
|
23
|
+
* scan (the derived apiRelations) — one regenerate produces both committed files. rpc APIs become
|
|
24
|
+
* direct runtime edges; pubsub APIs become edges the viz draws through a queue.
|
|
27
25
|
*/
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return;
|
|
33
|
-
}
|
|
34
|
-
console.log('📡 Generating runtime graph from service-contract.json files...');
|
|
35
|
-
const model = await (0, runtime_markers_1.buildWorkspaceModel)(workspaceRoot, config.apiProjectPaths, config.servicePaths);
|
|
36
|
-
const runtimeGraph = (0, runtime_graph_1.assembleRuntimeGraph)(model, workspaceRoot);
|
|
26
|
+
// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file
|
|
27
|
+
function generateRuntimeGraph(workspaceRoot, scan) {
|
|
28
|
+
console.log('📡 Generating runtime graph from the source scan (implements × uses per API)...');
|
|
29
|
+
const runtimeGraph = (0, runtime_graph_1.assembleRuntimeGraphFromScan)(scan);
|
|
37
30
|
(0, runtime_graph_1.saveRuntimeGraph)(runtimeGraph, workspaceRoot);
|
|
38
31
|
const serviceCount = Object.keys(runtimeGraph.services).length;
|
|
39
32
|
console.log(`✅ Runtime graph saved (${serviceCount} services, ${runtimeGraph.runtimeEdges.length} runtime edges)`);
|
|
@@ -60,7 +53,7 @@ async function runExecutor(options, context) {
|
|
|
60
53
|
// scanning source, so dependencies.json + the viz + the runtime graph all
|
|
61
54
|
// read the same derived truth.
|
|
62
55
|
console.log('🔎 Scanning source for implements/uses API relations...');
|
|
63
|
-
(0, api_scanner_1.scanAndAttachApiRelations)(workspaceRoot, enhancedGraph, projectInfos);
|
|
56
|
+
const scanResult = (0, api_scanner_1.scanAndAttachApiRelations)(workspaceRoot, enhancedGraph, projectInfos);
|
|
64
57
|
// Step 4: Save the graph
|
|
65
58
|
console.log('💾 Saving graph to architecture/dependencies.json...');
|
|
66
59
|
(0, graph_loader_1.saveGraph)(enhancedGraph, workspaceRoot, graphPath);
|
|
@@ -69,8 +62,8 @@ async function runExecutor(options, context) {
|
|
|
69
62
|
// dependencies.html regenerates in lock-step with dependencies.json.
|
|
70
63
|
const vizPaths = new graph_visualizer_1.GraphVisualizer().writeVisualization(enhancedGraph, workspaceRoot);
|
|
71
64
|
console.log(`✅ Wrote ${vizPaths.htmlPath}`);
|
|
72
|
-
// Step 5: Generate the runtime microservice graph
|
|
73
|
-
|
|
65
|
+
// Step 5: Generate the runtime microservice graph from the same scan
|
|
66
|
+
generateRuntimeGraph(workspaceRoot, scanResult);
|
|
74
67
|
// Print summary
|
|
75
68
|
const projectCount = Object.keys(enhancedGraph).length;
|
|
76
69
|
const levels = new Set(Object.values(enhancedGraph).map((e) => e.level));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/generate/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;
|
|
1
|
+
{"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/generate/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;AAsCH,8BA+DC;AAlGD,0DAAwD;AACxD,+DAAiE;AACjE,yDAAgE;A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MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,KAAK,CAAC,4BAA4B,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAC3D,IAAI,KAAK,YAAY,wCAAuB,EAAE,CAAC;YAC3C,MAAM,MAAM,GAAG,IAAA,4BAAa,EAAC,aAAa,EAAE,+BAA+B,CAAC,CAAC;YAC7E,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClB,OAAO,CAAC,KAAK,CAAC,mBAAmB,GAAG,MAAM,GAAG,qDAAqD,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Generate Executor\n *\n * Generates the architecture dependency graph and saves it to architecture/dependencies.json.\n *\n * Usage:\n * nx run architecture:generate\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { writeTemplate } from '@webpieces/rules-config';\nimport { generateReducedGraph } from '../../lib/graph-generator';\nimport { sortGraphTopologically } from '../../lib/graph-sorter';\nimport { saveGraph } from '../../lib/graph-loader';\nimport { collectProjectInfo, enrichGraph, MetadataValidationError } from '../../lib/graph-metadata';\nimport { scanAndAttachApiRelations } from '../../lib/api-usage/api-scanner';\nimport type { ApiScanResult } from '../../lib/api-usage/api-scanner';\nimport { GraphVisualizer } from '../../lib/graph-visualizer';\nimport { assembleRuntimeGraphFromScan, saveRuntimeGraph } from '../../lib/runtime-graph';\nimport { toError } from '../../toError';\n\nexport interface GenerateExecutorOptions {\n graphPath?: string;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n/**\n * Generate the runtime microservice graph alongside the compile-time graph, from the SAME source\n * scan (the derived apiRelations) — one regenerate produces both committed files. rpc APIs become\n * direct runtime edges; pubsub APIs become edges the viz draws through a queue.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction generateRuntimeGraph(workspaceRoot: string, scan: ApiScanResult): void {\n console.log('📡 Generating runtime graph from the source scan (implements × uses per API)...');\n const runtimeGraph = assembleRuntimeGraphFromScan(scan);\n saveRuntimeGraph(runtimeGraph, workspaceRoot);\n const serviceCount = Object.keys(runtimeGraph.services).length;\n console.log(\n `✅ Runtime graph saved (${serviceCount} services, ${runtimeGraph.runtimeEdges.length} runtime edges)`,\n );\n}\n\nexport default async function runExecutor(\n options: GenerateExecutorOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const graphPath = options.graphPath;\n const workspaceRoot = context.root;\n\n console.log('\\n📊 Architecture Graph Generator\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Step 1: Build the full graph from nx, then transitively reduce it to the view\n console.log(\"📊 Generating dependency graph from nx's project graph...\");\n const reducedGraph = await generateReducedGraph();\n\n // Step 2: Topological sort (to assign levels for visualization)\n console.log('🔄 Computing topological layers...');\n const enhancedGraph = sortGraphTopologically(reducedGraph);\n\n // Step 3: Enrich with AI metadata (framework, shortDescription, file\n // pointers). This VALIDATES (responsibilities.md required per project)\n // and throws before any write, so a failure never clobbers the file.\n console.log('🏷️ Enriching graph with framework + responsibilities metadata...');\n const projectInfos = await collectProjectInfo();\n enrichGraph(enhancedGraph, projectInfos, workspaceRoot);\n\n // Step 3b: Classify each api-lib edge (implements/uses + rpc/pubsub) by\n // scanning source, so dependencies.json + the viz + the runtime graph all\n // read the same derived truth.\n console.log('🔎 Scanning source for implements/uses API relations...');\n const scanResult = scanAndAttachApiRelations(workspaceRoot, enhancedGraph, projectInfos);\n\n // Step 4: Save the graph\n console.log('💾 Saving graph to architecture/dependencies.json...');\n saveGraph(enhancedGraph, workspaceRoot, graphPath);\n console.log('✅ Graph saved successfully');\n\n // Step 4b: Write the committed, clickable HTML view next to the JSON so\n // dependencies.html regenerates in lock-step with dependencies.json.\n const vizPaths = new GraphVisualizer().writeVisualization(enhancedGraph, workspaceRoot);\n console.log(`✅ Wrote ${vizPaths.htmlPath}`);\n\n // Step 5: Generate the runtime microservice graph from the same scan\n generateRuntimeGraph(workspaceRoot, scanResult);\n\n // Print summary\n const projectCount = Object.keys(enhancedGraph).length;\n const levels = new Set(Object.values(enhancedGraph).map((e) => e.level));\n console.log(`\\n📈 Graph Summary:`);\n console.log(` Projects: ${projectCount}`);\n console.log(` Levels: ${levels.size} (0-${Math.max(...levels)})`);\n\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n console.error('❌ Graph generation failed:', error.message);\n if (error instanceof MetadataValidationError) {\n const mdPath = writeTemplate(workspaceRoot, 'webpieces.responsibilities.md');\n console.error('');\n console.error('⚠️ *** Refer to ' + mdPath + ' for how to author responsibilities.md files *** ⚠️');\n }\n return { success: false };\n }\n}\n"]}
|
|
@@ -34,11 +34,12 @@ export declare class GraphVisualizer {
|
|
|
34
34
|
private roleBorderAttrs;
|
|
35
35
|
/**
|
|
36
36
|
* Edge styling by API-relation kind (why the edge exists):
|
|
37
|
-
* implements →
|
|
38
|
-
* uses →
|
|
39
|
-
*
|
|
37
|
+
* implements → BLACK dashed (a controller serves this api-lib's contract)
|
|
38
|
+
* uses → BLACK solid (a generated client calls it) — same as a
|
|
39
|
+
* plain library import, since a plain dependency IS a use.
|
|
40
|
+
* uses-implements → BLUE dashed, thicker (does both — implements some
|
|
40
41
|
* contracts of the api-lib, uses others)
|
|
41
|
-
* plain lib (none) → the default thin solid arrow, unchanged.
|
|
42
|
+
* plain lib (none) → the default thin black solid arrow, unchanged.
|
|
42
43
|
* `kind` is undefined for every non-api-lib dependency edge.
|
|
43
44
|
*/
|
|
44
45
|
private edgeAttrs;
|
|
@@ -82,20 +82,19 @@ class GraphVisualizer {
|
|
|
82
82
|
}
|
|
83
83
|
/**
|
|
84
84
|
* Edge styling by API-relation kind (why the edge exists):
|
|
85
|
-
* implements →
|
|
86
|
-
* uses →
|
|
87
|
-
*
|
|
85
|
+
* implements → BLACK dashed (a controller serves this api-lib's contract)
|
|
86
|
+
* uses → BLACK solid (a generated client calls it) — same as a
|
|
87
|
+
* plain library import, since a plain dependency IS a use.
|
|
88
|
+
* uses-implements → BLUE dashed, thicker (does both — implements some
|
|
88
89
|
* contracts of the api-lib, uses others)
|
|
89
|
-
* plain lib (none) → the default thin solid arrow, unchanged.
|
|
90
|
+
* plain lib (none) → the default thin black solid arrow, unchanged.
|
|
90
91
|
* `kind` is undefined for every non-api-lib dependency edge.
|
|
91
92
|
*/
|
|
92
93
|
edgeAttrs(kind) {
|
|
93
94
|
if (kind === 'implements')
|
|
94
95
|
return ' [style=dashed]';
|
|
95
|
-
if (kind === 'uses')
|
|
96
|
-
return ' [color="#1976d2", penwidth=2]';
|
|
97
96
|
if (kind === 'uses-implements')
|
|
98
|
-
return ' [style=dashed, color="#
|
|
97
|
+
return ' [style=dashed, color="#1976d2", penwidth=2]';
|
|
99
98
|
return '';
|
|
100
99
|
}
|
|
101
100
|
/**
|
|
@@ -427,20 +426,16 @@ class GraphVisualizer {
|
|
|
427
426
|
// Column 3 — edge line style keyed on WHY a project depends on an api-lib.
|
|
428
427
|
edgeItems() {
|
|
429
428
|
return `<div class="legend-item">
|
|
430
|
-
<svg width="42" height="12" style="vertical-align: middle; margin-right: 10px;"><line x1="0" y1="6" x2="42" y2="6" stroke="#333" stroke-width="2"
|
|
431
|
-
<strong>
|
|
432
|
-
</div>
|
|
433
|
-
<div class="legend-item">
|
|
434
|
-
<svg width="42" height="12" style="vertical-align: middle; margin-right: 10px;"><line x1="0" y1="6" x2="42" y2="6" stroke="#1976d2" stroke-width="2"/></svg>
|
|
435
|
-
<strong>uses:</strong> calls the API (generates an rpc/pubsub client via <code>createRpcClient</code>/<code>createPubSubClient</code>)
|
|
429
|
+
<svg width="42" height="12" style="vertical-align: middle; margin-right: 10px;"><line x1="0" y1="6" x2="42" y2="6" stroke="#333" stroke-width="2"/></svg>
|
|
430
|
+
<strong>uses:</strong> calls the API (generates an rpc/pubsub client via <code>createRpcClient</code>/<code>createPubSubClient</code>) — also covers a plain library import, since a plain dependency is just a use.
|
|
436
431
|
</div>
|
|
437
432
|
<div class="legend-item">
|
|
438
|
-
<svg width="42" height="12" style="vertical-align: middle; margin-right: 10px;"><line x1="0" y1="6" x2="42" y2="6" stroke="#
|
|
439
|
-
<strong>
|
|
433
|
+
<svg width="42" height="12" style="vertical-align: middle; margin-right: 10px;"><line x1="0" y1="6" x2="42" y2="6" stroke="#333" stroke-width="2" stroke-dasharray="5,3"/></svg>
|
|
434
|
+
<strong>implements:</strong> serves the API — NOTE: this is a build-dependency diagram, so a UML <em>implements</em> arrow can't be used; we use a dashed line to signal a build dep, because this server implements the api and the api is built first, then this server after.
|
|
440
435
|
</div>
|
|
441
436
|
<div class="legend-item">
|
|
442
|
-
<svg width="42" height="12" style="vertical-align: middle; margin-right: 10px;"><line x1="0" y1="6" x2="42" y2="6" stroke="#
|
|
443
|
-
<strong>
|
|
437
|
+
<svg width="42" height="12" style="vertical-align: middle; margin-right: 10px;"><line x1="0" y1="6" x2="42" y2="6" stroke="#1976d2" stroke-width="2" stroke-dasharray="5,3"/></svg>
|
|
438
|
+
<strong>uses/implements:</strong> both — implements some of the api-lib's contracts, uses others
|
|
444
439
|
</div>`;
|
|
445
440
|
}
|
|
446
441
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph-visualizer.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/graph-visualizer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,iDAAyC;AAGzC,+CAA2C;AAC3C,qEAAoE;AACpE,wCAAqC;AAErC;;;;GAIG;AACH,MAAM,gBAAgB,GAA2B;IAC7C,OAAO,EAAE,SAAS,EAAE,6BAA6B;IACjD,KAAK,EAAE,SAAS,EAAE,2BAA2B;IAC7C,OAAO,EAAE,SAAS,EAAE,wCAAwC;IAC5D,OAAO,EAAE,SAAS,EAAE,iCAAiC;IACrD,IAAI,EAAE,SAAS,EAAE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E,IAAI,EAAE,OAAO,CAAC,CAAC;QAE1C,OAAO,IAAI,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAC5C,CAAC;IAED;;OAEG;IACH,iBAAiB,CAAC,QAAgB;QAC9B,8DAA8D;QAC9D,IAAI,CAAC;YACD,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;YAClC,IAAI,WAAmB,CAAC;YAExB,IAAI,QAAQ,KAAK,QAAQ,EAAE,CAAC;gBACxB,WAAW,GAAG,SAAS,QAAQ,GAAG,CAAC;YACvC,CAAC;iBAAM,IAAI,QAAQ,KAAK,OAAO,EAAE,CAAC;gBAC9B,WAAW,GAAG,aAAa,QAAQ,GAAG,CAAC;YAC3C,CAAC;iBAAM,CAAC;gBACJ,WAAW,GAAG,aAAa,QAAQ,GAAG,CAAC;YAC3C,CAAC;YAED,IAAA,wBAAQ,EAAC,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;YAC3C,OAAO,IAAI,CAAC;QAChB,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,OAAO,CAAC,IAAI,CAAC,+BAA+B,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YAC7D,OAAO,KAAK,CAAC;QACjB,CAAC;IACL,CAAC;CACJ;AAleD,0CAkeC","sourcesContent":["/**\n * Graph Visualizer\n *\n * Generates visual representations of the architecture graph:\n * - DOT format (for Graphviz)\n * - Interactive HTML (using viz.js)\n *\n * All behavior lives on the injectable GraphVisualizer class so webpieces DI +\n * @DocumentDesign can wire it — module-scope functions are a dead end the DI\n * graph can't reach.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport type { EnhancedGraph } from './graph-sorter';\nimport type { ApiRelationKind } from './api-usage/api-relations';\nimport { GraphNames } from './graph-names';\nimport { ResponsibilitiesRenderer } from './graph-responsibilities';\nimport { toError } from '../toError';\n\n/**\n * Framework (libType) colors for visualization — nodes are filled by the FIRST\n * env in their set that has a color, so it is obvious at a glance which side a\n * project targets. A project's full env set is shown in the label.\n */\nconst FRAMEWORK_COLORS: Record<string, string> = {\n angular: '#FCE4EC', // pink - Angular front-end\n react: '#E3F2FD', // blue - React front-end\n browser: '#EDE7F6', // purple - browser (front-end base env)\n express: '#E8F5E9', // green - Express / server side\n node: '#FFF9C4', // yellow - node (server base env)\n};\n\nconst DEFAULT_FRAMEWORK_COLOR = '#F5F5F5'; // grey - unknown/empty env set\n\n/**\n * Directory (repo-relative) that the committed architecture HTML lives in.\n * Node click-through links are computed relative to this so they resolve when\n * the file is opened straight from the checkout.\n */\nconst ARCH_OUTPUT_DIR = 'architecture';\n\nexport class VisualizationPaths {\n htmlPath: string;\n\n constructor(htmlPath: string) {\n this.htmlPath = htmlPath;\n }\n}\n\nexport class GraphVisualizer {\n private readonly names = new GraphNames();\n private readonly responsibilities = new ResponsibilitiesRenderer();\n\n /**\n * Fill color for an env set — the color of the first env in the set that has\n * a known color, else the default.\n */\n private frameworkColor(frameworks: string[]): string {\n for (const env of frameworks) {\n const color = FRAMEWORK_COLORS[env];\n if (color !== undefined) return color;\n }\n return DEFAULT_FRAMEWORK_COLOR;\n }\n\n /**\n * Role border styling — fill stays keyed on framework; the border shows a\n * project's ROLE at a glance. Server and client are the top-level runnable\n * nodes, so they get bold, colored borders to stand out:\n * server → thick GREEN border (a runnable server app)\n * client → thick RED border (a client app, e.g. angular)\n * designed-lib → bold border (a library with a generated @DocumentDesign design)\n * lib / other → plain thin border\n */\n private roleBorderAttrs(role: string): string {\n if (role === 'server') return ', color=\"green\", penwidth=3';\n if (role === 'client') return ', color=\"red\", penwidth=3';\n if (role === 'api-lib') return ', color=\"#EF6C00\", penwidth=2';\n if (role === 'designed-lib') return ', penwidth=2';\n return '';\n }\n\n /**\n * Edge styling by API-relation kind (why the edge exists):\n * implements → DASHED (a controller serves this api-lib's contract)\n * uses → SOLID blue, thicker (a generated client calls it)\n * uses-implements → DASHED purple, thicker (does both — implements some\n * contracts of the api-lib, uses others)\n * plain lib (none) → the default thin solid arrow, unchanged.\n * `kind` is undefined for every non-api-lib dependency edge.\n */\n private edgeAttrs(kind: ApiRelationKind | undefined): string {\n if (kind === 'implements') return ' [style=dashed]';\n if (kind === 'uses') return ' [color=\"#1976d2\", penwidth=2]';\n if (kind === 'uses-implements') return ' [style=dashed, color=\"#8e24aa\", penwidth=2]';\n return '';\n }\n\n /**\n * Click-through href for a node: the project's committed design.html, made\n * relative to architecture/dependencies.html. Returns null when the project\n * has no generated DI design (no design.json → no clickable design page).\n */\n private designHtmlHref(designFile: string | undefined): string | null {\n if (!designFile) return null;\n const designHtml = designFile.replace(/design\\.json$/, 'design.html');\n return path.posix.relative(ARCH_OUTPUT_DIR, designHtml);\n }\n\n /**\n * Generate Graphviz DOT format from the graph\n */\n generateDot(graph: EnhancedGraph, title: string = 'Monorepo Dependency Architecture'): string {\n let dot = 'digraph Architecture {\\n';\n dot += ' rankdir=TB;\\n';\n dot += ' node [shape=box, style=filled, fontname=\"Arial\"];\\n';\n dot += ' edge [fontname=\"Arial\"];\\n\\n';\n\n // Group projects by level\n const levels: Record<number, string[]> = {};\n for (const project of Object.keys(graph)) {\n const level = graph[project].level;\n if (!levels[level]) levels[level] = [];\n levels[level].push(project);\n }\n\n dot += this.dotNodes(graph);\n dot += '\\n';\n\n // Create same-rank subgraphs for each level\n for (const projects of Object.values(levels)) {\n dot += ` { rank=same; `;\n for (const p of projects) {\n dot += `\"${this.names.getShortName(p)}\"; `;\n }\n dot += '}\\n';\n }\n\n dot += '\\n';\n dot += this.dotEdges(graph);\n\n dot += '\\n labelloc=\"t\";\\n';\n dot += ` label=\"${title}\\\\n(from architecture/dependencies.json)\";\\n`;\n dot += ' fontsize=20;\\n';\n dot += '}\\n';\n\n return dot;\n }\n\n // Node lines: fill colored by framework env set (libType), border shaped by\n // role; the label shows the env set + role (e.g. [browser, node] · server). A\n // node with a generated DI design also gets a URL so the rendered SVG box is\n // clickable — it opens that project's committed design.html in a new tab.\n private dotNodes(graph: EnhancedGraph): string {\n let dot = '';\n for (const project of Object.keys(graph)) {\n const info = graph[project];\n const shortName = this.names.getShortName(project);\n const frameworks = info.framework ?? [];\n const role = info.role ?? 'lib';\n const color = this.frameworkColor(frameworks);\n const border = this.roleBorderAttrs(role);\n const href = this.designHtmlHref(info.designFile);\n const link = href ? `, URL=\"${href}\", target=\"_blank\"` : '';\n const envSet = `[${frameworks.join(', ')}]`;\n const labelMeta = `L${info.level} · ${envSet} · ${role}`;\n dot += ` \"${shortName}\" [fillcolor=\"${color}\"${border}${link}, label=\"${shortName}\\\\n(${labelMeta})\"];\\n`;\n }\n return dot;\n }\n\n // Edge lines (dependencies). An edge to an api-lib is styled by WHY it exists\n // (implements/uses/uses-implements, from apiRelations); every other dependency\n // keeps the default plain arrow.\n private dotEdges(graph: EnhancedGraph): string {\n let dot = '';\n for (const project of Object.keys(graph)) {\n const shortName = this.names.getShortName(project);\n const info = graph[project];\n for (const dep of info.dependsOn || []) {\n const attrs = this.edgeAttrs(info.apiRelations?.[dep]?.kind);\n dot += ` \"${shortName}\" -> \"${this.names.getShortName(dep)}\"${attrs};\\n`;\n }\n }\n return dot;\n }\n\n /**\n * Generate interactive HTML with embedded SVG using viz.js\n */\n generateHTML(\n dot: string,\n title: string = 'Monorepo Dependency Architecture',\n lockControl: string = '',\n responsibilitiesHtml: string = ''\n ): string {\n const styles = this.styles();\n const legend = this.legend();\n const script = this.script(dot);\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>${title}</title>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/viz.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/full.render.js\"></script>\n <style>${styles}</style>\n</head>\n<body>\n <h1>${title}</h1>\n <p class=\"hint\">💡 Click any box with a generated DI design to open its <strong>design.html</strong> (what the AI sees inside that project).</p>\n <p class=\"hint\">🔦 <strong>Hover any box</strong> to trace its <em>entire</em> dependency chain — every ancestor above it (all the way up) <em>and</em> every dependency below it (all the way down), with all the boxes and lines between — while the rest of the graph dims so you can follow one box at a glance.</p>\n ${legend}\n ${lockControl}\n <div id=\"graph\"></div>\n ${responsibilitiesHtml}\n <script>${script}</script>\n</body>\n</html>`;\n }\n\n /**\n * The lock control (a single-select dropdown, rendered below the legend).\n * Picking a module LOCKS the graph into that box's hover view — its full\n * ancestor + descendant chain stays lit while everything else stays dimmed —\n * and narrows the responsibilities list below the graph to just that chain.\n * The first option, \"All\", is the default and clears the lock. Hover still\n * works on top of a lock; leaving a box returns to the locked view.\n *\n * Options are ordered by level DESCENDING to match the responsibilities cards.\n */\n lockControl(graph: EnhancedGraph): string {\n const projects = Object.keys(graph);\n projects.sort((a: string, b: string): number => {\n const levelDiff = graph[b].level - graph[a].level;\n if (levelDiff !== 0) return levelDiff;\n return a.localeCompare(b);\n });\n let options = '';\n for (const project of projects) {\n const shortName = this.names.getShortName(project);\n options += `<option value=\"${shortName}\">L${graph[project].level} · ${shortName}</option>`;\n }\n return `<div class=\"wp-lock-control\">\n <label for=\"wp-lock\">🔒 Lock a box (dim the rest & filter responsibilities):</label>\n <select id=\"wp-lock\"><option value=\"\">All (no lock)</option>${options}</select>\n </div>`;\n }\n\n private styles(): string {\n return `\n body { margin: 0; padding: 20px; font-family: Arial, sans-serif; background: #f5f5f5; }\n h1 { text-align: center; color: #333; }\n .hint { text-align: center; color: #555; margin: 0 0 16px; }\n /* viz.js renders node URLs as <a> — only boxes with a design.html get\n * one, so a:hover is a clickable-only signal. Make it pop clearly: a\n * thicker border PLUS a blue glow lift the box off the page, so it is\n * obvious which boxes you can click into vs. which you cannot. (A plain\n * stroke bump is invisible on server/client boxes, whose resting border\n * is already thick.) */\n #graph a { cursor: pointer; }\n #graph a polygon,\n #graph a ellipse { transition: stroke-width 0.12s ease, filter 0.12s ease; }\n #graph a:hover polygon,\n #graph a:hover ellipse {\n stroke: #1976d2;\n stroke-width: 5;\n filter: drop-shadow(0 0 6px rgba(25, 118, 210, 0.85));\n }\n /* Hover-highlight (wired up in JS after viz.js renders). Hovering a node\n * adds .wp-dim to the <svg> and .wp-focus/.wp-neighbor/.wp-hl to the\n * connected box, its neighbors, and its edges. We ONLY dim: the connected\n * subgraph keeps its exact normal look (full opacity), the rest recedes.\n * The un-dim rules repeat \"svg.wp-dim\" so they out-specify the dim rule\n * (which has an extra type selector) — else the subgraph stays dimmed. */\n #graph .node, #graph .edge { transition: opacity 0.12s ease; }\n #graph svg.wp-dim .node,\n #graph svg.wp-dim .edge { opacity: 0.15; }\n #graph svg.wp-dim .node.wp-focus,\n #graph svg.wp-dim .node.wp-neighbor,\n #graph svg.wp-dim .edge.wp-hl { opacity: 1; }\n #graph {\n text-align: center;\n background: white;\n padding: 20px;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n }\n .legend {\n margin: 20px auto;\n max-width: 1100px;\n padding: 15px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n }\n .legend h2 { margin-top: 0; }\n .legend-item { margin: 8px 0; }\n .legend-box {\n display: inline-block;\n width: 20px;\n height: 20px;\n border: 1px solid #ccc;\n margin-right: 10px;\n vertical-align: middle;\n }\n ${this.componentStyles()}\n `;\n }\n\n // Styles for the lock dropdown and the responsibilities card list below the\n // graph. Split out of styles() to keep each method within the line limit.\n private componentStyles(): string {\n return `\n /* The architecture graph is very wide, so lay the legend out as three\n * side-by-side columns (fill / border / edge) instead of one tall\n * column — it keeps the legend short next to the wide graph, and\n * collapses back to a single column on narrow viewports. */\n .legend-columns {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 28px;\n align-items: start;\n }\n .legend-col h3 { margin: 0 0 8px; color: #333; font-size: 15px; }\n @media (max-width: 800px) { .legend-columns { grid-template-columns: 1fr; } }\n .wp-lock-control {\n max-width: 600px;\n margin: 0 auto 16px;\n padding: 12px 15px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n text-align: center;\n }\n .wp-lock-control label { font-weight: bold; color: #333; margin-right: 8px; }\n .wp-lock-control select { font-size: 14px; padding: 4px 8px; }\n #wp-responsibilities { max-width: 900px; margin: 24px auto 0; }\n #wp-responsibilities h2 { color: #333; }\n .wp-resp-card {\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n margin: 10px 0;\n padding: 10px 15px;\n }\n .wp-resp-card > summary { cursor: pointer; color: #333; }\n .wp-resp-level {\n display: inline-block;\n min-width: 26px;\n padding: 1px 6px;\n margin-right: 6px;\n border-radius: 4px;\n background: #eef;\n font-size: 12px;\n font-weight: bold;\n text-align: center;\n }\n .wp-resp-body { margin-top: 8px; color: #444; }\n .wp-resp-body code {\n background: #f2f2f2;\n padding: 1px 4px;\n border-radius: 3px;\n font-family: monospace;\n }\n .wp-hidden { display: none; }`;\n }\n\n // The legend is laid out in three side-by-side columns (fill / border /\n // edge) so it stays short next to the very wide architecture graph. Each\n // column's rows come from a helper below to keep this method within the line\n // limit; the footnote spans the full width beneath the columns.\n private legend(): string {\n return `<div class=\"legend\">\n <h2>Legend</h2>\n <div class=\"legend-columns\">\n <div class=\"legend-col\">\n <h3>Fill = framework (libType)</h3>\n ${this.fillItems()}\n </div>\n <div class=\"legend-col\">\n <h3>Border = role</h3>\n ${this.borderItems()}\n </div>\n <div class=\"legend-col\">\n <h3>Edge lines — <em>why</em> a project depends on an api-lib</h3>\n ${this.edgeItems()}\n </div>\n </div>\n <div class=\"legend-item\" style=\"margin-top: 15px;\">\n <em>Each node label shows its dependency level (L#), its framework env set (e.g. [browser, node]), and its role. Rows are laid out by level (top = no dependencies), with the deepest libraries at the bottom. Transitive dependencies are allowed but not shown.</em>\n </div>\n </div>`;\n }\n\n // Column 1 — fill color keyed on the project's framework (libType) env set.\n private fillItems(): string {\n return `<div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #FCE4EC;\"></span>\n <strong>angular:</strong> Angular front-end\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #E3F2FD;\"></span>\n <strong>react:</strong> React front-end\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #EDE7F6;\"></span>\n <strong>browser:</strong> browser front-end base env\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #E8F5E9;\"></span>\n <strong>express:</strong> Express / server side\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #FFF9C4;\"></span>\n <strong>node:</strong> node server base env\n </div>`;\n }\n\n // Column 2 — border style keyed on the project's role.\n private borderItems(): string {\n return `<div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 3px solid green;\"></span>\n <strong>server:</strong> runnable server app (thick green border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 3px solid red;\"></span>\n <strong>client:</strong> client app, e.g. angular (thick red border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 2px solid #333;\"></span>\n <strong>designed-lib:</strong> library with a generated @DocumentDesign design (bold border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 1px solid #ccc;\"></span>\n <strong>lib:</strong> plain library, no generated design (thin border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 2px solid #EF6C00;\"></span>\n <strong>api-lib:</strong> API-contract library (defines <code>@ApiPath</code>/<code>@Rpc</code>/<code>@PubSub</code> <code>*Api</code> classes)\n </div>`;\n }\n\n // Column 3 — edge line style keyed on WHY a project depends on an api-lib.\n private edgeItems(): string {\n return `<div class=\"legend-item\">\n <svg width=\"42\" height=\"12\" style=\"vertical-align: middle; margin-right: 10px;\"><line x1=\"0\" y1=\"6\" x2=\"42\" y2=\"6\" stroke=\"#333\" stroke-width=\"2\" stroke-dasharray=\"5,3\"/></svg>\n <strong>implements:</strong> serves the API — NOTE: this is a build-dependency diagram, so a UML <em>implements</em> arrow can't be used; we use a dashed line to signal a build dep, because this server implements the api and the api is built first, then this server after.\n </div>\n <div class=\"legend-item\">\n <svg width=\"42\" height=\"12\" style=\"vertical-align: middle; margin-right: 10px;\"><line x1=\"0\" y1=\"6\" x2=\"42\" y2=\"6\" stroke=\"#1976d2\" stroke-width=\"2\"/></svg>\n <strong>uses:</strong> calls the API (generates an rpc/pubsub client via <code>createRpcClient</code>/<code>createPubSubClient</code>)\n </div>\n <div class=\"legend-item\">\n <svg width=\"42\" height=\"12\" style=\"vertical-align: middle; margin-right: 10px;\"><line x1=\"0\" y1=\"6\" x2=\"42\" y2=\"6\" stroke=\"#8e24aa\" stroke-width=\"2\" stroke-dasharray=\"5,3\"/></svg>\n <strong>uses-implements:</strong> both — implements some of the api-lib's contracts, uses others\n </div>\n <div class=\"legend-item\">\n <svg width=\"42\" height=\"12\" style=\"vertical-align: middle; margin-right: 10px;\"><line x1=\"0\" y1=\"6\" x2=\"42\" y2=\"6\" stroke=\"#999\" stroke-width=\"1.5\"/></svg>\n <strong>plain dependency:</strong> a normal library import (no API relationship)\n </div>`;\n }\n\n /**\n * The page script. The browser code lives in graph-visualizer.client.js (a\n * plain .js asset, NOT a TS template literal) so its dim/highlight/lock\n * functions can be ordinary browser functions — the TS lint rules that scan\n * .ts template strings would otherwise forbid them, and browser JS cannot\n * carry TS return annotations. We inline it and substitute the DOT.\n */\n private script(dot: string): string {\n const clientJs = fs.readFileSync(path.join(__dirname, 'graph-visualizer.client.js'), 'utf-8');\n return clientJs.split('__DOT__').join(JSON.stringify(dot));\n }\n\n /**\n * Write the committed architecture visualization to\n * architecture/dependencies.html, next to dependencies.json.\n *\n * This is a checked-in artifact, regenerated deterministically by\n * architecture:generate so the boxes stay clickable into each project's\n * design.html. The DOT is embedded in the HTML (rendered client-side by\n * viz.js). Output is deterministic (sorted graph in → same bytes out) so git\n * only shows a diff when the architecture actually changed.\n */\n writeVisualization(\n graph: EnhancedGraph,\n workspaceRoot: string,\n title: string = 'Monorepo Dependency Architecture'\n ): VisualizationPaths {\n const outputDir = path.join(workspaceRoot, ARCH_OUTPUT_DIR);\n\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const lockControl = this.lockControl(graph);\n const responsibilities = this.responsibilities.generateSection(graph, workspaceRoot);\n const html = this.generateHTML(this.generateDot(graph, title), title, lockControl, responsibilities);\n const htmlPath = path.join(outputDir, 'dependencies.html');\n fs.writeFileSync(htmlPath, html, 'utf-8');\n\n return new VisualizationPaths(htmlPath);\n }\n\n /**\n * Open the HTML visualization in the default browser\n */\n openVisualization(htmlPath: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const platform = process.platform;\n let openCommand: string;\n\n if (platform === 'darwin') {\n openCommand = `open \"${htmlPath}\"`;\n } else if (platform === 'win32') {\n openCommand = `start \"\" \"${htmlPath}\"`;\n } else {\n openCommand = `xdg-open \"${htmlPath}\"`;\n }\n\n execSync(openCommand, { stdio: 'ignore' });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n console.warn(`⚠️ Could not open browser: ${error.message}`);\n return false;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"graph-visualizer.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/graph-visualizer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;;AAEH,+CAAyB;AACzB,mDAA6B;AAC7B,iDAAyC;AAGzC,+CAA2C;AAC3C,qEAAoE;AACpE,wCAAqC;AAErC;;;;GAIG;AACH,MAAM,gBAAgB,GAA2B;IAC7C,OAAO,EAAE,SAAS,EAAE,6BAA6B;IACjD,KAAK,EAAE,SAAS,EAAE,2BAA2B;IAC7C,OAAO,EAAE,SAAS,EAAE,wCAAwC;IAC5D,OAAO,EAAE,SAAS,EAAE,iCAAiC;IACrD,IAAI,EAAE,SAAS,EAAE,kCAAkC;CACtD,CAAC;AAEF,MAAM,uBA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AED;;OAEG;IACH,iBAAiB,CAAC,QAAgB;QAC9B,8DAA8D;QAC9D,IAAI,CAAC;YACD,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;YAClC,IAAI,WAAmB,CAAC;YAExB,IAAI,QAAQ,KAAK,QAAQ,EAAE,CAAC;gBACxB,WAAW,GAAG,SAAS,QAAQ,GAAG,CAAC;YACvC,CAAC;iBAAM,IAAI,QAAQ,KAAK,OAAO,EAAE,CAAC;gBAC9B,WAAW,GAAG,aAAa,QAAQ,GAAG,CAAC;YAC3C,CAAC;iBAAM,CAAC;gBACJ,WAAW,GAAG,aAAa,QAAQ,GAAG,CAAC;YAC3C,CAAC;YAED,IAAA,wBAAQ,EAAC,WAAW,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;YAC3C,OAAO,IAAI,CAAC;QAChB,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,OAAO,CAAC,IAAI,CAAC,+BAA+B,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YAC7D,OAAO,KAAK,CAAC;QACjB,CAAC;IACL,CAAC;CACJ;AA9dD,0CA8dC","sourcesContent":["/**\n * Graph Visualizer\n *\n * Generates visual representations of the architecture graph:\n * - DOT format (for Graphviz)\n * - Interactive HTML (using viz.js)\n *\n * All behavior lives on the injectable GraphVisualizer class so webpieces DI +\n * @DocumentDesign can wire it — module-scope functions are a dead end the DI\n * graph can't reach.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport type { EnhancedGraph } from './graph-sorter';\nimport type { ApiRelationKind } from './api-usage/api-relations';\nimport { GraphNames } from './graph-names';\nimport { ResponsibilitiesRenderer } from './graph-responsibilities';\nimport { toError } from '../toError';\n\n/**\n * Framework (libType) colors for visualization — nodes are filled by the FIRST\n * env in their set that has a color, so it is obvious at a glance which side a\n * project targets. A project's full env set is shown in the label.\n */\nconst FRAMEWORK_COLORS: Record<string, string> = {\n angular: '#FCE4EC', // pink - Angular front-end\n react: '#E3F2FD', // blue - React front-end\n browser: '#EDE7F6', // purple - browser (front-end base env)\n express: '#E8F5E9', // green - Express / server side\n node: '#FFF9C4', // yellow - node (server base env)\n};\n\nconst DEFAULT_FRAMEWORK_COLOR = '#F5F5F5'; // grey - unknown/empty env set\n\n/**\n * Directory (repo-relative) that the committed architecture HTML lives in.\n * Node click-through links are computed relative to this so they resolve when\n * the file is opened straight from the checkout.\n */\nconst ARCH_OUTPUT_DIR = 'architecture';\n\nexport class VisualizationPaths {\n htmlPath: string;\n\n constructor(htmlPath: string) {\n this.htmlPath = htmlPath;\n }\n}\n\nexport class GraphVisualizer {\n private readonly names = new GraphNames();\n private readonly responsibilities = new ResponsibilitiesRenderer();\n\n /**\n * Fill color for an env set — the color of the first env in the set that has\n * a known color, else the default.\n */\n private frameworkColor(frameworks: string[]): string {\n for (const env of frameworks) {\n const color = FRAMEWORK_COLORS[env];\n if (color !== undefined) return color;\n }\n return DEFAULT_FRAMEWORK_COLOR;\n }\n\n /**\n * Role border styling — fill stays keyed on framework; the border shows a\n * project's ROLE at a glance. Server and client are the top-level runnable\n * nodes, so they get bold, colored borders to stand out:\n * server → thick GREEN border (a runnable server app)\n * client → thick RED border (a client app, e.g. angular)\n * designed-lib → bold border (a library with a generated @DocumentDesign design)\n * lib / other → plain thin border\n */\n private roleBorderAttrs(role: string): string {\n if (role === 'server') return ', color=\"green\", penwidth=3';\n if (role === 'client') return ', color=\"red\", penwidth=3';\n if (role === 'api-lib') return ', color=\"#EF6C00\", penwidth=2';\n if (role === 'designed-lib') return ', penwidth=2';\n return '';\n }\n\n /**\n * Edge styling by API-relation kind (why the edge exists):\n * implements → BLACK dashed (a controller serves this api-lib's contract)\n * uses → BLACK solid (a generated client calls it) — same as a\n * plain library import, since a plain dependency IS a use.\n * uses-implements → BLUE dashed, thicker (does both — implements some\n * contracts of the api-lib, uses others)\n * plain lib (none) → the default thin black solid arrow, unchanged.\n * `kind` is undefined for every non-api-lib dependency edge.\n */\n private edgeAttrs(kind: ApiRelationKind | undefined): string {\n if (kind === 'implements') return ' [style=dashed]';\n if (kind === 'uses-implements') return ' [style=dashed, color=\"#1976d2\", penwidth=2]';\n return '';\n }\n\n /**\n * Click-through href for a node: the project's committed design.html, made\n * relative to architecture/dependencies.html. Returns null when the project\n * has no generated DI design (no design.json → no clickable design page).\n */\n private designHtmlHref(designFile: string | undefined): string | null {\n if (!designFile) return null;\n const designHtml = designFile.replace(/design\\.json$/, 'design.html');\n return path.posix.relative(ARCH_OUTPUT_DIR, designHtml);\n }\n\n /**\n * Generate Graphviz DOT format from the graph\n */\n generateDot(graph: EnhancedGraph, title: string = 'Monorepo Dependency Architecture'): string {\n let dot = 'digraph Architecture {\\n';\n dot += ' rankdir=TB;\\n';\n dot += ' node [shape=box, style=filled, fontname=\"Arial\"];\\n';\n dot += ' edge [fontname=\"Arial\"];\\n\\n';\n\n // Group projects by level\n const levels: Record<number, string[]> = {};\n for (const project of Object.keys(graph)) {\n const level = graph[project].level;\n if (!levels[level]) levels[level] = [];\n levels[level].push(project);\n }\n\n dot += this.dotNodes(graph);\n dot += '\\n';\n\n // Create same-rank subgraphs for each level\n for (const projects of Object.values(levels)) {\n dot += ` { rank=same; `;\n for (const p of projects) {\n dot += `\"${this.names.getShortName(p)}\"; `;\n }\n dot += '}\\n';\n }\n\n dot += '\\n';\n dot += this.dotEdges(graph);\n\n dot += '\\n labelloc=\"t\";\\n';\n dot += ` label=\"${title}\\\\n(from architecture/dependencies.json)\";\\n`;\n dot += ' fontsize=20;\\n';\n dot += '}\\n';\n\n return dot;\n }\n\n // Node lines: fill colored by framework env set (libType), border shaped by\n // role; the label shows the env set + role (e.g. [browser, node] · server). A\n // node with a generated DI design also gets a URL so the rendered SVG box is\n // clickable — it opens that project's committed design.html in a new tab.\n private dotNodes(graph: EnhancedGraph): string {\n let dot = '';\n for (const project of Object.keys(graph)) {\n const info = graph[project];\n const shortName = this.names.getShortName(project);\n const frameworks = info.framework ?? [];\n const role = info.role ?? 'lib';\n const color = this.frameworkColor(frameworks);\n const border = this.roleBorderAttrs(role);\n const href = this.designHtmlHref(info.designFile);\n const link = href ? `, URL=\"${href}\", target=\"_blank\"` : '';\n const envSet = `[${frameworks.join(', ')}]`;\n const labelMeta = `L${info.level} · ${envSet} · ${role}`;\n dot += ` \"${shortName}\" [fillcolor=\"${color}\"${border}${link}, label=\"${shortName}\\\\n(${labelMeta})\"];\\n`;\n }\n return dot;\n }\n\n // Edge lines (dependencies). An edge to an api-lib is styled by WHY it exists\n // (implements/uses/uses-implements, from apiRelations); every other dependency\n // keeps the default plain arrow.\n private dotEdges(graph: EnhancedGraph): string {\n let dot = '';\n for (const project of Object.keys(graph)) {\n const shortName = this.names.getShortName(project);\n const info = graph[project];\n for (const dep of info.dependsOn || []) {\n const attrs = this.edgeAttrs(info.apiRelations?.[dep]?.kind);\n dot += ` \"${shortName}\" -> \"${this.names.getShortName(dep)}\"${attrs};\\n`;\n }\n }\n return dot;\n }\n\n /**\n * Generate interactive HTML with embedded SVG using viz.js\n */\n generateHTML(\n dot: string,\n title: string = 'Monorepo Dependency Architecture',\n lockControl: string = '',\n responsibilitiesHtml: string = ''\n ): string {\n const styles = this.styles();\n const legend = this.legend();\n const script = this.script(dot);\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>${title}</title>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/viz.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/full.render.js\"></script>\n <style>${styles}</style>\n</head>\n<body>\n <h1>${title}</h1>\n <p class=\"hint\">💡 Click any box with a generated DI design to open its <strong>design.html</strong> (what the AI sees inside that project).</p>\n <p class=\"hint\">🔦 <strong>Hover any box</strong> to trace its <em>entire</em> dependency chain — every ancestor above it (all the way up) <em>and</em> every dependency below it (all the way down), with all the boxes and lines between — while the rest of the graph dims so you can follow one box at a glance.</p>\n ${legend}\n ${lockControl}\n <div id=\"graph\"></div>\n ${responsibilitiesHtml}\n <script>${script}</script>\n</body>\n</html>`;\n }\n\n /**\n * The lock control (a single-select dropdown, rendered below the legend).\n * Picking a module LOCKS the graph into that box's hover view — its full\n * ancestor + descendant chain stays lit while everything else stays dimmed —\n * and narrows the responsibilities list below the graph to just that chain.\n * The first option, \"All\", is the default and clears the lock. Hover still\n * works on top of a lock; leaving a box returns to the locked view.\n *\n * Options are ordered by level DESCENDING to match the responsibilities cards.\n */\n lockControl(graph: EnhancedGraph): string {\n const projects = Object.keys(graph);\n projects.sort((a: string, b: string): number => {\n const levelDiff = graph[b].level - graph[a].level;\n if (levelDiff !== 0) return levelDiff;\n return a.localeCompare(b);\n });\n let options = '';\n for (const project of projects) {\n const shortName = this.names.getShortName(project);\n options += `<option value=\"${shortName}\">L${graph[project].level} · ${shortName}</option>`;\n }\n return `<div class=\"wp-lock-control\">\n <label for=\"wp-lock\">🔒 Lock a box (dim the rest & filter responsibilities):</label>\n <select id=\"wp-lock\"><option value=\"\">All (no lock)</option>${options}</select>\n </div>`;\n }\n\n private styles(): string {\n return `\n body { margin: 0; padding: 20px; font-family: Arial, sans-serif; background: #f5f5f5; }\n h1 { text-align: center; color: #333; }\n .hint { text-align: center; color: #555; margin: 0 0 16px; }\n /* viz.js renders node URLs as <a> — only boxes with a design.html get\n * one, so a:hover is a clickable-only signal. Make it pop clearly: a\n * thicker border PLUS a blue glow lift the box off the page, so it is\n * obvious which boxes you can click into vs. which you cannot. (A plain\n * stroke bump is invisible on server/client boxes, whose resting border\n * is already thick.) */\n #graph a { cursor: pointer; }\n #graph a polygon,\n #graph a ellipse { transition: stroke-width 0.12s ease, filter 0.12s ease; }\n #graph a:hover polygon,\n #graph a:hover ellipse {\n stroke: #1976d2;\n stroke-width: 5;\n filter: drop-shadow(0 0 6px rgba(25, 118, 210, 0.85));\n }\n /* Hover-highlight (wired up in JS after viz.js renders). Hovering a node\n * adds .wp-dim to the <svg> and .wp-focus/.wp-neighbor/.wp-hl to the\n * connected box, its neighbors, and its edges. We ONLY dim: the connected\n * subgraph keeps its exact normal look (full opacity), the rest recedes.\n * The un-dim rules repeat \"svg.wp-dim\" so they out-specify the dim rule\n * (which has an extra type selector) — else the subgraph stays dimmed. */\n #graph .node, #graph .edge { transition: opacity 0.12s ease; }\n #graph svg.wp-dim .node,\n #graph svg.wp-dim .edge { opacity: 0.15; }\n #graph svg.wp-dim .node.wp-focus,\n #graph svg.wp-dim .node.wp-neighbor,\n #graph svg.wp-dim .edge.wp-hl { opacity: 1; }\n #graph {\n text-align: center;\n background: white;\n padding: 20px;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n }\n .legend {\n margin: 20px auto;\n max-width: 1100px;\n padding: 15px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n }\n .legend h2 { margin-top: 0; }\n .legend-item { margin: 8px 0; }\n .legend-box {\n display: inline-block;\n width: 20px;\n height: 20px;\n border: 1px solid #ccc;\n margin-right: 10px;\n vertical-align: middle;\n }\n ${this.componentStyles()}\n `;\n }\n\n // Styles for the lock dropdown and the responsibilities card list below the\n // graph. Split out of styles() to keep each method within the line limit.\n private componentStyles(): string {\n return `\n /* The architecture graph is very wide, so lay the legend out as three\n * side-by-side columns (fill / border / edge) instead of one tall\n * column — it keeps the legend short next to the wide graph, and\n * collapses back to a single column on narrow viewports. */\n .legend-columns {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 28px;\n align-items: start;\n }\n .legend-col h3 { margin: 0 0 8px; color: #333; font-size: 15px; }\n @media (max-width: 800px) { .legend-columns { grid-template-columns: 1fr; } }\n .wp-lock-control {\n max-width: 600px;\n margin: 0 auto 16px;\n padding: 12px 15px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n text-align: center;\n }\n .wp-lock-control label { font-weight: bold; color: #333; margin-right: 8px; }\n .wp-lock-control select { font-size: 14px; padding: 4px 8px; }\n #wp-responsibilities { max-width: 900px; margin: 24px auto 0; }\n #wp-responsibilities h2 { color: #333; }\n .wp-resp-card {\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n margin: 10px 0;\n padding: 10px 15px;\n }\n .wp-resp-card > summary { cursor: pointer; color: #333; }\n .wp-resp-level {\n display: inline-block;\n min-width: 26px;\n padding: 1px 6px;\n margin-right: 6px;\n border-radius: 4px;\n background: #eef;\n font-size: 12px;\n font-weight: bold;\n text-align: center;\n }\n .wp-resp-body { margin-top: 8px; color: #444; }\n .wp-resp-body code {\n background: #f2f2f2;\n padding: 1px 4px;\n border-radius: 3px;\n font-family: monospace;\n }\n .wp-hidden { display: none; }`;\n }\n\n // The legend is laid out in three side-by-side columns (fill / border /\n // edge) so it stays short next to the very wide architecture graph. Each\n // column's rows come from a helper below to keep this method within the line\n // limit; the footnote spans the full width beneath the columns.\n private legend(): string {\n return `<div class=\"legend\">\n <h2>Legend</h2>\n <div class=\"legend-columns\">\n <div class=\"legend-col\">\n <h3>Fill = framework (libType)</h3>\n ${this.fillItems()}\n </div>\n <div class=\"legend-col\">\n <h3>Border = role</h3>\n ${this.borderItems()}\n </div>\n <div class=\"legend-col\">\n <h3>Edge lines — <em>why</em> a project depends on an api-lib</h3>\n ${this.edgeItems()}\n </div>\n </div>\n <div class=\"legend-item\" style=\"margin-top: 15px;\">\n <em>Each node label shows its dependency level (L#), its framework env set (e.g. [browser, node]), and its role. Rows are laid out by level (top = no dependencies), with the deepest libraries at the bottom. Transitive dependencies are allowed but not shown.</em>\n </div>\n </div>`;\n }\n\n // Column 1 — fill color keyed on the project's framework (libType) env set.\n private fillItems(): string {\n return `<div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #FCE4EC;\"></span>\n <strong>angular:</strong> Angular front-end\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #E3F2FD;\"></span>\n <strong>react:</strong> React front-end\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #EDE7F6;\"></span>\n <strong>browser:</strong> browser front-end base env\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #E8F5E9;\"></span>\n <strong>express:</strong> Express / server side\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"background: #FFF9C4;\"></span>\n <strong>node:</strong> node server base env\n </div>`;\n }\n\n // Column 2 — border style keyed on the project's role.\n private borderItems(): string {\n return `<div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 3px solid green;\"></span>\n <strong>server:</strong> runnable server app (thick green border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 3px solid red;\"></span>\n <strong>client:</strong> client app, e.g. angular (thick red border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 2px solid #333;\"></span>\n <strong>designed-lib:</strong> library with a generated @DocumentDesign design (bold border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 1px solid #ccc;\"></span>\n <strong>lib:</strong> plain library, no generated design (thin border)\n </div>\n <div class=\"legend-item\">\n <span class=\"legend-box\" style=\"border: 2px solid #EF6C00;\"></span>\n <strong>api-lib:</strong> API-contract library (defines <code>@ApiPath</code>/<code>@Rpc</code>/<code>@PubSub</code> <code>*Api</code> classes)\n </div>`;\n }\n\n // Column 3 — edge line style keyed on WHY a project depends on an api-lib.\n private edgeItems(): string {\n return `<div class=\"legend-item\">\n <svg width=\"42\" height=\"12\" style=\"vertical-align: middle; margin-right: 10px;\"><line x1=\"0\" y1=\"6\" x2=\"42\" y2=\"6\" stroke=\"#333\" stroke-width=\"2\"/></svg>\n <strong>uses:</strong> calls the API (generates an rpc/pubsub client via <code>createRpcClient</code>/<code>createPubSubClient</code>) — also covers a plain library import, since a plain dependency is just a use.\n </div>\n <div class=\"legend-item\">\n <svg width=\"42\" height=\"12\" style=\"vertical-align: middle; margin-right: 10px;\"><line x1=\"0\" y1=\"6\" x2=\"42\" y2=\"6\" stroke=\"#333\" stroke-width=\"2\" stroke-dasharray=\"5,3\"/></svg>\n <strong>implements:</strong> serves the API — NOTE: this is a build-dependency diagram, so a UML <em>implements</em> arrow can't be used; we use a dashed line to signal a build dep, because this server implements the api and the api is built first, then this server after.\n </div>\n <div class=\"legend-item\">\n <svg width=\"42\" height=\"12\" style=\"vertical-align: middle; margin-right: 10px;\"><line x1=\"0\" y1=\"6\" x2=\"42\" y2=\"6\" stroke=\"#1976d2\" stroke-width=\"2\" stroke-dasharray=\"5,3\"/></svg>\n <strong>uses/implements:</strong> both — implements some of the api-lib's contracts, uses others\n </div>`;\n }\n\n /**\n * The page script. The browser code lives in graph-visualizer.client.js (a\n * plain .js asset, NOT a TS template literal) so its dim/highlight/lock\n * functions can be ordinary browser functions — the TS lint rules that scan\n * .ts template strings would otherwise forbid them, and browser JS cannot\n * carry TS return annotations. We inline it and substitute the DOT.\n */\n private script(dot: string): string {\n const clientJs = fs.readFileSync(path.join(__dirname, 'graph-visualizer.client.js'), 'utf-8');\n return clientJs.split('__DOT__').join(JSON.stringify(dot));\n }\n\n /**\n * Write the committed architecture visualization to\n * architecture/dependencies.html, next to dependencies.json.\n *\n * This is a checked-in artifact, regenerated deterministically by\n * architecture:generate so the boxes stay clickable into each project's\n * design.html. The DOT is embedded in the HTML (rendered client-side by\n * viz.js). Output is deterministic (sorted graph in → same bytes out) so git\n * only shows a diff when the architecture actually changed.\n */\n writeVisualization(\n graph: EnhancedGraph,\n workspaceRoot: string,\n title: string = 'Monorepo Dependency Architecture'\n ): VisualizationPaths {\n const outputDir = path.join(workspaceRoot, ARCH_OUTPUT_DIR);\n\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const lockControl = this.lockControl(graph);\n const responsibilities = this.responsibilities.generateSection(graph, workspaceRoot);\n const html = this.generateHTML(this.generateDot(graph, title), title, lockControl, responsibilities);\n const htmlPath = path.join(outputDir, 'dependencies.html');\n fs.writeFileSync(htmlPath, html, 'utf-8');\n\n return new VisualizationPaths(htmlPath);\n }\n\n /**\n * Open the HTML visualization in the default browser\n */\n openVisualization(htmlPath: string): boolean {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const platform = process.platform;\n let openCommand: string;\n\n if (platform === 'darwin') {\n openCommand = `open \"${htmlPath}\"`;\n } else if (platform === 'win32') {\n openCommand = `start \"\" \"${htmlPath}\"`;\n } else {\n openCommand = `xdg-open \"${htmlPath}\"`;\n }\n\n execSync(openCommand, { stdio: 'ignore' });\n return true;\n } catch (err: unknown) {\n const error = toError(err);\n console.warn(`⚠️ Could not open browser: ${error.message}`);\n return false;\n }\n }\n}\n"]}
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
* dependencies.json (both Z and X only compile-depend on the api library Y).
|
|
11
11
|
*/
|
|
12
12
|
import type { WorkspaceModel } from './runtime-markers';
|
|
13
|
+
import type { ApiScanResult } from './api-usage/api-scanner';
|
|
14
|
+
import type { ApiTransport } from './api-usage/api-relations';
|
|
13
15
|
export declare const DEFAULT_RUNTIME_GRAPH_PATH = "architecture/runtime-dependencies.json";
|
|
14
16
|
export interface RuntimeService {
|
|
15
17
|
level: number;
|
|
@@ -20,11 +22,19 @@ export interface RuntimeService {
|
|
|
20
22
|
export interface RuntimeApi {
|
|
21
23
|
implementedBy: string[];
|
|
22
24
|
usedBy: string[];
|
|
25
|
+
/** Transport of this API — 'rpc' (direct call) or 'pubsub' (delivered through a queue). */
|
|
26
|
+
type?: ApiTransport;
|
|
23
27
|
}
|
|
24
28
|
export interface RuntimeEdge {
|
|
25
29
|
from: string;
|
|
26
30
|
to: string;
|
|
27
31
|
via: string[];
|
|
32
|
+
/**
|
|
33
|
+
* Transport of this edge. 'rpc' → a direct call arrow. 'pubsub' → the producer enqueues and the
|
|
34
|
+
* consumer is delivered later, so the runtime viz draws it as producer → QUEUE → consumer.
|
|
35
|
+
* Edges are split by transport, so every edge is a single kind.
|
|
36
|
+
*/
|
|
37
|
+
type?: ApiTransport;
|
|
28
38
|
}
|
|
29
39
|
export interface RuntimeUnresolved {
|
|
30
40
|
service: string;
|
|
@@ -40,6 +50,8 @@ export interface RuntimeGraph {
|
|
|
40
50
|
export declare function runtimeAdjacency(graph: RuntimeGraph): Record<string, string[]>;
|
|
41
51
|
/** Assemble the full runtime graph from the workspace model + service contracts. */
|
|
42
52
|
export declare function assembleRuntimeGraph(model: WorkspaceModel, workspaceRoot: string): RuntimeGraph;
|
|
53
|
+
/** Assemble the runtime graph from the source scan (the derived apiRelations). */
|
|
54
|
+
export declare function assembleRuntimeGraphFromScan(scan: ApiScanResult): RuntimeGraph;
|
|
43
55
|
export declare function saveRuntimeGraph(graph: RuntimeGraph, workspaceRoot: string, graphPath?: string): void;
|
|
44
56
|
export declare function runtimeGraphFileExists(workspaceRoot: string, graphPath?: string): boolean;
|
|
45
57
|
export declare function loadRuntimeGraph(workspaceRoot: string, graphPath?: string): RuntimeGraph | null;
|
package/src/lib/runtime-graph.js
CHANGED
|
@@ -14,6 +14,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
14
14
|
exports.DEFAULT_RUNTIME_GRAPH_PATH = void 0;
|
|
15
15
|
exports.runtimeAdjacency = runtimeAdjacency;
|
|
16
16
|
exports.assembleRuntimeGraph = assembleRuntimeGraph;
|
|
17
|
+
exports.assembleRuntimeGraphFromScan = assembleRuntimeGraphFromScan;
|
|
17
18
|
exports.saveRuntimeGraph = saveRuntimeGraph;
|
|
18
19
|
exports.runtimeGraphFileExists = runtimeGraphFileExists;
|
|
19
20
|
exports.loadRuntimeGraph = loadRuntimeGraph;
|
|
@@ -23,6 +24,7 @@ const fs = tslib_1.__importStar(require("fs"));
|
|
|
23
24
|
const path = tslib_1.__importStar(require("path"));
|
|
24
25
|
const graph_sorter_1 = require("./graph-sorter");
|
|
25
26
|
const runtime_markers_1 = require("./runtime-markers");
|
|
27
|
+
const api_relations_1 = require("./api-usage/api-relations");
|
|
26
28
|
const toError_1 = require("../toError");
|
|
27
29
|
exports.DEFAULT_RUNTIME_GRAPH_PATH = 'architecture/runtime-dependencies.json';
|
|
28
30
|
/** Collect every service project (servicePaths), with its declarations resolved to projects. */
|
|
@@ -152,6 +154,124 @@ function assembleRuntimeGraph(model, workspaceRoot) {
|
|
|
152
154
|
unresolvedUses: edgeResult.unresolved,
|
|
153
155
|
};
|
|
154
156
|
}
|
|
157
|
+
/**
|
|
158
|
+
* Assembles the runtime microservice graph from the SOURCE SCAN (apiRelations) instead of
|
|
159
|
+
* service-contract.json: implementers × users per API, split by transport. An rpc edge is a direct
|
|
160
|
+
* call; a pubsub edge flows through a queue (drawn producer → queue → consumer by the visualizer).
|
|
161
|
+
*/
|
|
162
|
+
class ScanRuntimeAssembler {
|
|
163
|
+
scan;
|
|
164
|
+
constructor(scan) {
|
|
165
|
+
this.scan = scan;
|
|
166
|
+
}
|
|
167
|
+
assemble() {
|
|
168
|
+
const decls = this.collectDecls();
|
|
169
|
+
const apis = this.buildApis(decls);
|
|
170
|
+
const edgeResult = this.buildEdges(decls, apis);
|
|
171
|
+
const services = this.buildServices(decls, edgeResult.edges);
|
|
172
|
+
const apisObj = {};
|
|
173
|
+
for (const api of Array.from(apis.keys()).sort())
|
|
174
|
+
apisObj[api] = apis.get(api);
|
|
175
|
+
return { services, apis: apisObj, runtimeEdges: edgeResult.edges, unresolvedUses: edgeResult.unresolved };
|
|
176
|
+
}
|
|
177
|
+
/** Flatten each project's api-lib relations into implements/uses ApiRef lists. */
|
|
178
|
+
collectDecls() {
|
|
179
|
+
const decls = [];
|
|
180
|
+
for (const name of Array.from(this.scan.relationsByProject.keys()).sort()) {
|
|
181
|
+
const relations = this.scan.relationsByProject.get(name);
|
|
182
|
+
const implementsApis = [];
|
|
183
|
+
const usesApis = [];
|
|
184
|
+
for (const owner of Object.keys(relations)) {
|
|
185
|
+
implementsApis.push(...relations[owner].implements);
|
|
186
|
+
usesApis.push(...relations[owner].uses);
|
|
187
|
+
}
|
|
188
|
+
if (implementsApis.length > 0 || usesApis.length > 0) {
|
|
189
|
+
decls.push({ name, implementsApis: (0, api_relations_1.sortApiRefs)(implementsApis), usesApis: (0, api_relations_1.sortApiRefs)(usesApis) });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return decls;
|
|
193
|
+
}
|
|
194
|
+
/** apiClassName -> { implementedBy, usedBy, type }. */
|
|
195
|
+
buildApis(decls) {
|
|
196
|
+
const apis = new Map();
|
|
197
|
+
const ensure = (api, type) => {
|
|
198
|
+
let entry = apis.get(api);
|
|
199
|
+
if (!entry) {
|
|
200
|
+
entry = { implementedBy: [], usedBy: [], type };
|
|
201
|
+
apis.set(api, entry);
|
|
202
|
+
}
|
|
203
|
+
return entry;
|
|
204
|
+
};
|
|
205
|
+
for (const decl of decls) {
|
|
206
|
+
for (const ref of decl.implementsApis)
|
|
207
|
+
ensure(ref.api, ref.type).implementedBy.push(decl.name);
|
|
208
|
+
for (const ref of decl.usesApis)
|
|
209
|
+
ensure(ref.api, ref.type).usedBy.push(decl.name);
|
|
210
|
+
}
|
|
211
|
+
for (const entry of apis.values()) {
|
|
212
|
+
entry.implementedBy.sort();
|
|
213
|
+
entry.usedBy.sort();
|
|
214
|
+
}
|
|
215
|
+
return apis;
|
|
216
|
+
}
|
|
217
|
+
/** Inferred edges U -> I via api A, split by transport; plus uses with no implementer. */
|
|
218
|
+
buildEdges(decls, apis) {
|
|
219
|
+
const viaByKey = new Map();
|
|
220
|
+
const unresolved = [];
|
|
221
|
+
for (const decl of decls) {
|
|
222
|
+
for (const ref of decl.usesApis) {
|
|
223
|
+
const implementers = apis.get(ref.api)?.implementedBy ?? [];
|
|
224
|
+
if (implementers.length === 0) {
|
|
225
|
+
unresolved.push({ service: decl.name, api: ref.api });
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
for (const target of implementers) {
|
|
229
|
+
if (target === decl.name)
|
|
230
|
+
continue;
|
|
231
|
+
const key = `${decl.name}${target}${ref.type}`;
|
|
232
|
+
if (!viaByKey.has(key))
|
|
233
|
+
viaByKey.set(key, new Set());
|
|
234
|
+
viaByKey.get(key).add(ref.api);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return { edges: this.edgesFromKeys(viaByKey), unresolved: sortUnresolved(unresolved) };
|
|
239
|
+
}
|
|
240
|
+
edgesFromKeys(viaByKey) {
|
|
241
|
+
const edges = [];
|
|
242
|
+
for (const key of viaByKey.keys()) {
|
|
243
|
+
const parts = key.split('');
|
|
244
|
+
edges.push({ from: parts[0], to: parts[1], via: Array.from(viaByKey.get(key)).sort(), type: parts[2] });
|
|
245
|
+
}
|
|
246
|
+
edges.sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to) || (a.type ?? '').localeCompare(b.type ?? ''));
|
|
247
|
+
return edges;
|
|
248
|
+
}
|
|
249
|
+
buildServices(decls, edges) {
|
|
250
|
+
const services = {};
|
|
251
|
+
for (const decl of decls) {
|
|
252
|
+
const dependsOn = Array.from(new Set(edges.filter((e) => e.from === decl.name).map((e) => e.to))).sort();
|
|
253
|
+
services[decl.name] = {
|
|
254
|
+
level: 0,
|
|
255
|
+
implements: decl.implementsApis.map((r) => r.api),
|
|
256
|
+
uses: decl.usesApis.map((r) => r.api),
|
|
257
|
+
dependsOn,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
const levels = assignLevels(adjacencyFromEdges(Object.keys(services), edges));
|
|
261
|
+
for (const name of Object.keys(services))
|
|
262
|
+
services[name].level = levels[name] ?? 0;
|
|
263
|
+
return services;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/** Assemble the runtime graph from the source scan (the derived apiRelations). */
|
|
267
|
+
// webpieces-disable no-function-outside-class -- module entry point, mirrors assembleRuntimeGraph
|
|
268
|
+
function assembleRuntimeGraphFromScan(scan) {
|
|
269
|
+
return new ScanRuntimeAssembler(scan).assemble();
|
|
270
|
+
}
|
|
271
|
+
// webpieces-disable no-function-outside-class -- pure sort helper, matches the sibling helpers in this file
|
|
272
|
+
function sortUnresolved(unresolved) {
|
|
273
|
+
return [...unresolved].sort((a, b) => a.service.localeCompare(b.service) || a.api.localeCompare(b.api));
|
|
274
|
+
}
|
|
155
275
|
/** Deterministic JSON (sorted keys + arrays already sorted during assembly). */
|
|
156
276
|
function formatRuntimeJson(graph) {
|
|
157
277
|
return JSON.stringify(graph, null, 4) + '\n';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-graph.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-graph.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AA2IH,4CAEC;AAkBD,oDAyBC;AAOD,4CASC;AAED,wDAKC;AAED,4CAaC;AAGD,sDAEC;;AAjOD,+CAAyB;AACzB,mDAA6B;AAC7B,iDAAwD;AACxD,uDAA6E;AAE7E,wCAAqC;AAExB,QAAA,0BAA0B,GAAG,wCAAwC,CAAC;AA4CnF,gGAAgG;AAChG,SAAS,mBAAmB,CAAC,KAAqB,EAAE,aAAqB;IACrE,MAAM,KAAK,GAAkB,EAAE,CAAC;IAChC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;QACzC,IAAI,CAAC,IAAI,CAAC,SAAS;YAAE,SAAS;QAC9B,wEAAwE;QACxE,qEAAqE;QACrE,MAAM,QAAQ,GAAG,IAAA,qCAAmB,EAAC,aAAa,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/D,MAAM,cAAc,GAAG,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3D,MAAM,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;QAC/C,KAAK,CAAC,IAAI,CAAC;YACP,IAAI,EAAE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AAC","sourcesContent":["/**\n * Runtime Graph\n *\n * Assembles the runtime microservice graph from the per-service\n * `service-contract.json` files, and saves/loads the committed\n * `architecture/runtime-dependencies.json`.\n *\n * The runtime edge Z -> X (Z depends on X at runtime) is INFERRED: Z `uses` api\n * Y and X `implements` api Y. This edge does not exist in the compile-time\n * dependencies.json (both Z and X only compile-depend on the api library Y).\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { sortGraphTopologically } from './graph-sorter';\nimport { readServiceContract, resolvePackageNames } from './runtime-markers';\nimport type { WorkspaceModel } from './runtime-markers';\nimport { toError } from '../toError';\n\nexport const DEFAULT_RUNTIME_GRAPH_PATH = 'architecture/runtime-dependencies.json';\n\nexport interface RuntimeService {\n level: number;\n implements: string[];\n uses: string[];\n dependsOn: string[];\n}\n\nexport interface RuntimeApi {\n implementedBy: string[];\n usedBy: string[];\n}\n\nexport interface RuntimeEdge {\n from: string;\n to: string;\n via: string[];\n}\n\nexport interface RuntimeUnresolved {\n service: string;\n api: string;\n}\n\nexport interface RuntimeGraph {\n services: Record<string, RuntimeService>;\n apis: Record<string, RuntimeApi>;\n runtimeEdges: RuntimeEdge[];\n unresolvedUses: RuntimeUnresolved[];\n}\n\n/** One service's declared relationships, resolved to workspace project names. */\ninterface ServiceDecl {\n name: string;\n implements: string[];\n uses: string[];\n}\n\ninterface EdgeResult {\n edges: RuntimeEdge[];\n unresolved: RuntimeUnresolved[];\n}\n\n/** Collect every service project (servicePaths), with its declarations resolved to projects. */\nfunction collectServiceDecls(model: WorkspaceModel, workspaceRoot: string): ServiceDecl[] {\n const decls: ServiceDecl[] = [];\n for (const info of model.projects.values()) {\n if (!info.isService) continue;\n // A service missing its contract still appears as a node (empty edges);\n // validate-runtime-markers fails it separately for the missing file.\n const contract = readServiceContract(workspaceRoot, info.root);\n const implementsPkgs = contract ? contract.implements : [];\n const usesPkgs = contract ? contract.uses : [];\n decls.push({\n name: info.name,\n implements: resolvePackageNames(model, implementsPkgs).projects.sort(),\n uses: resolvePackageNames(model, usesPkgs).projects.sort(),\n });\n }\n return decls.sort((a: ServiceDecl, b: ServiceDecl) => a.name.localeCompare(b.name));\n}\n\nfunction buildApiIndex(decls: ServiceDecl[]): Map<string, RuntimeApi> {\n const apis = new Map<string, RuntimeApi>();\n const ensure = (api: string): RuntimeApi => {\n let entry = apis.get(api);\n if (!entry) {\n entry = { implementedBy: [], usedBy: [] };\n apis.set(api, entry);\n }\n return entry;\n };\n for (const decl of decls) {\n for (const api of decl.implements) ensure(api).implementedBy.push(decl.name);\n for (const api of decl.uses) ensure(api).usedBy.push(decl.name);\n }\n for (const entry of apis.values()) {\n entry.implementedBy.sort();\n entry.usedBy.sort();\n }\n return apis;\n}\n\n/** Build inferred runtime edges (Z -> X via Y) and the unresolved-uses list. */\nfunction buildEdges(decls: ServiceDecl[], apis: Map<string, RuntimeApi>): EdgeResult {\n const viaByEdge = new Map<string, Set<string>>();\n const unresolved: RuntimeUnresolved[] = [];\n\n for (const decl of decls) {\n for (const api of decl.uses) {\n const implementers = apis.get(api)?.implementedBy ?? [];\n if (implementers.length === 0) {\n unresolved.push({ service: decl.name, api });\n continue;\n }\n for (const target of implementers) {\n if (target === decl.name) continue;\n const key = `${decl.name} ${target}`;\n if (!viaByEdge.has(key)) viaByEdge.set(key, new Set());\n viaByEdge.get(key)!.add(api);\n }\n }\n }\n\n const edges: RuntimeEdge[] = [];\n for (const key of viaByEdge.keys()) {\n const parts = key.split(' ');\n edges.push({ from: parts[0], to: parts[1], via: Array.from(viaByEdge.get(key)!).sort() });\n }\n edges.sort((a: RuntimeEdge, b: RuntimeEdge) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to));\n unresolved.sort(\n (a: RuntimeUnresolved, b: RuntimeUnresolved) =>\n a.service.localeCompare(b.service) || a.api.localeCompare(b.api),\n );\n return { edges, unresolved };\n}\n\n/** Adjacency (service -> [targets]) used for leveling + cycle checks. */\nfunction adjacencyFromEdges(serviceNames: string[], edges: RuntimeEdge[]): Record<string, string[]> {\n const adj: Record<string, string[]> = {};\n for (const name of serviceNames) adj[name] = [];\n for (const edge of edges) {\n if (!adj[edge.from]) adj[edge.from] = [];\n adj[edge.from].push(edge.to);\n }\n return adj;\n}\n\n/** Adjacency (service -> [targets]) from a loaded runtime graph. */\nexport function runtimeAdjacency(graph: RuntimeGraph): Record<string, string[]> {\n return adjacencyFromEdges(Object.keys(graph.services), graph.runtimeEdges);\n}\n\n/** Assign levels via topological sort; falls back to level 0 when a cycle exists. */\nfunction assignLevels(adjacency: Record<string, string[]>): Record<string, number> {\n const levels: Record<string, number> = {};\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const sorted = sortGraphTopologically(adjacency);\n for (const name of Object.keys(sorted)) levels[name] = sorted[name].level;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n for (const name of Object.keys(adjacency)) levels[name] = 0;\n }\n return levels;\n}\n\n/** Assemble the full runtime graph from the workspace model + service contracts. */\nexport function assembleRuntimeGraph(model: WorkspaceModel, workspaceRoot: string): RuntimeGraph {\n const decls = collectServiceDecls(model, workspaceRoot);\n const apis = buildApiIndex(decls);\n const edgeResult = buildEdges(decls, apis);\n\n const services: Record<string, RuntimeService> = {};\n for (const decl of decls) {\n const dependsOn = Array.from(\n new Set(edgeResult.edges.filter((e: RuntimeEdge) => e.from === decl.name).map((e: RuntimeEdge) => e.to)),\n ).sort();\n services[decl.name] = { level: 0, implements: decl.implements, uses: decl.uses, dependsOn };\n }\n\n const levels = assignLevels(adjacencyFromEdges(Object.keys(services), edgeResult.edges));\n for (const name of Object.keys(services)) services[name].level = levels[name] ?? 0;\n\n const apisObj: Record<string, RuntimeApi> = {};\n for (const api of Array.from(apis.keys()).sort()) apisObj[api] = apis.get(api)!;\n\n return {\n services,\n apis: apisObj,\n runtimeEdges: edgeResult.edges,\n unresolvedUses: edgeResult.unresolved,\n };\n}\n\n/** Deterministic JSON (sorted keys + arrays already sorted during assembly). */\nfunction formatRuntimeJson(graph: RuntimeGraph): string {\n return JSON.stringify(graph, null, 4) + '\\n';\n}\n\nexport function saveRuntimeGraph(\n graph: RuntimeGraph,\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): void {\n const fullPath = path.join(workspaceRoot, graphPath);\n const dir = path.dirname(fullPath);\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(fullPath, formatRuntimeJson(graph), 'utf-8');\n}\n\nexport function runtimeGraphFileExists(\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): boolean {\n return fs.existsSync(path.join(workspaceRoot, graphPath));\n}\n\nexport function loadRuntimeGraph(\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): RuntimeGraph | null {\n const fullPath = path.join(workspaceRoot, graphPath);\n if (!fs.existsSync(fullPath)) return null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return JSON.parse(fs.readFileSync(fullPath, 'utf-8')) as RuntimeGraph;\n } catch (err: unknown) {\n const error = toError(err);\n throw new Error(`Failed to load runtime graph from ${fullPath}`, { cause: error });\n }\n}\n\n/** Serialize for an in-memory equality check (matches the on-disk format). */\nexport function serializeRuntimeGraph(graph: RuntimeGraph): string {\n return formatRuntimeJson(graph);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime-graph.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-graph.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;GAUG;;;AAsJH,4CAEC;AAkBD,oDAyBC;AA2HD,oEAEC;AAcD,4CASC;AAED,wDAKC;AAED,4CAaC;AAGD,sDAEC;;AAhXD,+CAAyB;AACzB,mDAA6B;AAC7B,iDAAwD;AACxD,uDAA6E;AAI7E,6DAAwD;AACxD,wCAAqC;AAExB,QAAA,0BAA0B,GAAG,wCAAwC,CAAC;AAoDnF,gGAAgG;AAChG,SAAS,mBAAmB,CAAC,KAA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AED,SAAgB,gBAAgB,CAC5B,aAAqB,EACrB,YAAoB,kCAA0B;IAE9C,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;IACrD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1C,8DAA8D;IAC9D,IAAI,CAAC;QACD,OAAO,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAiB,CAAC;IAC1E,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,MAAM,IAAI,KAAK,CAAC,qCAAqC,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACvF,CAAC;AACL,CAAC;AAED,8EAA8E;AAC9E,SAAgB,qBAAqB,CAAC,KAAmB;IACrD,OAAO,iBAAiB,CAAC,KAAK,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/**\n * Runtime Graph\n *\n * Assembles the runtime microservice graph from the per-service\n * `service-contract.json` files, and saves/loads the committed\n * `architecture/runtime-dependencies.json`.\n *\n * The runtime edge Z -> X (Z depends on X at runtime) is INFERRED: Z `uses` api\n * Y and X `implements` api Y. This edge does not exist in the compile-time\n * dependencies.json (both Z and X only compile-depend on the api library Y).\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { sortGraphTopologically } from './graph-sorter';\nimport { readServiceContract, resolvePackageNames } from './runtime-markers';\nimport type { WorkspaceModel } from './runtime-markers';\nimport type { ApiScanResult } from './api-usage/api-scanner';\nimport type { ApiRef, ApiTransport } from './api-usage/api-relations';\nimport { sortApiRefs } from './api-usage/api-relations';\nimport { toError } from '../toError';\n\nexport const DEFAULT_RUNTIME_GRAPH_PATH = 'architecture/runtime-dependencies.json';\n\nexport interface RuntimeService {\n level: number;\n implements: string[];\n uses: string[];\n dependsOn: string[];\n}\n\nexport interface RuntimeApi {\n implementedBy: string[];\n usedBy: string[];\n /** Transport of this API — 'rpc' (direct call) or 'pubsub' (delivered through a queue). */\n type?: ApiTransport;\n}\n\nexport interface RuntimeEdge {\n from: string;\n to: string;\n via: string[];\n /**\n * Transport of this edge. 'rpc' → a direct call arrow. 'pubsub' → the producer enqueues and the\n * consumer is delivered later, so the runtime viz draws it as producer → QUEUE → consumer.\n * Edges are split by transport, so every edge is a single kind.\n */\n type?: ApiTransport;\n}\n\nexport interface RuntimeUnresolved {\n service: string;\n api: string;\n}\n\nexport interface RuntimeGraph {\n services: Record<string, RuntimeService>;\n apis: Record<string, RuntimeApi>;\n runtimeEdges: RuntimeEdge[];\n unresolvedUses: RuntimeUnresolved[];\n}\n\n/** One service's declared relationships, resolved to workspace project names. */\ninterface ServiceDecl {\n name: string;\n implements: string[];\n uses: string[];\n}\n\ninterface EdgeResult {\n edges: RuntimeEdge[];\n unresolved: RuntimeUnresolved[];\n}\n\n/** Collect every service project (servicePaths), with its declarations resolved to projects. */\nfunction collectServiceDecls(model: WorkspaceModel, workspaceRoot: string): ServiceDecl[] {\n const decls: ServiceDecl[] = [];\n for (const info of model.projects.values()) {\n if (!info.isService) continue;\n // A service missing its contract still appears as a node (empty edges);\n // validate-runtime-markers fails it separately for the missing file.\n const contract = readServiceContract(workspaceRoot, info.root);\n const implementsPkgs = contract ? contract.implements : [];\n const usesPkgs = contract ? contract.uses : [];\n decls.push({\n name: info.name,\n implements: resolvePackageNames(model, implementsPkgs).projects.sort(),\n uses: resolvePackageNames(model, usesPkgs).projects.sort(),\n });\n }\n return decls.sort((a: ServiceDecl, b: ServiceDecl) => a.name.localeCompare(b.name));\n}\n\nfunction buildApiIndex(decls: ServiceDecl[]): Map<string, RuntimeApi> {\n const apis = new Map<string, RuntimeApi>();\n const ensure = (api: string): RuntimeApi => {\n let entry = apis.get(api);\n if (!entry) {\n entry = { implementedBy: [], usedBy: [] };\n apis.set(api, entry);\n }\n return entry;\n };\n for (const decl of decls) {\n for (const api of decl.implements) ensure(api).implementedBy.push(decl.name);\n for (const api of decl.uses) ensure(api).usedBy.push(decl.name);\n }\n for (const entry of apis.values()) {\n entry.implementedBy.sort();\n entry.usedBy.sort();\n }\n return apis;\n}\n\n/** Build inferred runtime edges (Z -> X via Y) and the unresolved-uses list. */\nfunction buildEdges(decls: ServiceDecl[], apis: Map<string, RuntimeApi>): EdgeResult {\n const viaByEdge = new Map<string, Set<string>>();\n const unresolved: RuntimeUnresolved[] = [];\n\n for (const decl of decls) {\n for (const api of decl.uses) {\n const implementers = apis.get(api)?.implementedBy ?? [];\n if (implementers.length === 0) {\n unresolved.push({ service: decl.name, api });\n continue;\n }\n for (const target of implementers) {\n if (target === decl.name) continue;\n const key = `${decl.name} ${target}`;\n if (!viaByEdge.has(key)) viaByEdge.set(key, new Set());\n viaByEdge.get(key)!.add(api);\n }\n }\n }\n\n const edges: RuntimeEdge[] = [];\n for (const key of viaByEdge.keys()) {\n const parts = key.split(' ');\n edges.push({ from: parts[0], to: parts[1], via: Array.from(viaByEdge.get(key)!).sort() });\n }\n edges.sort((a: RuntimeEdge, b: RuntimeEdge) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to));\n unresolved.sort(\n (a: RuntimeUnresolved, b: RuntimeUnresolved) =>\n a.service.localeCompare(b.service) || a.api.localeCompare(b.api),\n );\n return { edges, unresolved };\n}\n\n/** Adjacency (service -> [targets]) used for leveling + cycle checks. */\nfunction adjacencyFromEdges(serviceNames: string[], edges: RuntimeEdge[]): Record<string, string[]> {\n const adj: Record<string, string[]> = {};\n for (const name of serviceNames) adj[name] = [];\n for (const edge of edges) {\n if (!adj[edge.from]) adj[edge.from] = [];\n adj[edge.from].push(edge.to);\n }\n return adj;\n}\n\n/** Adjacency (service -> [targets]) from a loaded runtime graph. */\nexport function runtimeAdjacency(graph: RuntimeGraph): Record<string, string[]> {\n return adjacencyFromEdges(Object.keys(graph.services), graph.runtimeEdges);\n}\n\n/** Assign levels via topological sort; falls back to level 0 when a cycle exists. */\nfunction assignLevels(adjacency: Record<string, string[]>): Record<string, number> {\n const levels: Record<string, number> = {};\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const sorted = sortGraphTopologically(adjacency);\n for (const name of Object.keys(sorted)) levels[name] = sorted[name].level;\n } catch (err: unknown) {\n const error = toError(err);\n void error;\n for (const name of Object.keys(adjacency)) levels[name] = 0;\n }\n return levels;\n}\n\n/** Assemble the full runtime graph from the workspace model + service contracts. */\nexport function assembleRuntimeGraph(model: WorkspaceModel, workspaceRoot: string): RuntimeGraph {\n const decls = collectServiceDecls(model, workspaceRoot);\n const apis = buildApiIndex(decls);\n const edgeResult = buildEdges(decls, apis);\n\n const services: Record<string, RuntimeService> = {};\n for (const decl of decls) {\n const dependsOn = Array.from(\n new Set(edgeResult.edges.filter((e: RuntimeEdge) => e.from === decl.name).map((e: RuntimeEdge) => e.to)),\n ).sort();\n services[decl.name] = { level: 0, implements: decl.implements, uses: decl.uses, dependsOn };\n }\n\n const levels = assignLevels(adjacencyFromEdges(Object.keys(services), edgeResult.edges));\n for (const name of Object.keys(services)) services[name].level = levels[name] ?? 0;\n\n const apisObj: Record<string, RuntimeApi> = {};\n for (const api of Array.from(apis.keys()).sort()) apisObj[api] = apis.get(api)!;\n\n return {\n services,\n apis: apisObj,\n runtimeEdges: edgeResult.edges,\n unresolvedUses: edgeResult.unresolved,\n };\n}\n\n/** One project's implements/uses at api-CLASS granularity, from the source scan. */\ninterface ScanDecl {\n name: string;\n implementsApis: ApiRef[];\n usesApis: ApiRef[];\n}\n\n/**\n * Assembles the runtime microservice graph from the SOURCE SCAN (apiRelations) instead of\n * service-contract.json: implementers × users per API, split by transport. An rpc edge is a direct\n * call; a pubsub edge flows through a queue (drawn producer → queue → consumer by the visualizer).\n */\nclass ScanRuntimeAssembler {\n constructor(private readonly scan: ApiScanResult) {}\n\n assemble(): RuntimeGraph {\n const decls = this.collectDecls();\n const apis = this.buildApis(decls);\n const edgeResult = this.buildEdges(decls, apis);\n const services = this.buildServices(decls, edgeResult.edges);\n const apisObj: Record<string, RuntimeApi> = {};\n for (const api of Array.from(apis.keys()).sort()) apisObj[api] = apis.get(api)!;\n return { services, apis: apisObj, runtimeEdges: edgeResult.edges, unresolvedUses: edgeResult.unresolved };\n }\n\n /** Flatten each project's api-lib relations into implements/uses ApiRef lists. */\n private collectDecls(): ScanDecl[] {\n const decls: ScanDecl[] = [];\n for (const name of Array.from(this.scan.relationsByProject.keys()).sort()) {\n const relations = this.scan.relationsByProject.get(name)!;\n const implementsApis: ApiRef[] = [];\n const usesApis: ApiRef[] = [];\n for (const owner of Object.keys(relations)) {\n implementsApis.push(...relations[owner].implements);\n usesApis.push(...relations[owner].uses);\n }\n if (implementsApis.length > 0 || usesApis.length > 0) {\n decls.push({ name, implementsApis: sortApiRefs(implementsApis), usesApis: sortApiRefs(usesApis) });\n }\n }\n return decls;\n }\n\n /** apiClassName -> { implementedBy, usedBy, type }. */\n private buildApis(decls: ScanDecl[]): Map<string, RuntimeApi> {\n const apis = new Map<string, RuntimeApi>();\n const ensure = (api: string, type: ApiTransport): RuntimeApi => {\n let entry = apis.get(api);\n if (!entry) {\n entry = { implementedBy: [], usedBy: [], type };\n apis.set(api, entry);\n }\n return entry;\n };\n for (const decl of decls) {\n for (const ref of decl.implementsApis) ensure(ref.api, ref.type).implementedBy.push(decl.name);\n for (const ref of decl.usesApis) ensure(ref.api, ref.type).usedBy.push(decl.name);\n }\n for (const entry of apis.values()) {\n entry.implementedBy.sort();\n entry.usedBy.sort();\n }\n return apis;\n }\n\n /** Inferred edges U -> I via api A, split by transport; plus uses with no implementer. */\n private buildEdges(decls: ScanDecl[], apis: Map<string, RuntimeApi>): EdgeResult {\n const viaByKey = new Map<string, Set<string>>();\n const unresolved: RuntimeUnresolved[] = [];\n for (const decl of decls) {\n for (const ref of decl.usesApis) {\n const implementers = apis.get(ref.api)?.implementedBy ?? [];\n if (implementers.length === 0) {\n unresolved.push({ service: decl.name, api: ref.api });\n continue;\n }\n for (const target of implementers) {\n if (target === decl.name) continue;\n const key = `${decl.name}\u0000${target}\u0000${ref.type}`;\n if (!viaByKey.has(key)) viaByKey.set(key, new Set());\n viaByKey.get(key)!.add(ref.api);\n }\n }\n }\n return { edges: this.edgesFromKeys(viaByKey), unresolved: sortUnresolved(unresolved) };\n }\n\n private edgesFromKeys(viaByKey: Map<string, Set<string>>): RuntimeEdge[] {\n const edges: RuntimeEdge[] = [];\n for (const key of viaByKey.keys()) {\n const parts = key.split('\u0000');\n edges.push({ from: parts[0], to: parts[1], via: Array.from(viaByKey.get(key)!).sort(), type: parts[2] as ApiTransport });\n }\n edges.sort(\n (a: RuntimeEdge, b: RuntimeEdge) =>\n a.from.localeCompare(b.from) || a.to.localeCompare(b.to) || (a.type ?? '').localeCompare(b.type ?? ''),\n );\n return edges;\n }\n\n private buildServices(decls: ScanDecl[], edges: RuntimeEdge[]): Record<string, RuntimeService> {\n const services: Record<string, RuntimeService> = {};\n for (const decl of decls) {\n const dependsOn = Array.from(\n new Set(edges.filter((e: RuntimeEdge) => e.from === decl.name).map((e: RuntimeEdge) => e.to)),\n ).sort();\n services[decl.name] = {\n level: 0,\n implements: decl.implementsApis.map((r: ApiRef) => r.api),\n uses: decl.usesApis.map((r: ApiRef) => r.api),\n dependsOn,\n };\n }\n const levels = assignLevels(adjacencyFromEdges(Object.keys(services), edges));\n for (const name of Object.keys(services)) services[name].level = levels[name] ?? 0;\n return services;\n }\n}\n\n/** Assemble the runtime graph from the source scan (the derived apiRelations). */\n// webpieces-disable no-function-outside-class -- module entry point, mirrors assembleRuntimeGraph\nexport function assembleRuntimeGraphFromScan(scan: ApiScanResult): RuntimeGraph {\n return new ScanRuntimeAssembler(scan).assemble();\n}\n\n// webpieces-disable no-function-outside-class -- pure sort helper, matches the sibling helpers in this file\nfunction sortUnresolved(unresolved: RuntimeUnresolved[]): RuntimeUnresolved[] {\n return [...unresolved].sort(\n (a: RuntimeUnresolved, b: RuntimeUnresolved) => a.service.localeCompare(b.service) || a.api.localeCompare(b.api),\n );\n}\n\n/** Deterministic JSON (sorted keys + arrays already sorted during assembly). */\nfunction formatRuntimeJson(graph: RuntimeGraph): string {\n return JSON.stringify(graph, null, 4) + '\\n';\n}\n\nexport function saveRuntimeGraph(\n graph: RuntimeGraph,\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): void {\n const fullPath = path.join(workspaceRoot, graphPath);\n const dir = path.dirname(fullPath);\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(fullPath, formatRuntimeJson(graph), 'utf-8');\n}\n\nexport function runtimeGraphFileExists(\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): boolean {\n return fs.existsSync(path.join(workspaceRoot, graphPath));\n}\n\nexport function loadRuntimeGraph(\n workspaceRoot: string,\n graphPath: string = DEFAULT_RUNTIME_GRAPH_PATH,\n): RuntimeGraph | null {\n const fullPath = path.join(workspaceRoot, graphPath);\n if (!fs.existsSync(fullPath)) return null;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return JSON.parse(fs.readFileSync(fullPath, 'utf-8')) as RuntimeGraph;\n } catch (err: unknown) {\n const error = toError(err);\n throw new Error(`Failed to load runtime graph from ${fullPath}`, { cause: error });\n }\n}\n\n/** Serialize for an in-memory equality check (matches the on-disk format). */\nexport function serializeRuntimeGraph(graph: RuntimeGraph): string {\n return formatRuntimeJson(graph);\n}\n"]}
|
|
@@ -18,9 +18,28 @@ const LEVEL_COLORS = {
|
|
|
18
18
|
2: '#FFF3E0',
|
|
19
19
|
3: '#FCE4EC',
|
|
20
20
|
};
|
|
21
|
+
const QUEUE_FILL = '#FFF3E0';
|
|
21
22
|
function getShortName(name) {
|
|
22
23
|
return name.includes('/') ? name.split('/').pop() : name;
|
|
23
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* DOT for ONE runtime edge. rpc → a direct labeled arrow (producer calls consumer). pubsub → the
|
|
27
|
+
* producer enqueues and the consumer is delivered later, so we draw producer → QUEUE → consumer
|
|
28
|
+
* with a cylinder queue node and dashed enqueue/deliver arrows.
|
|
29
|
+
*/
|
|
30
|
+
// webpieces-disable no-function-outside-class -- DOT string builder, matching getShortName in this file
|
|
31
|
+
function edgeDot(edge) {
|
|
32
|
+
const from = getShortName(edge.from);
|
|
33
|
+
const to = getShortName(edge.to);
|
|
34
|
+
const via = edge.via.map((v) => getShortName(v)).join(', ');
|
|
35
|
+
if (edge.type !== 'pubsub') {
|
|
36
|
+
return ` "${from}" -> "${to}" [label="${via}"];\n`;
|
|
37
|
+
}
|
|
38
|
+
const queueId = `queue__${from}__${to}`;
|
|
39
|
+
return (` "${queueId}" [shape=cylinder, style="filled", fillcolor="${QUEUE_FILL}", label="${via}\\nqueue"];\n` +
|
|
40
|
+
` "${from}" -> "${queueId}" [label="enqueue", style=dashed];\n` +
|
|
41
|
+
` "${queueId}" -> "${to}" [label="deliver", style=dashed];\n`);
|
|
42
|
+
}
|
|
24
43
|
/** Build the Graphviz DOT for the runtime service graph. */
|
|
25
44
|
function generateRuntimeDot(graph, title = 'WebPieces Runtime Architecture') {
|
|
26
45
|
let dot = 'digraph RuntimeArchitecture {\n';
|
|
@@ -35,8 +54,7 @@ function generateRuntimeDot(graph, title = 'WebPieces Runtime Architecture') {
|
|
|
35
54
|
}
|
|
36
55
|
dot += '\n';
|
|
37
56
|
for (const edge of graph.runtimeEdges) {
|
|
38
|
-
|
|
39
|
-
dot += ` "${getShortName(edge.from)}" -> "${getShortName(edge.to)}" [label="${via}"];\n`;
|
|
57
|
+
dot += edgeDot(edge);
|
|
40
58
|
}
|
|
41
59
|
dot += '\n labelloc="t";\n';
|
|
42
60
|
dot += ` label="${title}\\n(from architecture/runtime-dependencies.json)";\n`;
|
|
@@ -67,7 +85,7 @@ function generateRuntimeHtml(dot, title) {
|
|
|
67
85
|
</head>
|
|
68
86
|
<body>
|
|
69
87
|
<h1>${title}</h1>
|
|
70
|
-
<div class="note">
|
|
88
|
+
<div class="note">Runtime calls between services. <strong>rpc</strong> = a direct arrow (synchronous call, labeled with the api). <strong>pubsub</strong> = producer → <em>queue</em> (cylinder) → consumer: the producer enqueues a Cloud Task and the consumer is delivered it later.</div>
|
|
71
89
|
<div id="graph"></div>
|
|
72
90
|
<script>${script}</script>
|
|
73
91
|
</body>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-visualizer.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-visualizer.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;
|
|
1
|
+
{"version":3,"file":"runtime-visualizer.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-visualizer.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAyCH,gDAwBC;AAsCD,8DAgBC;;AArHD,+CAAyB;AACzB,mDAA6B;AAG7B,MAAM,YAAY,GAA2B;IACzC,CAAC,EAAE,SAAS;IACZ,CAAC,EAAE,SAAS;IACZ,CAAC,EAAE,SAAS;IACZ,CAAC,EAAE,SAAS;CACf,CAAC;AAEF,MAAM,UAAU,GAAG,SAAS,CAAC;AAE7B,SAAS,YAAY,CAAC,IAAY;IAC9B,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9D,CAAC;AAED;;;;GAIG;AACH,wGAAwG;AACxG,SAAS,OAAO,CAAC,IAAiB;IAC9B,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACrC,MAAM,EAAE,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACjC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CA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O,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;AACjC,CAAC","sourcesContent":["/**\n * Runtime Visualizer\n *\n * Renders the runtime microservice graph (services + inferred Z -> X edges,\n * each labeled with the api(s) they flow over) to DOT + interactive HTML in\n * tmp/webpieces/runtime-architecture.{dot,html}.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { RuntimeGraph, RuntimeEdge } from './runtime-graph';\n\nconst LEVEL_COLORS: Record<number, string> = {\n 0: '#E8F5E9',\n 1: '#E3F2FD',\n 2: '#FFF3E0',\n 3: '#FCE4EC',\n};\n\nconst QUEUE_FILL = '#FFF3E0';\n\nfunction getShortName(name: string): string {\n return name.includes('/') ? name.split('/').pop()! : name;\n}\n\n/**\n * DOT for ONE runtime edge. rpc → a direct labeled arrow (producer calls consumer). pubsub → the\n * producer enqueues and the consumer is delivered later, so we draw producer → QUEUE → consumer\n * with a cylinder queue node and dashed enqueue/deliver arrows.\n */\n// webpieces-disable no-function-outside-class -- DOT string builder, matching getShortName in this file\nfunction edgeDot(edge: RuntimeEdge): string {\n const from = getShortName(edge.from);\n const to = getShortName(edge.to);\n const via = edge.via.map((v: string) => getShortName(v)).join(', ');\n if (edge.type !== 'pubsub') {\n return ` \"${from}\" -> \"${to}\" [label=\"${via}\"];\\n`;\n }\n const queueId = `queue__${from}__${to}`;\n return (\n ` \"${queueId}\" [shape=cylinder, style=\"filled\", fillcolor=\"${QUEUE_FILL}\", label=\"${via}\\\\nqueue\"];\\n` +\n ` \"${from}\" -> \"${queueId}\" [label=\"enqueue\", style=dashed];\\n` +\n ` \"${queueId}\" -> \"${to}\" [label=\"deliver\", style=dashed];\\n`\n );\n}\n\n/** Build the Graphviz DOT for the runtime service graph. */\nexport function generateRuntimeDot(graph: RuntimeGraph, title: string = 'WebPieces Runtime Architecture'): string {\n let dot = 'digraph RuntimeArchitecture {\\n';\n dot += ' rankdir=TB;\\n';\n dot += ' node [shape=box, style=\"filled,rounded\", fontname=\"Arial\"];\\n';\n dot += ' edge [fontname=\"Arial\", fontsize=10];\\n\\n';\n\n for (const name of Object.keys(graph.services)) {\n const svc = graph.services[name];\n const color = LEVEL_COLORS[svc.level] || '#F5F5F5';\n const role = svc.implements.length > 0 ? 'server' : 'client';\n dot += ` \"${getShortName(name)}\" [fillcolor=\"${color}\", label=\"${getShortName(name)}\\\\n(${role}, L${svc.level})\"];\\n`;\n }\n\n dot += '\\n';\n\n for (const edge of graph.runtimeEdges) {\n dot += edgeDot(edge);\n }\n\n dot += '\\n labelloc=\"t\";\\n';\n dot += ` label=\"${title}\\\\n(from architecture/runtime-dependencies.json)\";\\n`;\n dot += ' fontsize=20;\\n';\n dot += '}\\n';\n return dot;\n}\n\nfunction generateRuntimeHtml(dot: string, title: string): string {\n const script = `\n const dot = ${JSON.stringify(dot)};\n const viz = new Viz();\n viz.renderSVGElement(dot)\n .then(el => document.getElementById('graph').appendChild(el))\n .catch(err => { document.getElementById('graph').innerHTML = '<pre>' + err + '</pre>'; });\n `;\n return `<!DOCTYPE html>\n<html>\n<head>\n <title>${title}</title>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/viz.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/viz.js@2.1.2/full.render.js\"></script>\n <style>\n body { margin: 0; padding: 20px; font-family: Arial, sans-serif; background: #f5f5f5; }\n h1 { text-align: center; color: #333; }\n #graph { text-align: center; background: white; padding: 20px; border-radius: 8px; }\n .note { max-width: 700px; margin: 12px auto; color: #555; text-align: center; }\n </style>\n</head>\n<body>\n <h1>${title}</h1>\n <div class=\"note\">Runtime calls between services. <strong>rpc</strong> = a direct arrow (synchronous call, labeled with the api). <strong>pubsub</strong> = producer → <em>queue</em> (cylinder) → consumer: the producer enqueues a Cloud Task and the consumer is delivered it later.</div>\n <div id=\"graph\"></div>\n <script>${script}</script>\n</body>\n</html>`;\n}\n\nexport interface RuntimeVisualizationPaths {\n dotPath: string;\n htmlPath: string;\n}\n\n/** Write the DOT + HTML renderings to tmp/webpieces/. */\nexport function writeRuntimeVisualization(\n graph: RuntimeGraph,\n workspaceRoot: string,\n title: string = 'WebPieces Runtime Architecture',\n): RuntimeVisualizationPaths {\n const outputDir = path.join(workspaceRoot, 'tmp', 'webpieces');\n if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });\n\n const dot = generateRuntimeDot(graph, title);\n const dotPath = path.join(outputDir, 'runtime-architecture.dot');\n fs.writeFileSync(dotPath, dot, 'utf-8');\n\n const htmlPath = path.join(outputDir, 'runtime-architecture.html');\n fs.writeFileSync(htmlPath, generateRuntimeHtml(dot, title), 'utf-8');\n\n return { dotPath, htmlPath };\n}\n"]}
|