@domain-first/project-structure 8.9.1 → 8.10.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/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}`;
@@ -390,28 +390,6 @@ const nextAppFolder = (root)=>[
390
390
  'app',
391
391
  'src/app'
392
392
  ].find((folder)=>new Folder(node_path.join(root, folder)).exists) ?? 'app';
393
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
394
- class NestedName {
395
- folders;
396
- folderName;
397
- fileName;
398
- ClassName;
399
- classNameSegments;
400
- constructor(rawSource){
401
- const segments = splitSegments(rawSource);
402
- this.folders = segments.slice(0, -1);
403
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
404
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
405
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
406
- this.ClassName = this.classNameSegments.join('');
407
- }
408
- static validate = (rawSource)=>{
409
- const segments = splitSegments(rawSource);
410
- if (!segments.length) return 'Name is required';
411
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
412
- return true;
413
- };
414
- }
415
393
  const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
416
394
  ${[
417
395
  ...imports,
@@ -431,13 +409,14 @@ export default function Page() {
431
409
  return <${ClassName}Page />
432
410
  }
433
411
  `.trim();
434
- const scaffoldNextRoute = (name, pageFile)=>{
412
+ const scaffoldNextRoute = (name, pagePath)=>{
435
413
  const root = new ProjectRoot().path;
436
414
  const route = node_path.join(root, nextAppFolder(root), ...name.folders, name.folderName, 'page.tsx');
437
415
  const relativeRoute = node_path.relative(root, route).split(node_path.sep).join('/');
438
416
  const routeFile = new File(route);
439
- if (routeFile.exists) return void report(`${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`);
440
- routeFile.data = nextRouteContent(name.ClassName, relativeImport(route, pageFile.path.replace(/\.tsx$/, '')));
417
+ const content = nextRouteContent(name.ClassName, relativeImport(route, pagePath.replace(/\.tsx$/, '')));
418
+ if (routeFile.exists) return routeFile.data === content ? void 0 : `${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`;
419
+ routeFile.data = content;
441
420
  };
442
421
  const scaffoldReactPage = async (presentationReactFolder)=>{
443
422
  const name = await interaction_input({
@@ -451,7 +430,10 @@ const scaffoldReactPage = async (presentationReactFolder)=>{
451
430
  'pages',
452
431
  ...folders
453
432
  ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
454
- if (usesNext()) scaffoldNextRoute(nestedName, pageFile);
433
+ if (usesNext()) {
434
+ const hint = scaffoldNextRoute(nestedName, pageFile.path);
435
+ if (hint) report(hint);
436
+ }
455
437
  };
456
438
  const openapiScriptPath = "scripts/generate-openapi.ts";
457
439
  const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
@@ -460,9 +442,9 @@ const extractorPackages = [
460
442
  '@microsoft/tsdoc'
461
443
  ];
462
444
  const swaggerPagePath = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
463
- const swaggerPage = (rootFolder, outputPath)=>{
445
+ const swaggerPage = (rootFolder, outputPath, withNext = false)=>{
464
446
  const specImport = node_path.posix.relative(node_path.posix.dirname(swaggerPagePath(rootFolder)), outputPath);
465
- return reactPageContent('Swagger', {
447
+ const page = reactPageContent('Swagger', {
466
448
  imports: [
467
449
  "import 'swagger-ui-react/swagger-ui.css'",
468
450
  "import SwaggerUI from 'swagger-ui-react'",
@@ -470,6 +452,7 @@ const swaggerPage = (rootFolder, outputPath)=>{
470
452
  ],
471
453
  body: '<SwaggerUI displayOperationId spec={spec} />'
472
454
  });
455
+ return withNext ? `'use client'\n\n${page}` : page;
473
456
  };
474
457
  const openapiScripts = {
475
458
  openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
@@ -551,10 +534,14 @@ const addOpenapi = async ()=>{
551
534
  const generatorFile = new File(node_path.join(root, openapiScriptPath));
552
535
  const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
553
536
  if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
537
+ const withNextRoute = withSwaggerPage && usesNext();
538
+ let nextRouteHint;
554
539
  if (withSwaggerPage) {
555
- const pageFile = new File(node_path.join(root, swaggerPagePath(rootFolder)));
556
- const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
540
+ const pagePath = node_path.join(root, swaggerPagePath(rootFolder));
541
+ const pageFile = new File(pagePath);
542
+ const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'), withNextRoute);
557
543
  if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
544
+ if (withNextRoute) nextRouteHint = scaffoldNextRoute(new NestedName('swagger'), pagePath);
558
545
  }
559
546
  const resolveJsonModule = withSwaggerPage ? compilerOption(node_path.join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
560
547
  const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
@@ -581,9 +568,12 @@ const addOpenapi = async ()=>{
581
568
  ...describeScripts(selected, {
582
569
  openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
583
570
  }),
584
- ...withSwaggerPage ? [
571
+ ...withSwaggerPage && !withNextRoute ? [
585
572
  `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
586
573
  ] : [],
574
+ ...withNextRoute ? [
575
+ nextRouteHint ?? `/swagger shows ${splitPath(outputPath).join('/')} once it is generated — the route is ${nextAppFolder(root)}/swagger/page.tsx`
576
+ ] : [],
587
577
  ...hasRestHandlers ? [] : [
588
578
  `restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
589
579
  ]
@@ -1073,9 +1063,7 @@ const dependencyOptions = (boundedContextFolder)=>{
1073
1063
  module: x,
1074
1064
  label: `${x.typeName} (shared-kernel)`
1075
1065
  })),
1076
- ...isShared ? [] : contextsFolder.content.subfolderNames.filter((name)=>name !== boundedContextFolder.name).sort().flatMap((name)=>findWiredModules(contextsFolder.subitem([
1077
- name
1078
- ]).path).map((module)=>({
1066
+ ...isShared ? [] : boundedContextNames(contextsFolder.path).filter((name)=>name !== boundedContextName(boundedContextFolder.path)).flatMap((name)=>findWiredModules(contextsFolder.subitem(name.split('/')).path).map((module)=>({
1079
1067
  module,
1080
1068
  label: `${module.typeName} (${name})`
1081
1069
  })))
@@ -1548,7 +1536,7 @@ const integrationSpecFile = (unit, label)=>{
1548
1536
  ]).find((file)=>file.startsWith(`${layout.implementations}/${label}/`)) : void 0;
1549
1537
  const projectRoot = projectRootOf(unit.ownerPath);
1550
1538
  if (!source || !projectRoot) return;
1551
- 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'));
1552
1540
  };
1553
1541
  const integrationSpecSubjects = (unit)=>'infrastructure-service' === unit.kind ? [
1554
1542
  void 0
@@ -1637,11 +1625,14 @@ const validateBackendMove = (unit, target, sharedKernelPath)=>{
1637
1625
  return true;
1638
1626
  };
1639
1627
  const ownerOf = (rootFolderPath, file)=>{
1640
- const [area, context] = node_path.relative(rootFolderPath, file).split(node_path.sep);
1641
- if ('bounded-contexts' === area && context) return {
1642
- context,
1643
- path: node_path.join(rootFolderPath, area, context)
1644
- };
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
+ }
1645
1636
  if ('shared-kernel' === area) return {
1646
1637
  context: void 0,
1647
1638
  path: node_path.join(rootFolderPath, area)
@@ -2153,6 +2144,10 @@ const envBranchedWireArgument = (testWire, primaryWire)=>{
2153
2144
  ...primary.map((name)=>` ${name}: ${primaryWire}`)
2154
2145
  ].join(',\n')}\n}`;
2155
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
+ };
2156
2151
  const envBranchedWireSource = ()=>{
2157
2152
  const { names, custom } = wire_branches_envBranches();
2158
2153
  if (!custom) return `import { branchedWire } from '@domain-first/wire'
@@ -2333,11 +2328,11 @@ const configureIntegrationTests = async (root)=>{
2333
2328
  source.subitem([
2334
2329
  'shared-kernel'
2335
2330
  ]),
2336
- ...source.subitem([
2331
+ ...boundedContextNames(source.subitem([
2337
2332
  'bounded-contexts'
2338
- ]).content.subfolderNames.sort().map((name)=>source.subitem([
2333
+ ]).path).map((name)=>source.subitem([
2339
2334
  'bounded-contexts',
2340
- name
2335
+ ...name.split('/')
2341
2336
  ]))
2342
2337
  ];
2343
2338
  for (const owner of owners)for (const unit of findContracts(owner.path)){
@@ -2443,10 +2438,10 @@ export default defineConfig({
2443
2438
  exclude: [
2444
2439
  '**/*.spec.ts',
2445
2440
  ${folder('shared-kernel/infrastructure/**')},
2446
- ${folder('bounded-contexts/*/infrastructure/**')},
2447
- ${folder('bounded-contexts/*/presentation/rest/**')},
2441
+ ${folder('bounded-contexts/**/infrastructure/**')},
2442
+ ${folder('bounded-contexts/**/presentation/rest/**')},
2448
2443
  ${folder('shared-kernel/wiring/**')},
2449
- ${folder('bounded-contexts/*/wiring/**')}
2444
+ ${folder('bounded-contexts/**/wiring/**')}
2450
2445
  ],
2451
2446
  reporter: [['text', { skipFull: true }], 'html']
2452
2447
  }${server}
@@ -3361,10 +3356,8 @@ const moveBackendUnitUseCase = async (ownerFolder)=>{
3361
3356
  }),
3362
3357
  pageSize: 20
3363
3358
  });
3364
- const placeName = (ownerPath)=>ownerPath === sharedKernelPath ? 'Shared Kernel' : `Bounded Context: ${node_path.basename(ownerPath)}`;
3365
- const contexts = new Folder(rootFolderPath).subitem([
3366
- 'bounded-contexts'
3367
- ]).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('/')));
3368
3361
  const places = [
3369
3362
  unit.ownerPath,
3370
3363
  ...contexts,
@@ -3374,7 +3367,7 @@ const moveBackendUnitUseCase = async (ownerFolder)=>{
3374
3367
  ].filter((place, index, all)=>all.indexOf(place) === index);
3375
3368
  const ownerPath = await interaction_select({
3376
3369
  key: 'targetContext',
3377
- id: (owner)=>owner === sharedKernelPath ? 'shared-kernel' : node_path.basename(owner),
3370
+ id: (owner)=>owner === sharedKernelPath ? 'shared-kernel' : boundedContextName(owner) ?? node_path.basename(owner),
3378
3371
  message: 'Move to:',
3379
3372
  choices: places.map((value)=>({
3380
3373
  name: value === unit.ownerPath ? `${placeName(value)} (stays)` : placeName(value),
@@ -3667,7 +3660,10 @@ describe('${aggregateNaming.withSpaces}', () => {
3667
3660
  'repositories'
3668
3661
  ]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
3669
3662
  import { wireClass } from '@domain-first/wire'
3670
- import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
3663
+ ${envBranchedWireImport(boundedContextFolder.subitem([
3664
+ 'wiring',
3665
+ 'repositories'
3666
+ ]).path)}
3671
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')}
3672
3668
 
3673
3669
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${aggregateNaming.ClassName}Repository, [])`).join('\n\n')}
@@ -3736,7 +3732,7 @@ export abstract class ${naming.ClassName} {
3736
3732
  if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
3737
3733
  const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
3738
3734
  import { wireClass } from '@domain-first/wire'
3739
- import { envBranchedWire } from '../../../${'shared-kernel' === boundedContextFolder.name ? '' : '../'}shared-kernel/wiring/env-branched-wire'
3735
+ ${envBranchedWireImport(wiringFolder.path)}
3740
3736
  ${implementationTypes.map((x)=>({
3741
3737
  naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
3742
3738
  implementation: x
@@ -3810,19 +3806,19 @@ export const wire${naming.ClassName}ApplicationService = wireClass(
3810
3806
  }
3811
3807
  };
3812
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);
3813
3813
  const name = await interaction_input({
3814
3814
  key: 'name',
3815
- message: 'Name:',
3816
- validate: (x)=>!!x.length
3815
+ message: 'Name (folders split by "/"):',
3816
+ validate: (value)=>validateBoundedContextName(contextsFolder, value)
3817
3817
  });
3818
- const { path } = new ProjectRoot();
3819
- const rootFolder = new Folder(path);
3820
- const folder = rootFolder.subitem([
3821
- ConfigFile.Instance.data.project.rootFolder,
3822
- 'bounded-contexts',
3823
- name
3824
- ]);
3825
- folder.createIfNotExisted();
3818
+ rootFolder.subitem([
3819
+ boundedContextsFolderName,
3820
+ ...name.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment)
3821
+ ]).createIfNotExisted();
3826
3822
  };
3827
3823
  const scaffoldNewCommand = async (boundedContextFolder)=>{
3828
3824
  const commandsFolder = boundedContextFolder.subitem([
@@ -3884,7 +3880,10 @@ export abstract class ${naming.ClassName}Command {
3884
3880
  'commands'
3885
3881
  ]).createFile(`wire-${naming.fileName}-command.ts`, `
3886
3882
  import { wireClass } from '@domain-first/wire'
3887
- import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
3883
+ ${envBranchedWireImport(boundedContextFolder.subitem([
3884
+ 'wiring',
3885
+ 'commands'
3886
+ ]).path)}
3888
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')}
3889
3888
 
3890
3889
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Command, [])`).join('\n\n')}
@@ -4036,7 +4035,8 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
4036
4035
  'errors'
4037
4036
  ]);
4038
4037
  const names = errorNames(boundedContextFolder);
4039
- const contextNaming = new UnknownFormatNaming(boundedContextFolder.name);
4038
+ const contextName = boundedContextName(boundedContextFolder.path) ?? boundedContextFolder.name;
4039
+ const contextNaming = new NestedName(contextName);
4040
4040
  const currentErrorNamespaces = currentErrorFolder.content.fileNames.filter((x)=>'index' !== x);
4041
4041
  const variants = [
4042
4042
  'New error without namespace',
@@ -4055,7 +4055,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
4055
4055
  });
4056
4056
  const naming = new UnknownFormatNaming(errorName);
4057
4057
  const indexFile = currentErrorFolder.file('index.ts');
4058
- 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');
4059
4059
  return;
4060
4060
  }
4061
4061
  if ('New namespace' === selectedVariant) {
@@ -4067,7 +4067,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
4067
4067
  if (!currentErrorFolder.file(`${fileName}.ts`).exists) currentErrorFolder.createFile(`${fileName}.ts`, `
4068
4068
  import { errorNamespace } from '@domain-first/errors'
4069
4069
 
4070
- export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
4070
+ export const ${names.namespace(ClassName)} = errorNamespace('${contextName}').subnamespace('${fileName}')
4071
4071
  `.trim());
4072
4072
  currentErrorFolder.file('index.ts').addLineIfMissing(`export * from './${fileName}'`, '\n\n');
4073
4073
  return;
@@ -4084,15 +4084,17 @@ export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFol
4084
4084
  };
4085
4085
  const newController = 'New controller';
4086
4086
  const rootControllerChoice = 'No controller (context root)';
4087
- const sharedRestFolder = (boundedContextFolder)=>boundedContextFolder.subitem([
4088
- '..',
4089
- '..',
4087
+ const sourceFolder = ()=>new Folder(new ProjectRoot().path).subitem([
4088
+ ConfigFile.Instance.data.project.rootFolder
4089
+ ]);
4090
+ const sharedRestFolder = ()=>sourceFolder().subitem([
4090
4091
  'presentation',
4091
4092
  'rest'
4092
4093
  ]);
4093
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.`;
4094
4095
  const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
4095
- const context = boundedContextFolder.name;
4096
+ const context = boundedContextName(boundedContextFolder.path) ?? boundedContextFolder.name;
4097
+ const contextSegments = context.split('/');
4096
4098
  const restPresentationFolder = boundedContextFolder.subitem([
4097
4099
  'presentation',
4098
4100
  'rest'
@@ -4150,7 +4152,7 @@ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
4150
4152
  ...routeSegments
4151
4153
  ];
4152
4154
  const routePath = [
4153
- context,
4155
+ ...contextSegments,
4154
4156
  ...controller ? [
4155
4157
  controller
4156
4158
  ] : [],
@@ -4158,7 +4160,9 @@ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
4158
4160
  ];
4159
4161
  const endpointFolder = restPresentationFolder.subitem(folderSegments.map(pathParameterAsName));
4160
4162
  const nameSegments = [
4161
- controller ?? context,
4163
+ ...controller ? [
4164
+ controller
4165
+ ] : contextSegments,
4162
4166
  ...routeSegments
4163
4167
  ];
4164
4168
  const nameBase = `${[
@@ -4170,9 +4174,7 @@ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
4170
4174
  method,
4171
4175
  'endpoint'
4172
4176
  ].map((segment)=>segment.startsWith(':') ? pathParameterAsName(segment) : new UnknownFormatNaming(segment).ClassName).join('');
4173
- const endpointGenerator = findRestEndpointGenerator(boundedContextFolder.subitem([
4174
- '..',
4175
- '..',
4177
+ const endpointGenerator = findRestEndpointGenerator(sourceFolder().subitem([
4176
4178
  'shared-kernel'
4177
4179
  ]));
4178
4180
  const handler = withWiring ? await promptEndpointHandler(boundedContextFolder) : void 0;
@@ -4225,9 +4227,9 @@ export const wire${endpointClassName} = wireClass(
4225
4227
  'presentation',
4226
4228
  'rest'
4227
4229
  ]).file('index.ts').addLineIfMissing(`export * from './${group}'`);
4228
- sharedRestFolder(boundedContextFolder).file('wires.ts').addLineIfMissing(`export * from '../../bounded-contexts/${context}/wiring/presentation/rest/${group}'`);
4229
- const restHandlersFile = sharedRestFolder(boundedContextFolder).file('index.ts');
4230
- 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', `
4231
4233
  import * as wires from './wires'
4232
4234
 
4233
4235
  const restWires = Object.values(wires)
@@ -4488,7 +4490,10 @@ export abstract class ${naming.ClassName}Query {
4488
4490
  'queries'
4489
4491
  ]).createFile(`wire-${naming.fileName}-query.ts`, `
4490
4492
  import { wireClass } from '@domain-first/wire'
4491
- import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
4493
+ ${envBranchedWireImport(boundedContextFolder.subitem([
4494
+ 'wiring',
4495
+ 'queries'
4496
+ ]).path)}
4492
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')}
4493
4498
 
4494
4499
  ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Query, [])`).join('\n\n')}