@domain-first/project-structure 3.2.2 → 3.3.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/README.md CHANGED
@@ -138,10 +138,11 @@ Only the dependencies that respect the layers are offered: a use case can't take
138
138
  Choose **Domain → Errors** to add an error to the context namespace, create a nested namespace, or add an error to it.
139
139
 
140
140
  ```ts
141
- export const OutOfStockSalesError =
142
- SalesErrors.define("out-of-stock");
141
+ export class OutOfStock extends SalesErrors.define('out-of-stock') {}
143
142
  ```
144
143
 
144
+ Names don't repeat the context: an error of the `payment` namespace in `sales` is `PaymentDeclined`. In the Shared Layer they end with `SharedError`: `TimeoutSharedError`.
145
+
145
146
  ### How to share code between contexts
146
147
 
147
148
  Bounded contexts don't import each other. Put cross-context errors, entities, value objects, ports and services into the **Shared Layer** (`src/shared`). Its modules are offered as dependencies in every context.
package/dist/index.cjs CHANGED
@@ -276,6 +276,113 @@ const missingDomainFirstPackages = ()=>{
276
276
  `npm i ${missing.join(' ')}`
277
277
  ] : [];
278
278
  };
279
+ const external_node_module_namespaceObject = require("node:module");
280
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
281
+ const resolveExtends = (fromFile, target)=>{
282
+ if (target.startsWith('.') || external_node_path_default().isAbsolute(target)) {
283
+ const resolved = external_node_path_default().resolve(external_node_path_default().dirname(fromFile), target);
284
+ return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
285
+ }
286
+ const require1 = (0, external_node_module_namespaceObject.createRequire)(fromFile);
287
+ for (const candidate of [
288
+ target,
289
+ `${target}/tsconfig.json`
290
+ ])try {
291
+ return require1.resolve(candidate);
292
+ } catch {}
293
+ };
294
+ const compilerOption = (configFile, name, seen = new Set())=>{
295
+ if (seen.has(configFile) || !external_node_fs_default().existsSync(configFile)) return null;
296
+ seen.add(configFile);
297
+ let config;
298
+ try {
299
+ config = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(configFile, 'utf8')));
300
+ } catch {
301
+ return null;
302
+ }
303
+ if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
304
+ const parents = [
305
+ config.extends ?? []
306
+ ].flat().reverse();
307
+ for (const parent of parents){
308
+ const parentFile = resolveExtends(configFile, parent);
309
+ const value = parentFile ? compilerOption(parentFile, name, seen) : null;
310
+ if (void 0 !== value) return value;
311
+ }
312
+ };
313
+ class UnknownFormatNaming {
314
+ rawSource;
315
+ camelCase;
316
+ PascalCase;
317
+ constructor(rawSource){
318
+ this.rawSource = rawSource;
319
+ const source = rawSource.trim();
320
+ if (!source.includes('-')) {
321
+ this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
322
+ this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
323
+ }
324
+ const words = source.split('-').filter((word)=>!!word);
325
+ this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
326
+ this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
327
+ }
328
+ get fileName() {
329
+ return this.rawSource;
330
+ }
331
+ get variableName() {
332
+ return this.camelCase;
333
+ }
334
+ get ClassName() {
335
+ return this.PascalCase;
336
+ }
337
+ get withSpaces() {
338
+ return this.fileName.replaceAll('-', ' ');
339
+ }
340
+ }
341
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
342
+ class NestedName {
343
+ folders;
344
+ folderName;
345
+ fileName;
346
+ ClassName;
347
+ classNameSegments;
348
+ constructor(rawSource){
349
+ const segments = splitSegments(rawSource);
350
+ this.folders = segments.slice(0, -1);
351
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
352
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
353
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
354
+ this.ClassName = this.classNameSegments.join('');
355
+ }
356
+ static validate = (rawSource)=>{
357
+ const segments = splitSegments(rawSource);
358
+ if (!segments.length) return 'Name is required';
359
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
360
+ return true;
361
+ };
362
+ }
363
+ const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
364
+ ${[
365
+ ...imports,
366
+ "import { type FC } from 'react'"
367
+ ].join('\n')}
368
+
369
+ export type ${ClassName}PageProps = {}
370
+
371
+ export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
372
+ return ${body}
373
+ }
374
+ `.trim();
375
+ const scaffoldReactPage = async (presentationReactFolder)=>{
376
+ const name = await (0, prompts_namespaceObject.input)({
377
+ message: 'Provide name (folders split by "/"):',
378
+ validate: NestedName.validate
379
+ });
380
+ const { folders, ClassName, fileName } = new NestedName(name);
381
+ presentationReactFolder.subitem([
382
+ 'pages',
383
+ ...folders
384
+ ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
385
+ };
279
386
  const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
280
387
  const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
281
388
  const openapiExtractor = (rootFolder)=>`import path from 'node:path';
