@domain-first/project-structure 8.9.2 → 8.10.1

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/115.js CHANGED
@@ -249,7 +249,7 @@ const legacyEndpointFileLookup = (rootFolder)=>` // The controller, i
249
249
  )
250
250
  );
251
251
  `;
252
- const endpointFileLookup = (rootFolder)=>` const [currentBoundedContext, ...relativePath] = routeMetadata.path;
252
+ const rootEndpointFileLookup = (rootFolder)=>` const [currentBoundedContext, ...relativePath] = routeMetadata.path;
253
253
 
254
254
  if (!currentBoundedContext) {
255
255
  return undefined;
@@ -273,6 +273,37 @@ const endpointFileLookup = (rootFolder)=>` const [currentBoundedConte
273
273
  path.join(restFolder, '(root)', ...endpointPath)
274
274
  );
275
275
  `;
276
+ const endpointFileLookup = (rootFolder)=>` // A context is the start of the route, nested ones included
277
+ // (/sales/orders/...). A controller is the next folder; other
278
+ // routes belong to the context root in presentation/rest/(root).
279
+ const contextsFolder = path.join(
280
+ ${rootFolderSegments(rootFolder, 16)}'bounded-contexts'
281
+ );
282
+ const endpointFile = Array.from(
283
+ { length: routeMetadata.path.length },
284
+ (_, index) => index + 1
285
+ )
286
+ .flatMap((contextLength) => {
287
+ const restFolder = path.join(
288
+ contextsFolder,
289
+ ...routeMetadata.path.slice(0, contextLength),
290
+ 'presentation',
291
+ 'rest'
292
+ );
293
+ const endpointPath = [
294
+ ...routeMetadata.path
295
+ .slice(contextLength)
296
+ .map(pathParameterAsName),
297
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
298
+ ];
299
+ return [
300
+ path.join(restFolder, ...endpointPath),
301
+ path.join(restFolder, '(root)', ...endpointPath)
302
+ ];
303
+ })
304
+ .map((file) => project.getSourceFile(file))
305
+ .find((file) => !!file);
306
+ `;
276
307
  const openapiExtractor = (rootFolder)=>`import path from 'node:path';
277
308
  import {
278
309
  type DocNode,
@@ -581,4 +612,4 @@ const legacyRootEndpoints = (boundedContextFolder)=>{
581
612
  };
582
613
  };
583
614
  const hasLegacyRootEndpoints = (boundedContextFolder)=>Object.values(legacyRootEndpoints(boundedContextFolder)).some((paths)=>paths.length > 0);
584
- export { addInMemoryDbSection, codeExtension, endpointFileLookup, escapeRegExp, hasDependency, hasLegacyRootEndpoints, inMemoryDbScaffolded, inMemoryDbSectionMembers, inMemoryDbTypeImport, inMemoryImplementationType, injectInMemoryDb, isInMemoryDb, isPathParameterName, keepInMemoryDbSection, legacyEndpointFileLookup, legacyHasId, legacyRootEndpoints, legacyWithIdLookup, missingDomainFirstPackages, missingPackages, openapiExtractor, openapiExtractorPath, pathParameterAsName, plural, projectImports, restControllers, restFolders, rootStaticSegments, scaffoldInMemoryDb, stageModuleMove, toPosix, usesInMemoryDb, walk, wireInMemoryDb, withIdLookup };
615
+ export { addInMemoryDbSection, codeExtension, endpointFileLookup, escapeRegExp, hasDependency, hasLegacyRootEndpoints, inMemoryDbScaffolded, inMemoryDbSectionMembers, inMemoryDbTypeImport, inMemoryImplementationType, injectInMemoryDb, isInMemoryDb, isPathParameterName, keepInMemoryDbSection, legacyEndpointFileLookup, legacyHasId, legacyRootEndpoints, legacyWithIdLookup, missingDomainFirstPackages, missingPackages, openapiExtractor, openapiExtractorPath, pathParameterAsName, plural, projectImports, restControllers, restFolders, rootEndpointFileLookup, rootStaticSegments, scaffoldInMemoryDb, stageModuleMove, toPosix, usesInMemoryDb, walk, wireInMemoryDb, withIdLookup };
package/dist/201.js CHANGED
@@ -1,24 +1,128 @@
1
- import node_fs from "node:fs";
2
1
  import node_path from "node:path";
2
+ import node_fs from "node:fs";
3
3
  import zod from "zod";
4
4
  import { createRequire } from "node:module";
5
+ class UnknownFormatNaming {
6
+ rawSource;
7
+ camelCase;
8
+ PascalCase;
9
+ constructor(rawSource){
10
+ this.rawSource = rawSource;
11
+ const source = rawSource.trim();
12
+ if (!source.includes('-')) {
13
+ this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
14
+ this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
15
+ }
16
+ const words = source.split('-').filter((word)=>!!word);
17
+ this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
18
+ this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
19
+ }
20
+ get fileName() {
21
+ return this.rawSource;
22
+ }
23
+ get variableName() {
24
+ return this.camelCase;
25
+ }
26
+ get ClassName() {
27
+ return this.PascalCase;
28
+ }
29
+ get withSpaces() {
30
+ return this.fileName.replaceAll('-', ' ');
31
+ }
32
+ }
33
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
34
+ class NestedName {
35
+ folders;
36
+ folderName;
37
+ fileName;
38
+ ClassName;
39
+ classNameSegments;
40
+ constructor(rawSource){
41
+ const segments = splitSegments(rawSource);
42
+ this.folders = segments.slice(0, -1);
43
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
44
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
45
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
46
+ this.ClassName = this.classNameSegments.join('');
47
+ }
48
+ static validate = (rawSource)=>{
49
+ const segments = splitSegments(rawSource);
50
+ if (!segments.length) return 'Name is required';
51
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
52
+ return true;
53
+ };
54
+ }
55
+ const boundedContextsFolderName = 'bounded-contexts';
56
+ const contextLayerFolders = [
57
+ 'domain',
58
+ 'application',
59
+ 'infrastructure',
60
+ 'presentation',
61
+ 'wiring'
62
+ ];
63
+ const subfolders = (folder)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder, {
64
+ withFileTypes: true
65
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name) : [];
66
+ const isBoundedContextFolder = (folder)=>{
67
+ const names = subfolders(folder);
68
+ return !names.length || names.some((name)=>contextLayerFolders.includes(name));
69
+ };
70
+ const boundedContextNames = (contextsFolder)=>{
71
+ const walk = (folder, prefix)=>subfolders(folder).flatMap((name)=>{
72
+ const child = node_path.join(folder, name);
73
+ return isBoundedContextFolder(child) ? [
74
+ [
75
+ ...prefix,
76
+ name
77
+ ].join('/')
78
+ ] : walk(child, [
79
+ ...prefix,
80
+ name
81
+ ]);
82
+ });
83
+ return walk(contextsFolder, []).sort();
84
+ };
85
+ const boundedContextPath = (contextsFolder, name)=>node_path.join(contextsFolder, ...name.split('/'));
86
+ const contextClassName = (name)=>new NestedName(name).ClassName;
87
+ const splitContextSegments = (segments)=>{
88
+ const layer = segments.findIndex((segment)=>contextLayerFolders.includes(segment));
89
+ const length = layer > 0 ? layer : 1;
90
+ return {
91
+ name: segments.slice(0, length).join('/'),
92
+ segments: segments.slice(length)
93
+ };
94
+ };
95
+ const validateBoundedContextName = (contextsFolder, name)=>{
96
+ const valid = NestedName.validate(name);
97
+ if (true !== valid) return valid;
98
+ const segments = name.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
99
+ const reserved = segments.find((segment)=>contextLayerFolders.includes(segment));
100
+ if (reserved) return `"${reserved}" is a layer folder of a bounded context and can't name one`;
101
+ for(let index = 1; index < segments.length; index++){
102
+ const parent = node_path.join(contextsFolder, ...segments.slice(0, index));
103
+ if (node_fs.existsSync(parent) && isBoundedContextFolder(parent)) return `${segments.slice(0, index).join('/')} is a bounded context: contexts can't be nested in one`;
104
+ }
105
+ const folder = node_path.join(contextsFolder, ...segments);
106
+ if (node_fs.existsSync(folder) && !isBoundedContextFolder(folder)) return `${segments.join('/')} groups bounded contexts: pick a name inside it`;
107
+ return true;
108
+ };
5
109
  const crossContextImplementation = 'cross-context';
