@domain-first/project-structure 8.1.1 → 8.2.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/README.md CHANGED
@@ -194,7 +194,7 @@ export const wirePlaceOrderUseCase = wireClass(PlaceOrderUseCase, [
194
194
  ]);
195
195
  ```
196
196
 
197
- Only the dependencies that respect the layers are offered: a use case can't take another use case, the domain can't take the application. To add a dependency later, choose **Wire dependency** in the context menu.
197
+ Only the dependencies that respect the layers are offered: a use case can't take another use case, the domain can't take the application. To add a dependency later, choose **Wire dependency** in the context menu. Menus with more than ten choices, such as the module list, take a search: type part of a name to filter.
198
198
 
199
199
  ### How to add an implementation
200
200
 
@@ -308,6 +308,17 @@ Defaults and details: [Dependency rules](API.md#dependency-rules), [`df-lint`](A
308
308
  }
309
309
  ```
310
310
 
311
+ ### How to see the structure
312
+
313
+ ```bash
314
+ npx df-graph # bounded contexts and the Shared Kernel
315
+ npx df-graph --context sales # the modules of one context by layer
316
+ npx df-graph --html # open the rendered charts in the browser
317
+ npx df-graph --out docs/ARCHITECTURE.md
318
+ ```
319
+
320
+ `df-graph` reads the wiring and draws Mermaid charts: which contexts reach each other through cross-context ports, which use the Shared Kernel, and inside a context, what each module depends on. It prints the chart, opens a rendered page with `--html` (Mermaid comes from a CDN), or writes `--out` in the format of the extension: `.md` for GitHub, which renders the chart, `.mmd`, `.json` or `.html`. `--json` gives the same graph to tools and agents.
321
+
311
322
  ### How to upgrade to a new major version
312
323
 
313
324
  After upgrading the package to a new major version, run:
package/dist/201.js CHANGED
@@ -499,4 +499,4 @@ const compilerOption = (configFile, name, seen = new Set())=>{
499
499
  if (void 0 !== value) return value;
500
500
  }
501
501
  };
502
- export { UnknownFormatNaming, addBranchedImplementation, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, boundedContextLocation, canDependOn, compilerOption, crossContextImplementation, crossContextImportAllowed, findWiredModules, hasNeighboringBoundedContext, implementationType, isCrossContextImplementation, isSuggestedFor, moduleKindOf, namedImportFiles, readWiredModule, relativeImport, stripJsonComments, wireBranches, wireDependencies, wiredDependencyNames };
502
+ export { UnknownFormatNaming, addBranchedImplementation, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, boundedContextLocation, canDependOn, compilerOption, crossContextImplementation, crossContextImportAllowed, findWiredModules, hasNeighboringBoundedContext, implementationType, isCrossContextImplementation, isSuggestedFor, moduleKindOf, namedImportFiles, readWiredModule, relativeImport, stripJsonComments, wireBranches, wireDependencies, wiredDependencyNames, wiring_layers };
package/dist/287.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import node_path from "node:path";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
- import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, select as prompts_select } from "@inquirer/prompts";
3
+ import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, search, select as prompts_select } from "@inquirer/prompts";
4
4
  import { styleText } from "node:util";
5
5
  import node_fs from "node:fs";
6
6
  import { addImport, availableDependencies, compilerOption, findWiredModules, UnknownFormatNaming, readWiredModule, stripJsonComments, addClassMember, hasNeighboringBoundedContext, addBranchedImplementation, addWireDependencies, boundedContextLocation, addConstructorParameters, relativeImport, wireBranches, wireDependencies, implementationType as wiring_implementationType, crossContextImportAllowed, crossContextImplementation, isSuggestedFor } from "./201.js";
@@ -246,6 +246,7 @@ const addInMemoryDb = ()=>{
246
246
  return [];
247
247
  };
248
248
  const inMemoryDbApplied = ()=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && inMemoryDbScaffolded();
249
+ const isSeparator = (choice)=>'function' == typeof Separator && choice instanceof Separator || 'object' == typeof choice && null !== choice && 'separator' === choice.type;
249
250
  class RequestError extends Error {
250
251
  code;
251
252
  details;
@@ -321,7 +322,7 @@ const interaction_confirm = async (config)=>{
321
322
  });
322
323
  return value;
323
324
  };