@@ -475,6 +582,18 @@ const extractorPackages = [
475
582
  'ts-morph',
476
583
  '@microsoft/tsdoc'
477
584
  ];
585
+ const swaggerPagePath = (rootFolder)=>external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
586
+ const swaggerPage = (rootFolder, outputPath)=>{
587
+ const specImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(swaggerPagePath(rootFolder)), outputPath);
588
+ return reactPageContent('Swagger', {
589
+ imports: [
590
+ "import 'swagger-ui-react/swagger-ui.css'",
591
+ "import SwaggerUI from 'swagger-ui-react'",
592
+ `import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
593
+ ],
594
+ body: '<SwaggerUI displayOperationId spec={spec} />'
595
+ });
596
+ };
478
597
  const openapiScripts = {
479
598
  openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
480
599
  };
@@ -538,6 +657,10 @@ const addOpenapi = async ()=>{
538
657
  message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
539
658
  default: true
540
659
  });
660
+ const withSwaggerPage = ConfigFile.Instance.data.useReact && await (0, prompts_namespaceObject.confirm)({
661
+ message: 'Add a Swagger UI page?',
662
+ default: true
663
+ });
541
664
  const selected = await addPackageScripts(manifestFile, openapiScripts);
542
665
  if (withExtractor) {
543
666
  const extractorFile = new File(external_node_path_default().join(root, openapiExtractorPath));
@@ -547,6 +670,12 @@ const addOpenapi = async ()=>{
547
670
  const generatorFile = new File(external_node_path_default().join(root, openapiScriptPath));
548
671
  const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
549
672
  if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
673
+ if (withSwaggerPage) {
674
+ const pageFile = new File(external_node_path_default().join(root, swaggerPagePath(rootFolder)));
675
+ const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
676
+ if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
677
+ }
678
+ const resolveJsonModule = withSwaggerPage ? compilerOption(external_node_path_default().join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
550
679
  const hasRestHandlers = new File(external_node_path_default().join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
551
680
  const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
552
681
  return [
@@ -559,9 +688,21 @@ const addOpenapi = async ()=>{
559
688
  ...missingExtractorPackages.length ? [
560
689
  `npm install --save-dev ${missingExtractorPackages.join(' ')}`
561
690
  ] : [],
691
+ ...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
692
+ 'npm install swagger-ui-react'
693
+ ] : [],
694
+ ...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
695
+ 'npm install --save-dev @types/swagger-ui-react'
696
+ ] : [],
697
+ ...true === resolveJsonModule || null === resolveJsonModule ? [] : [
698
+ 'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
699
+ ],
562
700
  ...describeScripts(selected, {
563
701
  openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
564
702
  }),
703
+ ...withSwaggerPage ? [
704
+ `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
705
+ ] : [],
565
706
  ...hasRestHandlers ? [] : [
566
707
  `restHandlers appear in ${external_node_path_default().posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
567
708
  ]
@@ -1186,34 +1327,6 @@ const addIntegration = async ()=>{
1186
1327
  const nextSteps = await integration.run();
1187
1328
  if (await savePendingChanges()) printNextSteps(nextSteps);
1188
1329
  };
1189
- class UnknownFormatNaming {
1190
- rawSource;
1191
- camelCase;
1192
- PascalCase;
1193
- constructor(rawSource){
1194
- this.rawSource = rawSource;
1195
- const source = rawSource.trim();
1196
- if (!source.includes('-')) {
1197
- this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
1198
- this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
1199
- }
1200
- const words = source.split('-').filter((word)=>!!word);
1201
- this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1202
- this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1203
- }
1204
- get fileName() {
1205
- return this.rawSource;
1206
- }
1207
- get variableName() {
1208
- return this.camelCase;
1209
- }
1210
- get ClassName() {
1211
- return this.PascalCase;
1212
- }
1213
- get withSpaces() {
1214
- return this.fileName.replaceAll('-', ' ');
1215
- }
1216
- }
1217
1330
  const wiring_layers = [
1218
1331
  'domain',
1219
1332
  'application',
@@ -2056,28 +2169,6 @@ export const SharedErrors = errorNamespace('shared')
2056
2169
  }
2057
2170
  return nextSteps;
2058
2171
  };
2059
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
2060
- class NestedName {
2061
- folders;
2062
- folderName;
2063
- fileName;
2064
- ClassName;
2065
- classNameSegments;
2066
- constructor(rawSource){
2067
- const segments = splitSegments(rawSource);
2068
- this.folders = segments.slice(0, -1);
2069
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
2070
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
2071
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
2072
- this.ClassName = this.classNameSegments.join('');
2073
- }
2074
- static validate = (rawSource)=>{
2075
- const segments = splitSegments(rawSource);
2076
- if (!segments.length) return 'Name is required';
2077
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
2078
- return true;
2079
- };
2080
- }
2081
2172
  const ignoredFolders = new Set([
2082
2173
  'node_modules',
2083
2174
  '.git',
@@ -2153,7 +2244,6 @@ const validateMove = (reactFolder, module, rawName)=>{
2153
2244
  if (target.startsWith(`${module.path}${external_node_path_default().sep}`)) return 'A widget cannot be moved into itself';
2154
2245
  return true;
2155
2246
  };
2156
- const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
2157
2247
  const readAliases = (projectRoot)=>{
2158
2248
  const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
2159
2249
  if (!external_node_fs_default().existsSync(tsconfig)) return [];
@@ -2932,11 +3022,25 @@ export const wire${naming.ClassName}DomainService = wireClass(
2932
3022
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2933
3023
  }
2934
3024
  };
3025
+ const errorNames = (boundedContextFolder)=>{
3026
+ const isShared = boundedContextFolder.path === new Folder(new ProjectRoot().path).subitem([
3027
+ ConfigFile.Instance.data.rootFolder,
3028
+ 'shared'
3029
+ ]).path;
3030
+ return {
3031
+ namespace: (namespaceName)=>`${namespaceName}${isShared ? 'Shared' : ''}Errors`,
3032
+ error: (errorName)=>`${errorName}${isShared ? 'SharedError' : ''}`
3033
+ };
3034
+ };
3035
+ const exportedNamespace = (file, fallback)=>/export\s+const\s+(\w+)\s*=\s*errorNamespace\b/.exec(file.data)?.[1] ?? fallback;
3036
+ const errorClass = (className, namespace, code)=>`export class ${className} extends ${namespace}.define('${code}') {}`;
2935
3037
  const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
2936
3038
  const currentErrorFolder = boundedContextFolder.subitem([
2937
3039
  'domain',
2938
3040
  'errors'
2939
3041
  ]);
3042
+ const names = errorNames(boundedContextFolder);
3043
+ const contextNaming = new UnknownFormatNaming(boundedContextFolder.name);
2940
3044
  const currentErrorNamespaces = currentErrorFolder.content.fileNames.filter((x)=>'index' !== x);
2941
3045
  const variants = [
2942
3046
  'New error without namespace',
@@ -2952,7 +3056,8 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
2952
3056
  message: 'Error name:'
2953
3057
  });
2954
3058
  const naming = new UnknownFormatNaming(errorName);
2955
- currentErrorFolder.file('index.ts').addLineIfMissing(`export const ${naming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Error = ${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors.define('${naming.fileName}')`, '\n\n');
3059
+ const indexFile = currentErrorFolder.file('index.ts');
3060
+ indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), exportedNamespace(indexFile, `${contextNaming.ClassName}Errors`), naming.fileName), '\n\n');
2956
3061
  return;
2957
3062
  }
2958
3063
  if ('New namespace' === selectedVariant) {
@@ -2963,7 +3068,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
2963
3068
  if (!currentErrorFolder.file(`${fileName}.ts`).exists) currentErrorFolder.createFile(`${fileName}.ts`, `
2964
3069
  import { errorNamespace } from '@domain-first/errors'
2965
3070
 
2966
- export const ${ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
3071
+ export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
2967
3072
  `.trim());
2968
3073
  currentErrorFolder.file('index.ts').addLineIfMissing(`export * from './${fileName}'`, '\n\n');
2969
3074
  return;
@@ -2974,7 +3079,8 @@ export const ${ClassName}${new UnknownFormatNaming(boundedContextFolder.name).Cl
2974
3079
  message: 'Error name:'
2975
3080
  });
2976
3081
  const { ClassName, fileName } = new UnknownFormatNaming(errorName);
2977
- currentErrorFolder.file(`${namespace}.ts`).addLineIfMissing(`export const ${ClassName}${namespaceNaming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Error = ${namespaceNaming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors.define('${fileName}')`, '\n\n');
3082
+ const namespaceFile = currentErrorFolder.file(`${namespace}.ts`);
3083
+ namespaceFile.addLineIfMissing(errorClass(names.error(`${namespaceNaming.ClassName}${ClassName}`), exportedNamespace(namespaceFile, names.namespace(namespaceNaming.ClassName)), fileName), '\n\n');
2978
3084
  };
2979
3085
  const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
2980
3086
  const restPresentationFolder = boundedContextFolder.subitem([
@@ -3408,25 +3514,6 @@ export const wire${naming.ClassName}UseCase = wireClass(
3408
3514
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
3409
3515
  }
3410
3516
  };
3411
- const scaffoldReactPage = async (presentationReactFolder)=>{
3412
- const name = await (0, prompts_namespaceObject.input)({
3413
- message: 'Provide name (folders split by "/"):',
3414
- validate: NestedName.validate
3415
- });
3416
- const { folders, ClassName, fileName } = new NestedName(name);
3417
- presentationReactFolder.subitem([
3418
- 'pages',
3419
- ...folders
3420
- ]).createFile(`${fileName}-page.tsx`, `
3421
- import { type FC } from 'react'
3422
-
3423
- export type ${ClassName}PageProps = {}
3424
-
3425
- export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
3426
- return <></>
3427
- }
3428
- `.trim());
3429
- };
3430
3517
  const scaffoldReactSharedHook = async (presentationReactFolder)=>{
3431
3518
  const name = await (0, prompts_namespaceObject.input)({
3432
3519
  message: 'Name without "use" (e.g. debounce): '
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ import node_path from "node:path";
4
4
  import zod from "zod";
5
5
  import node_fs from "node:fs";
6
6
  import { styleText } from "node:util";
7
+ import { createRequire } from "node:module";
7
8
  const pendingFiles = new Map();
8
9
  const pendingFolders = new Set();
9
10
  const pendingMoves = new Map();
@@ -246,6 +247,112 @@ const missingDomainFirstPackages = ()=>{
246
247
  `npm i ${missing.join(' ')}`
247
248
  ] : [];
248
249
  };
250
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
251
+ const resolveExtends = (fromFile, target)=>{
252
+ if (target.startsWith('.') || node_path.isAbsolute(target)) {
253
+ const resolved = node_path.resolve(node_path.dirname(fromFile), target);
254
+ return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
255
+ }
256
+ const require = createRequire(fromFile);
257
+ for (const candidate of [
258
+ target,
259
+ `${target}/tsconfig.json`
260
+ ])try {
261
+ return require.resolve(candidate);
262
+ } catch {}
263
+ };
264
+ const compilerOption = (configFile, name, seen = new Set())=>{
265
+ if (seen.has(configFile) || !node_fs.existsSync(configFile)) return null;
266
+ seen.add(configFile);
267
+ let config;
268
+ try {
269
+ config = JSON.parse(stripJsonComments(node_fs.readFileSync(configFile, 'utf8')));
270
+ } catch {
271
+ return null;
272
+ }
273
+ if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
274
+ const parents = [
275
+ config.extends ?? []
276
+ ].flat().reverse();
277
+ for (const parent of parents){
278
+ const parentFile = resolveExtends(configFile, parent);
279
+ const value = parentFile ? compilerOption(parentFile, name, seen) : null;
280
+ if (void 0 !== value) return value;
281
+ }
282
+ };
283
+ class UnknownFormatNaming {
284
+ rawSource;
285
+ camelCase;
286
+ PascalCase;
287
+ constructor(rawSource){
288
+ this.rawSource = rawSource;
289
+ const source = rawSource.trim();
290
+ if (!source.includes('-')) {
291
+ this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
292
+ this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
293
+ }
294
+ const words = source.split('-').filter((word)=>!!word);
295
+ this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
296
+ this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
297
+ }
298
+ get fileName() {
299
+ return this.rawSource;
300
+ }
301
+ get variableName() {
302
+ return this.camelCase;
303
+ }
304
+ get ClassName() {
305
+ return this.PascalCase;
306
+ }
307
+ get withSpaces() {
308
+ return this.fileName.replaceAll('-', ' ');
309
+ }
310
+ }
311
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
312
+ class NestedName {
313
+ folders;
314
+ folderName;
315
+ fileName;
316
+ ClassName;
317
+ classNameSegments;
318
+ constructor(rawSource){
319
+ const segments = splitSegments(rawSource);
320
+ this.folders = segments.slice(0, -1);
321
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
322
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
323
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
324
+ this.ClassName = this.classNameSegments.join('');
325
+ }
326
+ static validate = (rawSource)=>{
327
+ const segments = splitSegments(rawSource);
328
+ if (!segments.length) return 'Name is required';
329
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
330
+ return true;
331
+ };
332
+ }
333
+ const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
334
+ ${[
335
+ ...imports,
336
+ "import { type FC } from 'react'"
337
+ ].join('\n')}
338
+
339
+ export type ${ClassName}PageProps = {}
340
+
341
+ export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
342
+ return ${body}
343
+ }
344
+ `.trim();
345
+ const scaffoldReactPage = async (presentationReactFolder)=>{
346
+ const name = await input({
347
+ message: 'Provide name (folders split by "/"):',
348
+ validate: NestedName.validate
349
+ });
350
+ const { folders, ClassName, fileName } = new NestedName(name);
351
+ presentationReactFolder.subitem([
352
+ 'pages',
353
+ ...folders
354
+ ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
355
+ };
249
356
  const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
250
357
  const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
251
358
  const openapiExtractor = (rootFolder)=>`import path from 'node:path';
@@ -445,6 +552,18 @@ const extractorPackages = [
445
552
  'ts-morph',
446
553
  '@microsoft/tsdoc'
447
554
  ];
555
+ const swaggerPagePath = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
556
+ const swaggerPage = (rootFolder, outputPath)=>{
557
+ const specImport = node_path.posix.relative(node_path.posix.dirname(swaggerPagePath(rootFolder)), outputPath);
558
+ return reactPageContent('Swagger', {
559
+ imports: [
560
+ "import 'swagger-ui-react/swagger-ui.css'",
561
+ "import SwaggerUI from 'swagger-ui-react'",
562
+ `import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
563
+ ],
564
+ body: '<SwaggerUI displayOperationId spec={spec} />'
565
+ });
566
+ };
448
567
  const openapiScripts = {
449
568
  openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
450
569
  };
@@ -508,6 +627,10 @@ const addOpenapi = async ()=>{
508
627
  message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
509
628
  default: true
510
629
  });
630
+ const withSwaggerPage = ConfigFile.Instance.data.useReact && await prompts_confirm({
631
+ message: 'Add a Swagger UI page?',
632
+ default: true
633
+ });
511
634
  const selected = await addPackageScripts(manifestFile, openapiScripts);
512
635
  if (withExtractor) {
513
636
  const extractorFile = new File(node_path.join(root, openapiExtractorPath));
@@ -517,6 +640,12 @@ const addOpenapi = async ()=>{
517
640
  const generatorFile = new File(node_path.join(root, openapiScriptPath));
518
641
  const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
519
642
  if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
643
+ if (withSwaggerPage) {
644
+ const pageFile = new File(node_path.join(root, swaggerPagePath(rootFolder)));
645
+ const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
646
+ if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
647
+ }
648
+ const resolveJsonModule = withSwaggerPage ? compilerOption(node_path.join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
520
649
  const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
521
650
  const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
522
651
  return [
@@ -529,9 +658,21 @@ const addOpenapi = async ()=>{
529
658
  ...missingExtractorPackages.length ? [
530
659
  `npm install --save-dev ${missingExtractorPackages.join(' ')}`
531
660
  ] : [],
661
+ ...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
662
+ 'npm install swagger-ui-react'
663
+ ] : [],
664
+ ...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
665
+ 'npm install --save-dev @types/swagger-ui-react'
666
+ ] : [],
667
+ ...true === resolveJsonModule || null === resolveJsonModule ? [] : [
668
+ 'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
669
+ ],
532
670
  ...describeScripts(selected, {
533
671
  openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
534
672
  }),
673
+ ...withSwaggerPage ? [
674
+ `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
675
+ ] : [],
535
676
  ...hasRestHandlers ? [] : [
536
677
  `restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
537
678
  ]
@@ -1156,34 +1297,6 @@ const addIntegration = async ()=>{
1156
1297
  const nextSteps = await integration.run();
1157
1298
  if (await savePendingChanges()) printNextSteps(nextSteps);
1158
1299
  };
1159
- class UnknownFormatNaming {
1160
- rawSource;
1161
- camelCase;
1162
- PascalCase;
1163
- constructor(rawSource){
1164
- this.rawSource = rawSource;
1165
- const source = rawSource.trim();
1166
- if (!source.includes('-')) {
1167
- this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
1168
- this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
1169
- }
1170
- const words = source.split('-').filter((word)=>!!word);
1171
- this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1172
- this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1173
- }
1174
- get fileName() {
1175
- return this.rawSource;
1176
- }
1177
- get variableName() {
1178
- return this.camelCase;
1179
- }
1180
- get ClassName() {
1181
- return this.PascalCase;
1182
- }
1183
- get withSpaces() {
1184
- return this.fileName.replaceAll('-', ' ');
1185
- }
1186
- }
1187
1300
  const wiring_layers = [
1188
1301
  'domain',
1189
1302
  'application',
@@ -2026,28 +2139,6 @@ export const SharedErrors = errorNamespace('shared')
2026
2139
  }
2027
2140
  return nextSteps;
2028
2141
  };
2029
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
2030
- class NestedName {
2031
- folders;
2032
- folderName;
2033
- fileName;
2034
- ClassName;
2035
- classNameSegments;
2036
- constructor(rawSource){
2037
- const segments = splitSegments(rawSource);
2038
- this.folders = segments.slice(0, -1);
2039
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
2040
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
2041
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
2042
- this.ClassName = this.classNameSegments.join('');
2043
- }
2044
- static validate = (rawSource)=>{
2045
- const segments = splitSegments(rawSource);
2046
- if (!segments.length) return 'Name is required';
2047
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
2048
- return true;
2049
- };
2050
- }
2051
2142
  const ignoredFolders = new Set([
2052
2143
  'node_modules',
2053
2144
  '.git',
@@ -2123,7 +2214,6 @@ const validateMove = (reactFolder, module, rawName)=>{
2123
2214
  if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
2124
2215
  return true;
2125
2216
  };
2126
- const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
2127
2217
  const readAliases = (projectRoot)=>{
2128
2218
  const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
2129
2219
  if (!node_fs.existsSync(tsconfig)) return [];
@@ -2902,11 +2992,25 @@ export const wire${naming.ClassName}DomainService = wireClass(
2902
2992
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2903
2993
  }
2904
2994
  };
2995
+ const errorNames = (boundedContextFolder)=>{
2996
+ const isShared = boundedContextFolder.path === new Folder(new ProjectRoot().path).subitem([
2997
+ ConfigFile.Instance.data.rootFolder,
2998
+ 'shared'
2999
+ ]).path;
3000
+ return {
3001
+ namespace: (namespaceName)=>`${namespaceName}${isShared ? 'Shared' : ''}Errors`,
3002
+ error: (errorName)=>`${errorName}${isShared ? 'SharedError' : ''}`
3003
+ };
3004
+ };
3005
+ const exportedNamespace = (file, fallback)=>/export\s+const\s+(\w+)\s*=\s*errorNamespace\b/.exec(file.data)?.[1] ?? fallback;
3006
+ const errorClass = (className, namespace, code)=>`export class ${className} extends ${namespace}.define('${code}') {}`;
2905
3007
  const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
2906
3008
  const currentErrorFolder = boundedContextFolder.subitem([
2907
3009
  'domain',
2908
3010
  'errors'
2909
3011
  ]);
3012
+ const names = errorNames(boundedContextFolder);
3013
+ const contextNaming = new UnknownFormatNaming(boundedContextFolder.name);
2910
3014
  const currentErrorNamespaces = currentErrorFolder.content.fileNames.filter((x)=>'index' !== x);
2911
3015
  const variants = [
2912
3016
  'New error without namespace',
@@ -2922,7 +3026,8 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
2922
3026
  message: 'Error name:'
2923
3027
  });
2924
3028
  const naming = new UnknownFormatNaming(errorName);
2925
- currentErrorFolder.file('index.ts').addLineIfMissing(`export const ${naming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Error = ${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors.define('${naming.fileName}')`, '\n\n');
3029
+ const indexFile = currentErrorFolder.file('index.ts');
3030
+ indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), exportedNamespace(indexFile, `${contextNaming.ClassName}Errors`), naming.fileName), '\n\n');
2926
3031
  return;
2927
3032
  }
2928
3033
  if ('New namespace' === selectedVariant) {
@@ -2933,7 +3038,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
2933
3038
  if (!currentErrorFolder.file(`${fileName}.ts`).exists) currentErrorFolder.createFile(`${fileName}.ts`, `
2934
3039
  import { errorNamespace } from '@domain-first/errors'
2935
3040
 
2936
- export const ${ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
3041
+ export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
2937
3042
  `.trim());
2938
3043
  currentErrorFolder.file('index.ts').addLineIfMissing(`export * from './${fileName}'`, '\n\n');
2939
3044
  return;
@@ -2944,7 +3049,8 @@ export const ${ClassName}${new UnknownFormatNaming(boundedContextFolder.name).Cl
2944
3049
  message: 'Error name:'
2945
3050
  });
2946
3051
  const { ClassName, fileName } = new UnknownFormatNaming(errorName);
2947
- currentErrorFolder.file(`${namespace}.ts`).addLineIfMissing(`export const ${ClassName}${namespaceNaming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Error = ${namespaceNaming.ClassName}${new UnknownFormatNaming(boundedContextFolder.name).ClassName}Errors.define('${fileName}')`, '\n\n');
3052
+ const namespaceFile = currentErrorFolder.file(`${namespace}.ts`);
3053
+ namespaceFile.addLineIfMissing(errorClass(names.error(`${namespaceNaming.ClassName}${ClassName}`), exportedNamespace(namespaceFile, names.namespace(namespaceNaming.ClassName)), fileName), '\n\n');
2948
3054
  };
2949
3055
  const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
2950
3056
  const restPresentationFolder = boundedContextFolder.subitem([
@@ -3378,25 +3484,6 @@ export const wire${naming.ClassName}UseCase = wireClass(
3378
3484
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
3379
3485
  }
3380
3486
  };
3381
- const scaffoldReactPage = async (presentationReactFolder)=>{
3382
- const name = await input({
3383
- message: 'Provide name (folders split by "/"):',
3384
- validate: NestedName.validate
3385
- });
3386
- const { folders, ClassName, fileName } = new NestedName(name);
3387
- presentationReactFolder.subitem([
3388
- 'pages',
3389
- ...folders
3390
- ]).createFile(`${fileName}-page.tsx`, `
3391
- import { type FC } from 'react'
3392
-
3393
- export type ${ClassName}PageProps = {}
3394
-
3395
- export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
3396
- return <></>
3397
- }
3398
- `.trim());
3399
- };
3400
3487
  const scaffoldReactSharedHook = async (presentationReactFolder)=>{
3401
3488
  const name = await input({
3402
3489
  message: 'Name without "use" (e.g. debounce): '
@@ -1,5 +1,10 @@
1
1
  export declare const openapiScriptPath = "scripts/generate-openapi.ts";
2
2
  export declare const defaultOpenapiPath: (withNext: boolean) => "public/openapi.json" | "openapi.json";
3
+ export declare const swaggerPagePath: (rootFolder: string) => string;
4
+ /**
5
+ * A React page rendering the OpenAPI document with Swagger UI.
6
+ */
7
+ export declare const swaggerPage: (rootFolder: string, outputPath: string) => string;
3
8
  export declare const openapiScripts: {
4
9
  openapi: string;
5
10
  };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * tsconfig is JSON with comments and trailing commas.
3
+ */
4
+ export declare const stripJsonComments: (source: string) => string;
5
+ /**
6
+ * The compiler option as the config sets it, through its `extends`
7
+ * chain: the nearest config that sets it wins. Undefined when no config
8
+ * sets it; null when a config can't be read, so the value is unknown.
9
+ */
10
+ export declare const compilerOption: (configFile: string, name: string, seen?: Set<string>) => unknown;
@@ -0,0 +1 @@
1
+ export {};
@@ -1,2 +1,2 @@
1
- import type { Folder } from '../file-system';
1
+ import { Folder } from '../file-system';
2
2
  export declare const scaffoldNewErrorUseCase: (boundedContextFolder: Folder) => Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
@@ -1,2 +1,10 @@
1
1
  import type { Folder } from '../file-system';
2
+ /**
3
+ * Content of `<file>-page.tsx`: imports go before React's, `body` is
4
+ * what the page returns.
5
+ */
6
+ export declare const reactPageContent: (ClassName: string, { imports, body }?: {
7
+ imports?: string[];
8
+ body?: string;
9
+ }) => string;
2
10
  export declare const scaffoldReactPage: (presentationReactFolder: Folder) => Promise<void>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@domain-first/project-structure",
3
3
  "description": "Build and manage your Domain-First project structure with CLI",
4
- "version": "3.2.2",
4
+ "version": "3.3.1",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -42,9 +42,10 @@ First prompt (select): `New error without namespace` | `New namespace` | `New er
42
42
  `… pick:Domain pick:Errors "pick:New error in namespace order" text:not-found`
43
43
  `… pick:Domain pick:Errors "pick:New error without" text:order-closed`
44
44
 
45
- - Without namespace: appends `export const NCtxError = CtxErrors.define('n')` to `<C>/domain/errors/index.ts`
46
- - New namespace: `<C>/domain/errors/ns.ts` (`NsCtxErrors = errorNamespace('ctx').subnamespace('ns')`) + `export * from './ns'` in `index.ts`
47
- - In namespace: appends `NNsCtxError = NsCtxErrors.define('n')` to `ns.ts`
45
+ - Without namespace: appends `export class N extends CtxErrors.define('n') {}` to `<C>/domain/errors/index.ts`
46
+ - New namespace: `<C>/domain/errors/ns.ts` (`NsErrors = errorNamespace('ctx').subnamespace('ns')`) + `export * from './ns'` in `index.ts`
47
+ - In namespace: appends `export class NsN extends NsErrors.define('n') {}` to `ns.ts` (namespace first), extending the namespace the file exports
48
+ - Shared Layer: errors end with `SharedError`, namespaces with `SharedErrors`: `NSharedError`, `NsSharedErrors`, `NsNSharedError`
48
49
 
49
50
  Re-running is safe: an existing namespace file is kept, and a line already in the file isn't added again.
50
51