6
110
  const hasNeighboringBoundedContext = (ownerPath)=>{
7
- const contextsPath = node_path.dirname(ownerPath);
8
- return 'bounded-contexts' === node_path.basename(contextsPath) && node_fs.existsSync(contextsPath) && node_fs.readdirSync(contextsPath, {
9
- withFileTypes: true
10
- }).some((entry)=>entry.isDirectory() && entry.name !== node_path.basename(ownerPath));
111
+ const location = boundedContextLocation(node_path.join(ownerPath, 'domain'));
112
+ if (!location) return false;
113
+ const contextsPath = node_path.join(location.root, boundedContextsFolderName);
114
+ return boundedContextNames(contextsPath).some((name)=>name !== location.name);
11
115
  };
12
116
  const boundedContextLocation = (file)=>{
13
117
  const parts = node_path.resolve(file).split(node_path.sep);
14
- const index = parts.lastIndexOf('bounded-contexts');
118
+ const index = parts.lastIndexOf(boundedContextsFolderName);
15
119
  if (-1 === index || parts.length < index + 3) return;
16
120
  return {
17
121
  root: parts.slice(0, index).join(node_path.sep),
18
- name: parts[index + 1],
19
- segments: parts.slice(index + 2)
122
+ ...splitContextSegments(parts.slice(index + 1))
20
123
  };
21
124
  };
