@domain-first/project-structure 8.1.1 → 8.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lint.js CHANGED
@@ -1,272 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from "node:util";
3
- import node_fs from "node:fs";
4
- import node_path from "node:path";
5
- import { canDependOn, namedImportFiles, isCrossContextImplementation, findWiredModules, moduleKindOf, readWiredModule, crossContextImportAllowed, compilerOption, wiredDependencyNames } from "./201.js";
6
- import { defaultDependencyRules, fileModuleKind, configuredDependencyRules, ProjectRoot, ConfigFile, outdatedConfigMessage } from "./870.js";
7
- const readAliases = (projectRoot)=>{
8
- const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
9
- const paths = compilerOption(tsconfig, 'paths');
10
- if (!paths || 'object' != typeof paths) return [];
11
- const baseUrl = compilerOption(tsconfig, 'baseUrl');
12
- const base = node_path.resolve(projectRoot, 'string' == typeof baseUrl ? baseUrl : '.');
13
- return Object.entries(paths).filter(([, targets])=>targets.length).map(([key, [target]])=>{
14
- const wildcard = key.endsWith('*');
15
- return {
16
- prefix: wildcard ? key.slice(0, -1) : key,
17
- wildcard,
18
- target: node_path.resolve(base, wildcard ? target.replace(/\*$/, '') : target)
19
- };
20
- }).sort((a, b)=>b.prefix.length - a.prefix.length);
21
- };
22
- const resolveSpecifier = (specifier, fromFile, aliases)=>{
23
- if (specifier.startsWith('.')) return node_path.resolve(node_path.dirname(fromFile), specifier);
24
- for (const { prefix, wildcard, target } of aliases)if (wildcard ? specifier.startsWith(prefix) : specifier === prefix) return node_path.join(target, wildcard ? specifier.slice(prefix.length) : '');
25
- };
26
- const inside = (folder, file)=>{
27
- const relativePath = node_path.relative(folder, file);
28
- return !relativePath || relativePath.startsWith('..') || node_path.isAbsolute(relativePath) ? void 0 : relativePath.split(node_path.sep);
29
- };
30
- const sourceFiles = (folder)=>{
31
- if (!node_fs.existsSync(folder)) return [];
32
- return node_fs.readdirSync(folder, {
33
- withFileTypes: true
34
- }).flatMap((entry)=>{
35
- const entryPath = node_path.join(folder, entry.name);
36
- if (entry.isDirectory()) return 'node_modules' === entry.name ? [] : sourceFiles(entryPath);
37
- return /\.(c|m)?tsx?$/.test(entry.name) && !entry.name.endsWith('.d.ts') ? [
38
- entryPath
39
- ] : [];
40
- });
41
- };
42
- const importPattern = /\b(?:(import|export)\s+(type\s+)?(?:(?!\b(?:import|export)\b)[\w*{}\s,$])*?\s*from\s*|import\s*\(\s*|require\s*\(\s*|import\s*)(['"])([^'"\n]+)\3/g;
43
- const lineAt = (source, index)=>source.slice(0, index).split('\n').length;
44
- const importsOf = (source, file, aliases)=>[
45
- ...source.matchAll(importPattern)
46
- ].map((match)=>({
47
- typeOnly: 'import' === match[1] && Boolean(match[2]),
48
- target: resolveSpecifier(match[4], file, aliases),
49
- line: lineAt(source, match.index),
50
- statement: match[0].replace(/\s+/g, ' ')
51
- }));
52
- const isSpec = (file)=>/\.(spec|test)\.(c|m)?tsx?$/.test(file);
53
- const layerImportRules = {
54
- domain: {
55
- allows: ([layer])=>'domain' === layer,
56
- rule: 'domain imports outside the domain layer:'
57
- },
58
- application: {
59
- allows: ([layer])=>'domain' === layer || 'application' === layer,
60
- rule: 'application imports outside domain and application:'
61
- },
62
- infrastructure: {
63
- allows: ([layer, part])=>'domain' === layer || 'infrastructure' === layer || 'application' === layer && ('ports' === part || 'commands' === part || 'queries' === part),
64
- rule: 'infrastructure imports outside domain, infrastructure, application ports and command and query contracts:'
65
- },
66
- presentation: {
67
- allows: ([layer])=>'infrastructure' !== layer,
68
- rule: 'presentation imports infrastructure (only wiring knows concrete classes):'
69
- }
70
- };
71
- const baseName = (file)=>node_path.basename(file).replace(/\.[^.]+$/, '');
72
- const isOwnContract = (file, target)=>baseName(file).endsWith(`-${baseName(target)}`);
73
- const importViolations = (projectRoot, rootFolder, rules)=>{
74
- const root = node_path.resolve(projectRoot, rootFolder);
75
- const contextsFolder = node_path.join(root, 'bounded-contexts');
76
- const sharedFolder = node_path.join(root, 'shared-kernel');
77
- const reactFolder = node_path.join(root, 'presentation', 'react');
78
- const uiKitFolder = node_path.join(reactFolder, 'ui-kit');
79
- const widgetsFolder = node_path.join(reactFolder, 'widgets');
80
- const hooksFolder = node_path.join(reactFolder, 'hooks');
81
- const inMemoryDbFile = node_path.join(sharedFolder, 'infrastructure', 'services', 'in-memory-db-infrastructure-service.ts');
82
- const aliases = readAliases(projectRoot);
83
- const violations = [];
84
- const locate = (file)=>{
85
- const inContext = inside(contextsFolder, file);
86
- if (inContext && inContext.length > 1) {
87
- const [owner, ...segments] = inContext;
88
- return {
89
- owner,
90
- segments
91
- };
92
- }
93
- const inShared = inside(sharedFolder, file);
94
- return inShared && {
95
- owner: 'shared-kernel',
96
- segments: inShared
97
- };
98
- };
99
- const isDomainModel = ([layer, part], target)=>'domain' === layer && [
100
- 'aggregates',
101
- 'entities',
102
- 'value-objects'
103
- ].includes(part) && !/-repository(\.tsx?)?$/.test(node_path.basename(target));
104
- const widgetFolders = new Map();
105
- const isWidgetFolder = (folder)=>{
106
- if (!widgetFolders.has(folder)) widgetFolders.set(folder, node_fs.existsSync(folder) && node_fs.statSync(folder).isDirectory() && node_fs.readdirSync(folder).some((name)=>name.endsWith('-widget.tsx')));
107
- return widgetFolders.get(folder);
108
- };
109
- const widgetOf = (file)=>{
110
- for(let folder = file; inside(widgetsFolder, folder); folder = node_path.dirname(folder))if (isWidgetFolder(folder)) return folder;
111
- };
112
- const files = [
113
- contextsFolder,
114
- sharedFolder,
115
- reactFolder
116
- ].flatMap(sourceFiles);
117
- for (const file of files){
118
- const source = node_fs.readFileSync(file, 'utf8');
119
- const from = locate(file);
120
- const ownContext = inside(contextsFolder, file)?.[0];
121
- const directWiring = ownContext && from?.segments[0] === 'wiring' && readWiredModule(file, node_path.join(contextsFolder, ownContext))?.implementations.some((implementation)=>isCrossContextImplementation(implementation.file));
122
- const report = (check, rule, imported)=>violations.push({
123
- check,
124
- rule,
125
- file,
126
- line: imported.line,
127
- text: imported.statement
128
- });
129
- for (const imported of importsOf(source, file, aliases)){
130
- const target = imported.target;
131
- if (!target) continue;
132
- const to = locate(target);
133
- const targetContext = inside(contextsFolder, target)?.[0];
134
- const crossContextAllowed = true === crossContextImportAllowed(file, target) && (from?.segments[0] !== 'wiring' || directWiring);
135
- if (ownContext) {
136
- if (targetContext && targetContext !== ownContext && !crossContextAllowed) report('context-isolation', `[${ownContext}] imports another context:`, imported);
137
- } else if (inside(sharedFolder, file)) {
138
- const allowed = !to || 'shared-kernel' === to.owner || 'domain' === to.segments[0] && 'errors' === to.segments[1] || file === inMemoryDbFile && isDomainModel(to.segments, target);
139
- if (!allowed) report('shared-kernel', '[shared-kernel] imports a bounded context outside its domain/errors (and domain models for the in-memory DB):', imported);
140
- } else if (inside(uiKitFolder, file) || inside(hooksFolder, file)) {
141
- const [area] = inside(reactFolder, target) ?? [];
142
- const forbidden = inside(uiKitFolder, file) ? [
143
- 'widgets',
144
- 'pages'
145
- ] : [
146
- 'ui-kit',
147
- 'widgets',
148
- 'pages'
149
- ];
150
- if (targetContext || forbidden.includes(area)) report('react', inside(uiKitFolder, file) ? '[presentation/react/ui-kit] imports a bounded context, widget or page:' : '[presentation/react/hooks] a shared hook imports a bounded context, UI-kit, widget or page:', imported);
151
- } else if (targetContext && !(imported.typeOnly && to?.segments[0] === 'presentation' && 'rest' === to.segments[1])) report('react', '[presentation/react] imports a context other than `import type` from presentation/rest:', imported);
152
- const ownWidget = widgetOf(file);
153
- const targetWidget = widgetOf(target);
154
- if (ownWidget && targetWidget && targetWidget !== ownWidget) report('react', '[presentation/react/widgets] a widget imports another widget:', imported);
155
- if (!from || !to) continue;
156
- if (crossContextAllowed) continue;
157
- if (isSpec(file)) continue;
158
- const fromKind = fileModuleKind(from.segments);
159
- const toKind = fileModuleKind(to.segments);
160
- if (fromKind && toKind) {
161
- if (!rules[fromKind].has(toKind) && !(fromKind === toKind && isOwnContract(file, target))) report('dependencies', `[${from.owner}] ${fromKind} may not use ${toKind} (dependency rules):`, imported);
162
- if ('infrastructure' !== to.segments[0]) continue;
163
- }
164
- const layerRule = layerImportRules[from.segments[0]];
165
- if (layerRule && !layerRule.allows(to.segments)) report('layers', `[${from.owner}] ${layerRule.rule}`, imported);
166
- }
167
- }
168
- return violations;
169
- };
170
- const wiringViolations = (projectRoot, rootFolder, rules)=>{
171
- const root = node_path.resolve(projectRoot, rootFolder);
172
- const sharedFolder = node_path.join(root, 'shared-kernel');
173
- const contextsFolder = node_path.join(root, 'bounded-contexts');
174
- const sharedModules = findWiredModules(sharedFolder);
175
- const owners = [
176
- {
177
- name: 'shared-kernel',
178
- modules: sharedModules
179
- },
180
- ...node_fs.existsSync(contextsFolder) ? node_fs.readdirSync(contextsFolder, {
181
- withFileTypes: true
182
- }).filter((entry)=>entry.isDirectory()).map((entry)=>({
183
- name: entry.name,
184
- modules: findWiredModules(node_path.join(contextsFolder, entry.name))
185
- })) : []
186
- ];
187
- const violations = [];
188
- const allModules = new Map(owners.flatMap(({ modules })=>modules).map((module)=>[
189
- module.wireFile,
190
- module
191
- ]));
192
- const aliases = readAliases(projectRoot);
193
- for (const { name, modules } of owners){
194
- const visible = new Map([
195
- ...sharedModules,
196
- ...modules
197
- ].map((x)=>[
198
- x.wireName,
199
- x
200
- ]));
201
- for (const consumer of modules){
202
- const source = node_fs.readFileSync(consumer.wireFile, 'utf8');
203
- const imported = namedImportFiles(source, consumer.wireFile, (specifier, file)=>resolveSpecifier(specifier, file, aliases));
204
- for (const implementation of consumer.implementations){
205
- let dependencies;
206
- try {
207
- dependencies = wiredDependencyNames(source, implementation.className);
208
- } catch {
209
- continue;
210
- }
211
- const listStart = source.search(new RegExp(`wireClass\\(\\s*${implementation.className}\\b`));
212
- for (const dependency of dependencies){
213
- const target = imported.get(dependency);
214
- const candidate = (target ? allModules.get(target) : void 0) ?? visible.get(dependency);
215
- if (!candidate || canDependOn(consumer, candidate, rules, implementation)) continue;
216
- const index = source.indexOf(dependency, listStart);
217
- violations.push({
218
- check: 'dependencies',
219
- rule: `[${name}] wiring: a dependency the dependency rules don't allow:`,
220
- file: consumer.wireFile,
221
- line: lineAt(source, index),
222
- text: `${implementation.className} (${moduleKindOf(consumer) ?? consumer.kind}) ← ${candidate.typeName} (${moduleKindOf(candidate) ?? candidate.kind})`
223
- });
224
- }
225
- }
226
- }
227
- }
228
- return violations;
229
- };
230
- const clockViolations = (projectRoot, rootFolder)=>{
231
- const root = node_path.resolve(projectRoot, rootFolder);
232
- const folders = [
233
- node_path.join(root, 'shared-kernel'),
234
- ...node_fs.existsSync(node_path.join(root, 'bounded-contexts')) ? node_fs.readdirSync(node_path.join(root, 'bounded-contexts')).map((name)=>node_path.join(root, 'bounded-contexts', name)) : []
235
- ].flatMap((folder)=>[
236
- node_path.join(folder, 'domain'),
237
- node_path.join(folder, 'application')
238
- ]);
239
- return folders.flatMap(sourceFiles).filter((file)=>!isSpec(file)).flatMap((file)=>{
240
- const source = node_fs.readFileSync(file, 'utf8');
241
- return [
242
- ...source.matchAll(/\bnew\s+Date\s*\(\s*\)|\bDate\.now\s*\(/g)
243
- ].map((match)=>({
244
- check: 'clock',
245
- rule: 'domain or application reads the current time directly (use the clock port):',
246
- file,
247
- line: lineAt(source, match.index),
248
- text: match[0]
249
- }));
250
- });
251
- };
252
- const lintProject = (projectRoot, rootFolder, { rules = defaultDependencyRules, checks = {} } = {})=>[
253
- ...importViolations(projectRoot, rootFolder, rules),
254
- ...wiringViolations(projectRoot, rootFolder, rules),
255
- ...clockViolations(projectRoot, rootFolder)
256
- ].filter((x)=>false !== checks[x.check]);
257
- const formatViolations = (violations, projectRoot)=>{
258
- const groups = new Map();
259
- for (const { rule, file, line, text } of violations)groups.set(rule, [
260
- ...groups.get(rule) ?? [],
261
- ` ${node_path.relative(projectRoot, file)}:${line}: ${text}`
262
- ]);
263
- return [
264
- ...groups
265
- ].map(([rule, lines])=>[
266
- rule,
267
- ...lines
268
- ].join('\n')).join('\n\n');
269
- };
3
+ import { configuredDependencyRules, ProjectRoot, outdatedConfigMessage, ConfigFile } from "./870.js";
4
+ import { lintProject, formatViolations } from "./38.js";
270
5
  const help = `Usage: df-lint [rootFolder]
271
6
 
272
7
  Reports what breaks the Domain-First rules in the project:
@@ -292,20 +27,20 @@ if (values.help) {
292
27
  console.log(help);
293
28
  process.exit(0);
294
29
  }
295
- const lint_projectRoot = new ProjectRoot().path;
30
+ const projectRoot = new ProjectRoot().path;
296
31
  if (ConfigFile.outdated) {
297
32
  console.log(outdatedConfigMessage);
298
33
  process.exit(1);
299
34
  }
300
35
  const config = ConfigFile.exists ? ConfigFile.Instance.data : void 0;
301
- const lint_rootFolder = positionals[0] ?? config?.project.rootFolder ?? 'src';
302
- const lint_violations = lintProject(lint_projectRoot, lint_rootFolder, {
36
+ const rootFolder = positionals[0] ?? config?.project.rootFolder ?? 'src';
37
+ const violations = lintProject(projectRoot, rootFolder, {
303
38
  rules: configuredDependencyRules(),
304
39
  checks: config?.backend?.rules?.lint
305
40
  });
306
- if (lint_violations.length) {
307
- console.log(formatViolations(lint_violations, lint_projectRoot));
308
- console.log(`\n${lint_violations.length} problem(s) found.`);
41
+ if (violations.length) {
42
+ console.log(formatViolations(violations, projectRoot));
43
+ console.log(`\n${violations.length} problem(s) found.`);
309
44
  process.exit(1);
310
45
  }
311
46
  console.log('OK: no Domain-First rule violations.');
@@ -0,0 +1,53 @@
1
+ import { type Layer } from './wiring';
2
+ export declare const sharedKernel = "shared-kernel";
3
+ export type GraphModule = {
4
+ /** `<owner>:<TypeName>`, the module ID of the JSON interface. */
5
+ id: string;
6
+ owner: string;
7
+ typeName: string;
8
+ layer: Layer;
9
+ /** Implementation classes; several for an env-branched module. */
10
+ implementations: string[];
11
+ };
12
+ export type GraphEdge = {
13
+ from: string;
14
+ to: string;
15
+ /** The implementation class that takes the dependency. */
16
+ implementation: string;
17
+ };
18
+ export type ProjectGraph = {
19
+ owners: string[];
20
+ modules: GraphModule[];
21
+ edges: GraphEdge[];
22
+ };
23
+ /**
24
+ * Wired modules of the Shared Kernel and every bounded context, and the
25
+ * dependencies their wires inject, per implementation.
26
+ */
27
+ export declare const projectGraph: (projectRoot: string, rootFolder: string) => ProjectGraph;
28
+ /**
29
+ * Bounded contexts and the Shared Kernel. A solid arrow is a cross-context
30
+ * port reaching a neighbor's handlers; a dashed one, use of the Shared Kernel.
31
+ */
32
+ export declare const contextMap: (graph: ProjectGraph, idPrefix?: string) => string;
33
+ /**
34
+ * The wired modules of one owner by layer, with their dependencies. Modules
35
+ * of other owners it depends on are grouped under their owner. A branched
36
+ * module's arrows name the implementations that take the dependency.
37
+ */
38
+ export declare const ownerGraph: (graph: ProjectGraph, owner: string, idPrefix?: string) => string;
39
+ export type GraphFormat = 'mermaid' | 'markdown' | 'json' | 'html';
40
+ /** The format a `--out` file gets from its extension. */
41
+ export declare const formatOfFile: (file: string) => GraphFormat | undefined;
42
+ /** Mermaid version the HTML page loads; pinned so the page keeps working. */
43
+ export declare const mermaidScript = "https://cdn.jsdelivr.net/npm/mermaid@11.4.1/dist/mermaid.esm.min.mjs";
44
+ /**
45
+ * A page that renders the charts with Mermaid from a CDN: the context map
46
+ * and every context, or one context.
47
+ */
48
+ export declare const graphHtml: (graph: ProjectGraph, title: string, owner?: string) => string;
49
+ /** The graph in a format: one owner with `owner`, otherwise the whole project. */
50
+ export declare const renderGraph: (graph: ProjectGraph, format: GraphFormat, { owner, title }?: {
51
+ owner?: string;
52
+ title?: string;
53
+ }) => string;
@@ -0,0 +1 @@
1
+ export {};
@@ -13,6 +13,16 @@ export type Violation = {
13
13
  line: number;
14
14
  text: string;
15
15
  };
16
+ export type Alias = {
17
+ prefix: string;
18
+ wildcard: boolean;
19
+ target: string;
20
+ };
21
+ /**
22
+ * Wildcard and exact `paths` of the root tsconfig, longest first.
23
+ */
24
+ export declare const readAliases: (projectRoot: string) => Alias[];
25
+ export declare const resolveSpecifier: (specifier: string, fromFile: string, aliases: Alias[]) => string | undefined;
16
26
  export type LintOptions = {
17
27
  rules?: DependencyRules;
18
28
  /**
@@ -33,3 +33,24 @@ export declare const routeFiles: (folder: string) => string[];
33
33
  * files of that Next.js route folder move too.
34
34
  */
35
35
  export declare const moveReactModule: (projectRoot: string, reactFolder: string, module: ReactModule, rawName: string, route?: RouteMove) => MovePlan;
36
+ /**
37
+ * The route folder of a page with Next.js: `<app>/<name>/` when its
38
+ * `page.tsx` renders the page. Undefined for other routes or none.
39
+ */
40
+ export declare const pageRouteFolder: (appFolder: string, page: ReactModule) => string | undefined;
41
+ export type ReactDeleteResult = {
42
+ /** Files outside the module that still import it: [file, import]. */
43
+ usedBy: [string, string][];
44
+ } | {
45
+ deleted: string[];
46
+ usedBy?: undefined;
47
+ };
48
+ /**
49
+ * Stages the deletion of a page or widget with its files, and with `route`
50
+ * the files of that Next.js route folder too. Nothing is staged while other
51
+ * files still import the module; those imports are returned instead.
52
+ */
53
+ export declare const deleteReactModule: (projectRoot: string, reactFolder: string, module: ReactModule, route?: {
54
+ appFolder: string;
55
+ folder: string;
56
+ }) => ReactDeleteResult;