324
- const choicesOf = (config)=>config.choices.filter((choice)=>!(choice instanceof Separator)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
325
+ const choicesOf = (config)=>config.choices.filter((choice)=>!isSeparator(choice)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
325
326
  value: choice
326
327
  });
327
328
  const choiceId = (choice, id)=>id?.(choice.value) ?? choice.value;
@@ -334,9 +335,62 @@ const resolveChoice = (value, choices, key, id)=>{
334
335
  });
335
336
  return matches[0].value;
336
337
  };
338
+ const searchThreshold = 10;
339
+ const choiceLabel = (choice)=>choice.name ?? String(choice.value);
340
+ const filterChoices = (choices, term)=>{
341
+ const text = (term ?? '').trim().toLowerCase();
342
+ const words = text.split(/\s+/).filter(Boolean);
343
+ if (!words.length) return [
344
+ ...choices
345
+ ];
346
+ const groups = [
347
+ {
348
+ matches: []
349
+ }
350
+ ];
351
+ for (const choice of choices){
352
+ if (isSeparator(choice)) {
353
+ groups.push({
354
+ separator: choice,
355
+ matches: []
356
+ });
357
+ continue;
358
+ }
359
+ const normalized = 'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
360
+ value: choice
361
+ };
362
+ const label = choiceLabel(normalized).toLowerCase();
363
+ if (words.every((word)=>label.includes(word))) groups.at(-1)?.matches.push({
364
+ choice: normalized,
365
+ prefix: label.startsWith(text)
366
+ });
367
+ }
368
+ const byPrefix = (items, prefix)=>[
369
+ ...items.filter(prefix),
370
+ ...items.filter((item)=>!prefix(item))
371
+ ];
372
+ const [ungrouped, ...grouped] = groups;
373
+ return [
374
+ ungrouped,
375
+ ...byPrefix(grouped.filter(({ matches })=>matches.length), ({ matches })=>matches.some(({ prefix })=>prefix))
376
+ ].flatMap(({ separator, matches })=>[
377
+ ...separator ? [
378
+ separator
379
+ ] : [],
380
+ ...byPrefix(matches, ({ prefix })=>prefix).map(({ choice })=>choice)
381
+ ]);
382
+ };
337
383
  const interaction_select = async (config)=>{
338
384
  const { key, id, ...interactive } = config;
339
- if (!isNonInteractive()) return prompts_select(interactive);
385
+ if (!isNonInteractive()) {
386
+ if (choicesOf(config).length <= searchThreshold) return prompts_select(interactive);
387
+ return search({
388
+ message: `${config.message.trimEnd()} (type to filter)`,
389
+ source: (term)=>filterChoices(config.choices, term),
390
+ pageSize: config.pageSize,
391
+ default: config.default
392
+ });
393
+ }
340
394
  const field = requireKey(key);
341
395
  const value = answerFor(field, config.default);
342
396
  if (void 0 === value) throw interaction_missing(field);
package/dist/38.js ADDED
@@ -0,0 +1,268 @@
1
+ import node_fs from "node:fs";
2
+ import node_path from "node:path";
3
+ import { canDependOn, namedImportFiles, isCrossContextImplementation, findWiredModules, moduleKindOf, readWiredModule, crossContextImportAllowed, compilerOption, wiredDependencyNames } from "./201.js";
4
+ import { defaultDependencyRules, fileModuleKind } from "./870.js";
5
+ const readAliases = (projectRoot)=>{
6
+ const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
7
+ const paths = compilerOption(tsconfig, 'paths');
8
+ if (!paths || 'object' != typeof paths) return [];
9
+ const baseUrl = compilerOption(tsconfig, 'baseUrl');
10
+ const base = node_path.resolve(projectRoot, 'string' == typeof baseUrl ? baseUrl : '.');
11
+ return Object.entries(paths).filter(([, targets])=>targets.length).map(([key, [target]])=>{
12
+ const wildcard = key.endsWith('*');
13
+ return {
14
+ prefix: wildcard ? key.slice(0, -1) : key,
15
+ wildcard,
16
+ target: node_path.resolve(base, wildcard ? target.replace(/\*$/, '') : target)
17
+ };
18
+ }).sort((a, b)=>b.prefix.length - a.prefix.length);
19
+ };
20
+ const resolveSpecifier = (specifier, fromFile, aliases)=>{
21
+ if (specifier.startsWith('.')) return node_path.resolve(node_path.dirname(fromFile), specifier);
22
+ for (const { prefix, wildcard, target } of aliases)if (wildcard ? specifier.startsWith(prefix) : specifier === prefix) return node_path.join(target, wildcard ? specifier.slice(prefix.length) : '');
23
+ };
24
+ const inside = (folder, file)=>{
25
+ const relativePath = node_path.relative(folder, file);
26
+ return !relativePath || relativePath.startsWith('..') || node_path.isAbsolute(relativePath) ? void 0 : relativePath.split(node_path.sep);
27
+ };
28
+ const sourceFiles = (folder)=>{
29
+ if (!node_fs.existsSync(folder)) return [];
30
+ return node_fs.readdirSync(folder, {
31
+ withFileTypes: true
32
+ }).flatMap((entry)=>{
33
+ const entryPath = node_path.join(folder, entry.name);
34
+ if (entry.isDirectory()) return 'node_modules' === entry.name ? [] : sourceFiles(entryPath);
35
+ return /\.(c|m)?tsx?$/.test(entry.name) && !entry.name.endsWith('.d.ts') ? [
36
+ entryPath
37
+ ] : [];
38
+ });
39
+ };
40
+ 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;
41
+ const lineAt = (source, index)=>source.slice(0, index).split('\n').length;
42
+ const importsOf = (source, file, aliases)=>[
43
+ ...source.matchAll(importPattern)
44
+ ].map((match)=>({
45
+ typeOnly: 'import' === match[1] && Boolean(match[2]),
46
+ target: resolveSpecifier(match[4], file, aliases),
47
+ line: lineAt(source, match.index),
48
+ statement: match[0].replace(/\s+/g, ' ')
49
+ }));
50
+ const isSpec = (file)=>/\.(spec|test)\.(c|m)?tsx?$/.test(file);
51
+ const layerImportRules = {
52
+ domain: {
53
+ allows: ([layer])=>'domain' === layer,
54
+ rule: 'domain imports outside the domain layer:'
55
+ },
56
+ application: {
57
+ allows: ([layer])=>'domain' === layer || 'application' === layer,
58
+ rule: 'application imports outside domain and application:'
59
+ },
60
+ infrastructure: {
61
+ allows: ([layer, part])=>'domain' === layer || 'infrastructure' === layer || 'application' === layer && ('ports' === part || 'commands' === part || 'queries' === part),
62
+ rule: 'infrastructure imports outside domain, infrastructure, application ports and command and query contracts:'
63
+ },
64
+ presentation: {
65
+ allows: ([layer])=>'infrastructure' !== layer,
66
+ rule: 'presentation imports infrastructure (only wiring knows concrete classes):'
67
+ }
68
+ };
69
+ const baseName = (file)=>node_path.basename(file).replace(/\.[^.]+$/, '');
70
+ const isOwnContract = (file, target)=>baseName(file).endsWith(`-${baseName(target)}`);
71
+ const importViolations = (projectRoot, rootFolder, rules)=>{
72
+ const root = node_path.resolve(projectRoot, rootFolder);
73
+ const contextsFolder = node_path.join(root, 'bounded-contexts');
74
+ const sharedFolder = node_path.join(root, 'shared-kernel');
75
+ const reactFolder = node_path.join(root, 'presentation', 'react');
76
+ const uiKitFolder = node_path.join(reactFolder, 'ui-kit');
77
+ const widgetsFolder = node_path.join(reactFolder, 'widgets');
78
+ const hooksFolder = node_path.join(reactFolder, 'hooks');
79
+ const inMemoryDbFile = node_path.join(sharedFolder, 'infrastructure', 'services', 'in-memory-db-infrastructure-service.ts');
80
+ const aliases = readAliases(projectRoot);
81
+ const violations = [];
82
+ const locate = (file)=>{
83
+ const inContext = inside(contextsFolder, file);
84
+ if (inContext && inContext.length > 1) {
85
+ const [owner, ...segments] = inContext;
86
+ return {
87
+ owner,
88
+ segments
89
+ };
90
+ }
91
+ const inShared = inside(sharedFolder, file);
92
+ return inShared && {
93
+ owner: 'shared-kernel',
94
+ segments: inShared
95
+ };
96
+ };
97
+ const isDomainModel = ([layer, part], target)=>'domain' === layer && [
98
+ 'aggregates',
99
+ 'entities',
100
+ 'value-objects'
101
+ ].includes(part) && !/-repository(\.tsx?)?$/.test(node_path.basename(target));
102
+ const widgetFolders = new Map();
103
+ const isWidgetFolder = (folder)=>{
104
+ 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')));
105
+ return widgetFolders.get(folder);
106
+ };
107
+ const widgetOf = (file)=>{
108
+ for(let folder = file; inside(widgetsFolder, folder); folder = node_path.dirname(folder))if (isWidgetFolder(folder)) return folder;
109
+ };
110
+ const files = [
111
+ contextsFolder,
112
+ sharedFolder,
113
+ reactFolder
114
+ ].flatMap(sourceFiles);
115
+ for (const file of files){
116
+ const source = node_fs.readFileSync(file, 'utf8');
117
+ const from = locate(file);
118
+ const ownContext = inside(contextsFolder, file)?.[0];
119
+ const directWiring = ownContext && from?.segments[0] === 'wiring' && readWiredModule(file, node_path.join(contextsFolder, ownContext))?.implementations.some((implementation)=>isCrossContextImplementation(implementation.file));
120
+ const report = (check, rule, imported)=>violations.push({
121
+ check,
122
+ rule,
123
+ file,
124
+ line: imported.line,
125
+ text: imported.statement
126
+ });
127
+ for (const imported of importsOf(source, file, aliases)){
128
+ const target = imported.target;
129
+ if (!target) continue;
130
+ const to = locate(target);
131
+ const targetContext = inside(contextsFolder, target)?.[0];
132
+ const crossContextAllowed = true === crossContextImportAllowed(file, target) && (from?.segments[0] !== 'wiring' || directWiring);
133
+ if (ownContext) {
134
+ if (targetContext && targetContext !== ownContext && !crossContextAllowed) report('context-isolation', `[${ownContext}] imports another context:`, imported);
135
+ } else if (inside(sharedFolder, file)) {
136
+ const allowed = !to || 'shared-kernel' === to.owner || 'domain' === to.segments[0] && 'errors' === to.segments[1] || file === inMemoryDbFile && isDomainModel(to.segments, target);
137
+ if (!allowed) report('shared-kernel', '[shared-kernel] imports a bounded context outside its domain/errors (and domain models for the in-memory DB):', imported);
138
+ } else if (inside(uiKitFolder, file) || inside(hooksFolder, file)) {
139
+ const [area] = inside(reactFolder, target) ?? [];
140
+ const forbidden = inside(uiKitFolder, file) ? [
141
+ 'widgets',
142
+ 'pages'
143
+ ] : [
144
+ 'ui-kit',
145
+ 'widgets',
146
+ 'pages'
147
+ ];
148
+ 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);
149
+ } 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);
150
+ const ownWidget = widgetOf(file);
151
+ const targetWidget = widgetOf(target);
152
+ if (ownWidget && targetWidget && targetWidget !== ownWidget) report('react', '[presentation/react/widgets] a widget imports another widget:', imported);
153
+ if (!from || !to) continue;
154
+ if (crossContextAllowed) continue;
155
+ if (isSpec(file)) continue;
156
+ const fromKind = fileModuleKind(from.segments);
157
+ const toKind = fileModuleKind(to.segments);
158
+ if (fromKind && toKind) {
159
+ if (!rules[fromKind].has(toKind) && !(fromKind === toKind && isOwnContract(file, target))) report('dependencies', `[${from.owner}] ${fromKind} may not use ${toKind} (dependency rules):`, imported);
160
+ if ('infrastructure' !== to.segments[0]) continue;
161
+ }
162
+ const layerRule = layerImportRules[from.segments[0]];
163
+ if (layerRule && !layerRule.allows(to.segments)) report('layers', `[${from.owner}] ${layerRule.rule}`, imported);
164
+ }
165
+ }
166
+ return violations;
167
+ };
168
+ const wiringViolations = (projectRoot, rootFolder, rules)=>{
169
+ const root = node_path.resolve(projectRoot, rootFolder);
170
+ const sharedFolder = node_path.join(root, 'shared-kernel');
171
+ const contextsFolder = node_path.join(root, 'bounded-contexts');
172
+ const sharedModules = findWiredModules(sharedFolder);
173
+ const owners = [
174
+ {
175
+ name: 'shared-kernel',
176
+ modules: sharedModules
177
+ },
178
+ ...node_fs.existsSync(contextsFolder) ? node_fs.readdirSync(contextsFolder, {
179
+ withFileTypes: true
180
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>({
181
+ name: entry.name,
182
+ modules: findWiredModules(node_path.join(contextsFolder, entry.name))
183
+ })) : []
184
+ ];
185
+ const violations = [];
186
+ const allModules = new Map(owners.flatMap(({ modules })=>modules).map((module)=>[
187
+ module.wireFile,
188
+ module
189
+ ]));
190
+ const aliases = readAliases(projectRoot);
191
+ for (const { name, modules } of owners){
192
+ const visible = new Map([
193
+ ...sharedModules,
194
+ ...modules
195
+ ].map((x)=>[
196
+ x.wireName,
197
+ x
198
+ ]));
199
+ for (const consumer of modules){
200
+ const source = node_fs.readFileSync(consumer.wireFile, 'utf8');
201
+ const imported = namedImportFiles(source, consumer.wireFile, (specifier, file)=>resolveSpecifier(specifier, file, aliases));
202
+ for (const implementation of consumer.implementations){
203
+ let dependencies;
204
+ try {
205
+ dependencies = wiredDependencyNames(source, implementation.className);
206
+ } catch {
207
+ continue;
208
+ }
209
+ const listStart = source.search(new RegExp(`wireClass\\(\\s*${implementation.className}\\b`));
210
+ for (const dependency of dependencies){
211
+ const target = imported.get(dependency);
212
+ const candidate = (target ? allModules.get(target) : void 0) ?? visible.get(dependency);
213
+ if (!candidate || canDependOn(consumer, candidate, rules, implementation)) continue;
214
+ const index = source.indexOf(dependency, listStart);
215
+ violations.push({
216
+ check: 'dependencies',
217
+ rule: `[${name}] wiring: a dependency the dependency rules don't allow:`,
218
+ file: consumer.wireFile,
219
+ line: lineAt(source, index),
220
+ text: `${implementation.className} (${moduleKindOf(consumer) ?? consumer.kind}) ← ${candidate.typeName} (${moduleKindOf(candidate) ?? candidate.kind})`
221
+ });
222
+ }
223
+ }
224
+ }
225
+ }
226
+ return violations;
227
+ };
228
+ const clockViolations = (projectRoot, rootFolder)=>{
229
+ const root = node_path.resolve(projectRoot, rootFolder);
230
+ const folders = [
231
+ node_path.join(root, 'shared-kernel'),
232
+ ...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)) : []
233
+ ].flatMap((folder)=>[
234
+ node_path.join(folder, 'domain'),
235
+ node_path.join(folder, 'application')
236
+ ]);
237
+ return folders.flatMap(sourceFiles).filter((file)=>!isSpec(file)).flatMap((file)=>{
238
+ const source = node_fs.readFileSync(file, 'utf8');
239
+ return [
240
+ ...source.matchAll(/\bnew\s+Date\s*\(\s*\)|\bDate\.now\s*\(/g)
241
+ ].map((match)=>({
242
+ check: 'clock',
243
+ rule: 'domain or application reads the current time directly (use the clock port):',
244
+ file,
245
+ line: lineAt(source, match.index),
246
+ text: match[0]
247
+ }));
248
+ });
249
+ };
250
+ const lintProject = (projectRoot, rootFolder, { rules = defaultDependencyRules, checks = {} } = {})=>[
251
+ ...importViolations(projectRoot, rootFolder, rules),
252
+ ...wiringViolations(projectRoot, rootFolder, rules),
253
+ ...clockViolations(projectRoot, rootFolder)
254
+ ].filter((x)=>false !== checks[x.check]);
255
+ const formatViolations = (violations, projectRoot)=>{
256
+ const groups = new Map();
257
+ for (const { rule, file, line, text } of violations)groups.set(rule, [
258
+ ...groups.get(rule) ?? [],
259
+ ` ${node_path.relative(projectRoot, file)}:${line}: ${text}`
260
+ ]);
261
+ return [
262
+ ...groups
263
+ ].map(([rule, lines])=>[
264
+ rule,
265
+ ...lines
266
+ ].join('\n')).join('\n\n');
267
+ };
268
+ export { formatViolations, lintProject, readAliases, resolveSpecifier };