125
+ const boundedContextName = (folder)=>boundedContextLocation(node_path.join(folder, 'domain'))?.name;
22
126
  const isCrossContextImplementation = (file)=>{
23
127
  const location = boundedContextLocation(file);
24
128
  const [layer, kind, label] = location?.segments ?? [];
@@ -488,34 +592,6 @@ class ConfigFile {
488
592
  }
489
593
  }
490
594
  const configuredDependencyRules = ()=>resolveDependencyRules(ConfigFile.exists ? ConfigFile.Instance.data.backend?.rules?.dependencies : void 0);
491
- class UnknownFormatNaming {
492
- rawSource;
493
- camelCase;
494
- PascalCase;
495
- constructor(rawSource){
496
- this.rawSource = rawSource;
497
- const source = rawSource.trim();
498
- if (!source.includes('-')) {
499
- this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
500
- this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
501
- }
502
- const words = source.split('-').filter((word)=>!!word);
503
- this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
504
- this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
505
- }
506
- get fileName() {
507
- return this.rawSource;
508
- }
509
- get variableName() {
510
- return this.camelCase;
511
- }
512
- get ClassName() {
513
- return this.PascalCase;
514
- }
515
- get withSpaces() {
516
- return this.fileName.replaceAll('-', ' ');
517
- }
518
- }
519
595
  const wiring_layers = [
520
596
  'domain',
521
597
  'application',
@@ -858,7 +934,7 @@ const wireDependencies = (consumer, implementation, dependencies)=>{
858
934
  const bindings = dependencies.map((dependency)=>{
859
935
  const crossContext = crossContextImportAllowed(consumer.wireFile, dependency.wireFile);
860
936
  const context = crossContext ? boundedContextLocation(dependency.wireFile) : void 0;
861
- const prefix = context ? new UnknownFormatNaming(context.name).ClassName : '';
937
+ const prefix = context ? contextClassName(context.name) : '';
862
938
  const wireName = dependencyBinding(wireSource, consumer.wireFile, dependency.wireFile, dependency.wireName, context ? `wire${prefix}${dependency.typeName}` : dependency.wireName);
863
939
  const typeName = dependencyBinding(classSource, implementation.file, dependency.typeFile, dependency.typeName, `${prefix}${dependency.typeName}`);
864
940
  wireSource = addImport(wireSource, `import { ${importedAs(dependency.wireName, wireName)} } from '${relativeImport(consumer.wireFile, dependency.wireFile)}'`);
@@ -956,4 +1032,4 @@ const compilerOption = (configFile, name, seen = new Set())=>{
956
1032
  if (void 0 !== value) return value;
957
1033
  }
958
1034
  };
959
- export { ConfigFile, File, Folder, ProjectRoot, UnknownFormatNaming, addBranchedImplementation, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, boundedContextLocation, branchNameSchema, canDependOn, compilerOption, configFileName, configSchema, configuredDependencyRules, crossContextImplementation, crossContextImportAllowed, defaultDependencyRules, discardPendingChanges, domainFirstPackages, fileModuleKind, filesToOverwrite, findWiredModules, hasNeighboringBoundedContext, implementationKinds, implementationLabelSchema, implementationType, isCrossContextImplementation, isOutdatedConfig, isSuggestedFor, moduleKindOf, namedImportFiles, outdatedConfigMessage, pendingChanges, readWiredModule, relativeImport, rulesSchema, scaffoldBackendRules, stripJsonComments, wireBranches, wireDependencies, wiredDependencyNames, wiring_layers, withoutOverwrites, writePendingChanges };
1035
+ export { ConfigFile, File, Folder, NestedName, ProjectRoot, UnknownFormatNaming, addBranchedImplementation, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, boundedContextLocation, boundedContextName, boundedContextNames, boundedContextPath, boundedContextsFolderName, branchNameSchema, canDependOn, compilerOption, configFileName, configSchema, configuredDependencyRules, crossContextImplementation, crossContextImportAllowed, defaultDependencyRules, discardPendingChanges, domainFirstPackages, fileModuleKind, filesToOverwrite, findWiredModules, hasNeighboringBoundedContext, implementationKinds, implementationLabelSchema, implementationType, isCrossContextImplementation, isOutdatedConfig, isSuggestedFor, moduleKindOf, namedImportFiles, outdatedConfigMessage, pendingChanges, readWiredModule, relativeImport, rulesSchema, scaffoldBackendRules, splitContextSegments, stripJsonComments, validateBoundedContextName, wireBranches, wireDependencies, wiredDependencyNames, wiring_layers, withoutOverwrites, writePendingChanges };
package/dist/287.js CHANGED
@@ -3,7 +3,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, search, select as prompts_select } from "@inquirer/prompts";
4
4
  import node_fs from "node:fs";
5
5
  import { styleText } from "node:util";
6
- import { availableDependencies, isSuggestedFor, domainFirstPackages as config_file_domainFirstPackages, scaffoldBackendRules, discardPendingChanges, UnknownFormatNaming, findWiredModules, Folder, compilerOption, implementationKinds, writePendingChanges, readWiredModule, addBranchedImplementation, hasNeighboringBoundedContext, implementationLabelSchema, withoutOverwrites, boundedContextLocation, branchNameSchema, filesToOverwrite, ConfigFile, relativeImport, wireBranches, wireDependencies, File, ProjectRoot, crossContextImportAllowed, crossContextImplementation, implementationType as wiring_implementationType } from "./201.js";
6
+ import { scaffoldBackendRules, findWiredModules, UnknownFormatNaming, Folder, writePendingChanges, splitContextSegments, addBranchedImplementation, hasNeighboringBoundedContext, implementationLabelSchema, boundedContextLocation, branchNameSchema, wireDependencies, ProjectRoot, boundedContextsFolderName, crossContextImplementation, boundedContextName, availableDependencies, compilerOption, domainFirstPackages as config_file_domainFirstPackages, discardPendingChanges, implementationKinds, readWiredModule, boundedContextNames, withoutOverwrites, validateBoundedContextName, filesToOverwrite, ConfigFile, relativeImport, wireBranches, NestedName, implementationType as wiring_implementationType, File, crossContextImportAllowed, isSuggestedFor } from "./201.js";
7
7
  import { codeExtension, restControllers, missingDomainFirstPackages, isPathParameterName, keepInMemoryDbSection, walk, escapeRegExp, wireInMemoryDb, projectImports, pathParameterAsName, stageModuleMove, hasLegacyRootEndpoints, inMemoryImplementationType, toPosix, rootStaticSegments, inMemoryDbScaffolded, scaffoldInMemoryDb, injectInMemoryDb, isInMemoryDb, openapiExtractorPath, inMemoryDbTypeImport, addInMemoryDbSection, openapiExtractor, plural, missingPackages, inMemoryDbSectionMembers, usesInMemoryDb, hasDependency } from "./115.js";
8
8
  const moduleId = (module)=>`${boundedContextLocation(module.typeFile)?.name ?? 'shared-kernel'}:${module.typeName}`;
9
9
  const unitId = (unit)=>`${unit.kind}:${unit.aggregate ? `${unit.aggregate}/` : ''}${unit.name}`;
@@ -385,28 +385,6 @@ const addInMemoryDb = ()=>{
385
385
  return [];
386
386
  };
387
387
  const inMemoryDbApplied = ()=>Boolean(ConfigFile.Instance.data.backend?.withInMemoryDb) && inMemoryDbScaffolded();
388
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
389
- class NestedName {
390
- folders;
391
- folderName;
392
- fileName;
393
- ClassName;
394
- classNameSegments;
395
- constructor(rawSource){
396
- const segments = splitSegments(rawSource);
397
- this.folders = segments.slice(0, -1);
398
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
399
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
400
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
401
- this.ClassName = this.classNameSegments.join('');
402
- }
403
- static validate = (rawSource)=>{
404
- const segments = splitSegments(rawSource);
405
- if (!segments.length) return 'Name is required';
406
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
407
- return true;
408
- };
409
- }
410
388
  const usesNext = ()=>ConfigFile.exists && ConfigFile.Instance.data.frontend?.react?.framework === 'next';
411
389
  const nextAppFolder = (root)=>[
412
390
  'app',
@@ -1085,9 +1063,7 @@ const dependencyOptions = (boundedContextFolder)=>{
1085
1063
  module: x,
1086
1064
  label: `${x.typeName} (shared-kernel)`
1087
1065
  })),
1088
- ...isShared ? [] : contextsFolder.content.subfolderNames.filter((name)=>name !== boundedContextFolder.name).sort().flatMap((name)=>findWiredModules(contextsFolder.subitem([
1089
- name
1090
- ]).path).map((module)=>({
1066
+ ...isShared ? [] : boundedContextNames(contextsFolder.path).filter((name)=>name !== boundedContextName(boundedContextFolder.path)).flatMap((name)=>findWiredModules(contextsFolder.subitem(name.split('/')).path).map((module)=>({
1091
1067
  module,
1092
1068
  label: `${module.typeName} (${name})`
1093
1069
  })))
@@ -1560,7 +1536,7 @@ const integrationSpecFile = (unit, label)=>{
1560
1536
  ]).find((file)=>file.startsWith(`${layout.implementations}/${label}/`)) : void 0;
1561
1537
  const projectRoot = projectRootOf(unit.ownerPath);
1562
1538
  if (!source || !projectRoot) return;
1563
- return node_path.join(projectRoot, integrationSpecsFolder, node_path.basename(unit.ownerPath), source.slice(15).replace(/\.ts$/, '.spec.ts'));
1539
+ return node_path.join(projectRoot, integrationSpecsFolder, ...(boundedContextName(unit.ownerPath) ?? node_path.basename(unit.ownerPath)).split('/'), source.slice(15).replace(/\.ts$/, '.spec.ts'));
1564
1540
  };
1565
1541
  const integrationSpecSubjects = (unit)=>'infrastructure-service' === unit.kind ? [
1566
1542
  void 0
@@ -1649,11 +1625,14 @@ const validateBackendMove = (unit, target, sharedKernelPath)=>{
1649
1625
  return true;
1650
1626
  };
1651
1627
  const ownerOf = (rootFolderPath, file)=>{
1652
- const [area, context] = node_path.relative(rootFolderPath, file).split(node_path.sep);
1653
- if ('bounded-contexts' === area && context) return {
1654
- context,
1655
- path: node_path.join(rootFolderPath, area, context)
1656
- };
1628
+ const [area, ...segments] = node_path.relative(rootFolderPath, file).split(node_path.sep);
1629
+ if ('bounded-contexts' === area && segments.length) {
1630
+ const context = splitContextSegments(segments).name;
1631
+ return {
1632
+ context,
1633
+ path: node_path.join(rootFolderPath, area, ...context.split('/'))
1634
+ };
1635
+ }
1657
1636
  if ('shared-kernel' === area) return {
1658
1637
  context: void 0,
1659
1638
  path: node_path.join(rootFolderPath, area)
@@ -2165,6 +2144,10 @@ const envBranchedWireArgument = (testWire, primaryWire)=>{
2165
2144
  ...primary.map((name)=>` ${name}: ${primaryWire}`)
2166
2145
  ].join(',\n')}\n}`;
2167
2146
  };
2147
+ const envBranchedWireImport = (wireFolder)=>{
2148
+ const relativePath = node_path.relative(wireFolder, node_path.join(new ProjectRoot().path, ConfigFile.Instance.data.project.rootFolder, 'shared-kernel', 'wiring', 'env-branched-wire')).split(node_path.sep).join('/');
2149
+ return `import { envBranchedWire } from '${relativePath.startsWith('.') ? relativePath : `./${relativePath}`}'`;
2150
+ };
2168
2151
  const envBranchedWireSource = ()=>{
2169
2152
  const { names, custom } = wire_branches_envBranches();
2170
2153
  if (!custom) return `import { branchedWire } from '@domain-first/wire'
@@ -2345,11 +2328,11 @@ const configureIntegrationTests = async (root)=>{
2345
2328
  source.subitem([
2346
2329
  'shared-kernel'
2347
2330
  ]),
2348
- ...source.subitem([
2331
+ ...boundedContextNames(source.subitem([
2349
2332
  'bounded-contexts'
2350
- ]).content.subfolderNames.sort().map((name)=>source.subitem([
2333
+ ]).path).map((name)=>source.subitem([
2351
2334
  'bounded-contexts',
2352
- name
2335
+ ...name.split('/')
2353
2336
  ]))
2354
2337
  ];
2355
2338
  for (const owner of owners)for (const unit of findContracts(owner.path)){
@@ -2455,10 +2438,10 @@ export default defineConfig({
2455
2438
  exclude: [
2456
2439
  '**/*.spec.ts',
2457
2440
  ${folder('shared-kernel/infrastructure/**')},
2458
- ${folder('bounded-contexts/*/infrastructure/**')},
2459
- ${folder('bounded-contexts/*/presentation/rest/**')},
2441
+ ${folder('bounded-contexts/**/infrastructure/**')},
2442
+ ${folder('bounded-contexts/**/presentation/rest/**')},
2460
2443
  ${folder('shared-kernel/wiring/**')},
2461
- ${folder('bounded-contexts/*/wiring/**')}
2444
+ ${folder('bounded-contexts/**/wiring/**')}
2462
2445
  ],
2463
2446
  reporter: [['text', { skipFull: true }], 'html']
2464
2447
  }${server}
@@ -3373,10 +3356,8 @@ const moveBackendUnitUseCase = async (ownerFolder)=>{
3373
3356
  }),
3374
3357
  pageSize: 20
3375
3358
  });
3376
- const placeName = (ownerPath)=>ownerPath === sharedKernelPath ? 'Shared Kernel' : `Bounded Context: ${node_path.basename(ownerPath)}`;
3377
- const contexts = new Folder(rootFolderPath).subitem([
3378
- 'bounded-contexts'
3379
- ]).content.subfolderNames.map((name)=>node_path.join(rootFolderPath, 'bounded-contexts', name));
3359
+ const placeName = (ownerPath)=>ownerPath === sharedKernelPath ? 'Shared Kernel' : `Bounded Context: ${boundedContextName(ownerPath)}`;
3360
+ const contexts = boundedContextNames(node_path.join(rootFolderPath, 'bounded-contexts')).map((name)=>node_path.join(rootFolderPath, 'bounded-contexts', ...name.split('/')));
3380
3361
  const places = [
3381
3362
  unit.ownerPath,
3382
3363
  ...contexts,
@@ -3386,7 +3367,7 @@ const moveBackendUnitUseCase = async (ownerFolder)=>{
3386
3367
  ].filter((place, index, all)=>all.indexOf(place) === index);
3387
3368
  const ownerPath = await interaction_select({
3388
3369
  key: 'targetContext',
3389
- id: (owner)=>owner === sharedKernelPath ? 'shared-kernel' : node_path.basename(owner),
3370
+ id: (owner)=>owner === sharedKernelPath ? 'shared-kernel' : boundedContextName(owner) ?? node_path.basename(owner),
3390
3371
  message: 'Move to:',
3391
3372
  choices: places.map((value)=>({
3392
3373
  name: value === unit.ownerPath ? `${placeName(value)} (stays)` : placeName(value),
@@ -3679,7 +3660,10 @@ describe('${aggregateNaming.withSpaces}', () => {
3679
3660
  'repositories'
3680
3661
  ]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
3681
3662
  import { wireClass } from '@domain-first/wire'
3682
- import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
3663
+ ${envBranchedWireImport(boundedContextFolder.subitem([
3664
+ 'wiring',
3665
+ 'repositories'
3666
+ ]).path)}
3683
3667
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${aggregateNaming.ClassName}Repository } from '../../infrastructure/repositories/${fileName}/${fileName}-${aggregateNaming.fileName}-repository'`).join('\n')}
3684
3668
 
3685
3669
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${aggregateNaming.ClassName}Repository, [])`).join('\n\n')}
@@ -3748,7 +3732,7 @@ export abstract class ${naming.ClassName} {
3748
3732
  if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
3749
3733
  const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
3750
3734
  import { wireClass } from '@domain-first/wire'
3751
- import { envBranchedWire } from '../../../${'shared-kernel' === boundedContextFolder.name ? '' : '../'}shared-kernel/wiring/env-branched-wire'
3735
+ ${envBranchedWireImport(wiringFolder.path)}
3752
3736
  ${implementationTypes.map((x)=>({
3753
3737
  naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
3754
3738
  implementation: x
@@ -3822,19 +3806,19 @@ export const wire${naming.ClassName}ApplicationService = wireClass(
3822
3806
  }
3823
3807
  };
3824
3808
  const scaffoldNewBoundedContextUseCase = async ()=>{
3809
+ const rootFolder = new Folder(new ProjectRoot().path).subitem([
3810
+ ConfigFile.Instance.data.project.rootFolder
3811
+ ]);
3812
+ const contextsFolder = node_path.join(rootFolder.path, boundedContextsFolderName);
3825
3813
  const name = await interaction_input({
3826
3814
  key: 'name',
3827
- message: 'Name:',
3828
- validate: (x)=>!!x.length
3815
+ message: 'Name (folders split by "/"):',
3816
+ validate: (value)=>validateBoundedContextName(contextsFolder, value)
3829
3817
  });
3830
- const { path } = new ProjectRoot();
3831
- const rootFolder = new Folder(path);
3832
- const folder = rootFolder.subitem([
3833
- ConfigFile.Instance.data.project.rootFolder,
3834
- 'bounded-contexts',
3835
- name
3836
- ]);
3837
- folder.createIfNotExisted();
3818
+ rootFolder.subitem([
3819
+ boundedContextsFolderName,
3820
+ ...name.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment)
3821
+ ]).createIfNotExisted();
3838
3822
  };
3839
3823
  const scaffoldNewCommand = async (boundedContextFolder)=>{
3840
3824
  const commandsFolder = boundedContextFolder.subitem([
@@ -3896,7 +3880,10 @@ export abstract class ${naming.ClassName}Command {
3896
3880
  'commands'
3897
3881
  ]).createFile(`wire-${naming.fileName}-command.ts`, `
3898
3882
  import { wireClass } from '@domain-first/wire'
3899
- import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
3883
+ ${envBranchedWireImport(boundedContextFolder.subitem([
3884
+ 'wiring',
3885
+ 'commands'
3886
+ ]).path)}
3900
3887
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Command } from '../../infrastructure/commands/${fileName}/${fileName}-${naming.fileName}-command'`).join('\n')}
3901
3888
 
3902
3889
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Command, [])`).join('\n\n')}
@@ -4048,7 +4035,8 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
4048
4035
  'errors'
4049
4036
  ]);
4050
4037
  const names = errorNames(boundedContextFolder);
4051
- const contextNaming = new UnknownFormatNaming(boundedContextFolder.name);
4038
+ const contextName = boundedContextName(boundedContextFolder.path) ?? boundedContextFolder.name;
4039
+ const contextNaming = new NestedName(contextName);
4052
4040
  const currentErrorNamespaces = currentErrorFolder.content.fileNames.filter((x)=>'index' !== x);
4053
4041
  const variants = [
4054
4042
  'New error without namespace',
@@ -4067,7 +4055,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
4067
4055
  });
4068
4056
  const naming = new UnknownFormatNaming(errorName);
4069
4057
  const indexFile = currentErrorFolder.file('index.ts');
4070
- indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), rootNamespace(indexFile, `${contextNaming.ClassName}Errors`, boundedContextFolder.name), naming.fileName), '\n\n');
4058
+ indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), rootNamespace(indexFile, `${contextNaming.ClassName}Errors`, contextName), naming.fileName), '\n\n');
4071
4059
  return;
4072
4060
  }
4073
4061
  if ('New namespace' === selectedVariant) {
@@ -4079,7 +4067,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
4079
4067
  if (!currentErrorFolder.file(`${fileName}.ts`).exists) currentErrorFolder.createFile(`${fileName}.ts`, `
4080
4068
  import { errorNamespace } from '@domain-first/errors'
4081
4069
 
4082
- export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
4070
+ export const ${names.namespace(ClassName)} = errorNamespace('${contextName}').subnamespace('${fileName}')
4083
4071
  `.trim());
4084
4072
  currentErrorFolder.file('index.ts').addLineIfMissing(`export * from './${fileName}'`, '\n\n');
4085
4073
  return;
@@ -4096,15 +4084,17 @@ export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFol
4096
4084
  };
4097
4085
  const newController = 'New controller';
4098
4086
  const rootControllerChoice = 'No controller (context root)';
4099
- const sharedRestFolder = (boundedContextFolder)=>boundedContextFolder.subitem([
4100
- '..',
4101
- '..',
4087
+ const sourceFolder = ()=>new Folder(new ProjectRoot().path).subitem([
4088
+ ConfigFile.Instance.data.project.rootFolder
4089
+ ]);
4090
+ const sharedRestFolder = ()=>sourceFolder().subitem([
4102
4091
  'presentation',
4103
4092
  'rest'
4104
4093
  ]);
4105
4094
  const legacyRootEndpointsMessage = (context)=>`${context} keeps its context-root endpoints in the 8.5 layout (presentation/rest/<METHOD>.ts, _param_/). Run npx df-upgrade to move them to presentation/rest/(root)/ first.`;
4106
4095
  const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
4107
- const context = boundedContextFolder.name;
4096
+ const context = boundedContextName(boundedContextFolder.path) ?? boundedContextFolder.name;
4097
+ const contextSegments = context.split('/');
4108
4098
  const restPresentationFolder = boundedContextFolder.subitem([
4109
4099
  'presentation',
4110
4100
  'rest'
@@ -4162,7 +4152,7 @@ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
4162
4152
  ...routeSegments
4163
4153
  ];
4164
4154
  const routePath = [
4165
- context,
4155
+ ...contextSegments,
4166
4156
  ...controller ? [
4167
4157
  controller
4168
4158
  ] : [],
@@ -4170,7 +4160,9 @@ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
4170
4160
  ];
4171
4161
  const endpointFolder = restPresentationFolder.subitem(folderSegments.map(pathParameterAsName));
4172
4162
  const nameSegments = [
4173
- controller ?? context,
4163
+ ...controller ? [
4164
+ controller
4165
+ ] : contextSegments,
4174
4166
  ...routeSegments
4175
4167
  ];
4176
4168
  const nameBase = `${[
@@ -4182,9 +4174,7 @@ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
4182
4174
  method,
4183
4175
  'endpoint'
4184
4176
  ].map((segment)=>segment.startsWith(':') ? pathParameterAsName(segment) : new UnknownFormatNaming(segment).ClassName).join('');
4185
- const endpointGenerator = findRestEndpointGenerator(boundedContextFolder.subitem([
4186
- '..',
4187
- '..',
4177
+ const endpointGenerator = findRestEndpointGenerator(sourceFolder().subitem([
4188
4178
  'shared-kernel'
4189
4179
  ]));
4190
4180
  const handler = withWiring ? await promptEndpointHandler(boundedContextFolder) : void 0;
@@ -4237,9 +4227,9 @@ export const wire${endpointClassName} = wireClass(
4237
4227
  'presentation',
4238
4228
  'rest'
4239
4229
  ]).file('index.ts').addLineIfMissing(`export * from './${group}'`);
4240
- sharedRestFolder(boundedContextFolder).file('wires.ts').addLineIfMissing(`export * from '../../bounded-contexts/${context}/wiring/presentation/rest/${group}'`);
4241
- const restHandlersFile = sharedRestFolder(boundedContextFolder).file('index.ts');
4242
- if (!restHandlersFile.exists) sharedRestFolder(boundedContextFolder).createFile('index.ts', `
4230
+ sharedRestFolder().file('wires.ts').addLineIfMissing(`export * from '../../bounded-contexts/${context}/wiring/presentation/rest/${group}'`);
4231
+ const restHandlersFile = sharedRestFolder().file('index.ts');
4232
+ if (!restHandlersFile.exists) sharedRestFolder().createFile('index.ts', `
4243
4233
  import * as wires from './wires'
4244
4234
 
4245
4235
  const restWires = Object.values(wires)
@@ -4500,7 +4490,10 @@ export abstract class ${naming.ClassName}Query {
4500
4490
  'queries'
4501
4491
  ]).createFile(`wire-${naming.fileName}-query.ts`, `
4502
4492
  import { wireClass } from '@domain-first/wire'
4503
- import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
4493
+ ${envBranchedWireImport(boundedContextFolder.subitem([
4494
+ 'wiring',
4495
+ 'queries'
4496
+ ]).path)}
4504
4497
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Query } from '../../infrastructure/queries/${fileName}/${fileName}-${naming.fileName}-query'`).join('\n')}
4505
4498
 
4506
4499
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Query, [])`).join('\n\n')}
package/dist/38.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import node_fs from "node:fs";
2
2
  import node_path from "node:path";
3
- import { defaultDependencyRules, fileModuleKind, namedImportFiles, canDependOn, isCrossContextImplementation, findWiredModules, moduleKindOf, readWiredModule, crossContextImportAllowed, compilerOption, wiredDependencyNames } from "./201.js";
3
+ import { defaultDependencyRules, fileModuleKind, namedImportFiles, canDependOn, isCrossContextImplementation, findWiredModules, wiredDependencyNames, boundedContextPath, moduleKindOf, splitContextSegments, readWiredModule, crossContextImportAllowed, compilerOption, boundedContextNames } from "./201.js";
4
4
  const readAliases = (projectRoot)=>{
5
5
  const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
6
6
  const paths = compilerOption(tsconfig, 'paths');
@@ -104,12 +104,16 @@ const importViolations = (projectRoot, rootFolder, rules)=>{
104
104
  const inMemoryDbFile = node_path.join(sharedFolder, 'infrastructure', 'services', 'in-memory-db-infrastructure-service.ts');
105
105
  const aliases = readAliases(projectRoot);
106
106
  const violations = [];
107
+ const contextOf = (file)=>{
108
+ const segments = inside(contextsFolder, file);
109
+ return segments && splitContextSegments(segments).name;
110
+ };
107
111
  const locate = (file)=>{
108
112
  const inContext = inside(contextsFolder, file);
109
113
  if (inContext && inContext.length > 1) {
110
- const [owner, ...segments] = inContext;
114
+ const { name, segments } = splitContextSegments(inContext);
111
115
  return {
112
- owner,
116
+ owner: name,
113
117
  segments
114
118
  };
115
119
  }
@@ -148,8 +152,8 @@ const importViolations = (projectRoot, rootFolder, rules)=>{
148
152
  line: 1,
149
153
  text: node_path.basename(file)
150
154
  });
151
- const ownContext = inside(contextsFolder, file)?.[0];
152
- const directWiring = ownContext && from?.segments[0] === 'wiring' && readWiredModule(file, node_path.join(contextsFolder, ownContext))?.implementations.some((implementation)=>isCrossContextImplementation(implementation.file));
155
+ const ownContext = contextOf(file);
156
+ const directWiring = ownContext && from?.segments[0] === 'wiring' && readWiredModule(file, boundedContextPath(contextsFolder, ownContext))?.implementations.some((implementation)=>isCrossContextImplementation(implementation.file));
153
157
  const report = (check, rule, imported)=>violations.push({
154
158
  check,
155
159
  rule,
@@ -161,7 +165,7 @@ const importViolations = (projectRoot, rootFolder, rules)=>{
161
165
  const target = imported.target;
162
166
  if (!target) continue;
163
167
  const to = locate(target);
164
- const targetContext = inside(contextsFolder, target)?.[0];
168
+ const targetContext = contextOf(target);
165
169
  const crossContextAllowed = true === crossContextImportAllowed(file, target) && (from?.segments[0] !== 'wiring' || directWiring);
166
170
  if (ownContext) {
167
171
  if (targetContext && targetContext !== ownContext && !crossContextAllowed) report('context-isolation', `[${ownContext}] imports another context:`, imported);
@@ -210,12 +214,10 @@ const wiringViolations = (projectRoot, rootFolder, rules)=>{
210
214
  name: 'shared-kernel',
211
215
  modules: sharedModules
212
216
  },
213
- ...node_fs.existsSync(contextsFolder) ? node_fs.readdirSync(contextsFolder, {
214
- withFileTypes: true
215
- }).filter((entry)=>entry.isDirectory()).map((entry)=>({
216
- name: entry.name,
217
- modules: findWiredModules(node_path.join(contextsFolder, entry.name))
218
- })) : []
217
+ ...boundedContextNames(contextsFolder).map((name)=>({
218
+ name,
219
+ modules: findWiredModules(boundedContextPath(contextsFolder, name))
220
+ }))
219
221
  ];
220
222
  const violations = [];
221
223
  const allModules = new Map(owners.flatMap(({ modules })=>modules).map((module)=>[
@@ -276,7 +278,7 @@ const directReadViolations = (projectRoot, rootFolder)=>{
276
278
  const root = node_path.resolve(projectRoot, rootFolder);
277
279
  const folders = [
278
280
  node_path.join(root, 'shared-kernel'),
279
- ...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)) : []
281
+ ...boundedContextNames(node_path.join(root, 'bounded-contexts')).map((name)=>boundedContextPath(node_path.join(root, 'bounded-contexts'), name))
280
282
  ].flatMap((folder)=>[
281
283
  node_path.join(folder, 'domain'),
282
284
  node_path.join(folder, 'application')