@domain-first/project-structure 2.10.4 → 2.12.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/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import node_path from "node:path";
3
- import { checkbox as prompts_checkbox, confirm as prompts_confirm, input, select as prompts_select } from "@inquirer/prompts";
3
+ import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, select as prompts_select } from "@inquirer/prompts";
4
4
  import zod from "zod";
5
5
  import node_fs from "node:fs";
6
6
  const pendingFiles = new Map();
@@ -83,6 +83,12 @@ class File extends FileSystemItem {
83
83
  replacesFile: true
84
84
  });
85
85
  }
86
+ update = (content)=>{
87
+ pendingFiles.set(this.path, {
88
+ content,
89
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
90
+ });
91
+ };
86
92
  addLine = (newLine, separator = '\n')=>{
87
93
  const content = this.exists ? this.data : '';
88
94
  pendingFiles.set(this.path, {
@@ -247,6 +253,439 @@ class UnknownFormatNaming {
247
253
  return this.fileName.replaceAll('-', ' ');
248
254
  }
249
255
  }
256
+ const wiring_layers = [
257
+ 'domain',
258
+ 'application',
259
+ 'infrastructure',
260
+ 'presentation'
261
+ ];
262
+ const visibleLayers = {
263
+ domain: [
264
+ 'domain'
265
+ ],
266
+ application: [
267
+ 'domain',
268
+ 'application'
269
+ ],
270
+ infrastructure: [
271
+ 'domain',
272
+ 'infrastructure'
273
+ ],
274
+ presentation: [
275
+ 'application',
276
+ 'presentation'
277
+ ]
278
+ };
279
+ const branchedTypeFiles = {
280
+ repositories: (fileBase)=>[
281
+ 'domain',
282
+ 'aggregates',
283
+ fileBase.replace(/-repository$/, ''),
284
+ `${fileBase}.ts`
285
+ ],
286
+ commands: (fileBase)=>[
287
+ 'application',
288
+ 'commands',
289
+ 'execution',
290
+ `${fileBase}.ts`
291
+ ],
292
+ queries: (fileBase)=>[
293
+ 'application',
294
+ 'queries',
295
+ 'execution',
296
+ `${fileBase}.ts`
297
+ ],
298
+ 'application-ports': (fileBase)=>[
299
+ 'application',
300
+ 'ports',
301
+ `${fileBase}.ts`
302
+ ]
303
+ };
304
+ const layerOf = (file, contextPath)=>{
305
+ const [firstSegment] = node_path.relative(contextPath, file).split(node_path.sep);
306
+ return wiring_layers.find((layer)=>layer === firstSegment);
307
+ };
308
+ const namedImports = (source, fromFile)=>{
309
+ const result = new Map();
310
+ for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
311
+ const cleanName = name.replace(/^\s*type\s+/, '').trim();
312
+ if (cleanName) result.set(cleanName, `${node_path.resolve(node_path.dirname(fromFile), importPath)}.ts`);
313
+ }
314
+ return result;
315
+ };
316
+ const isEndpointWire = (wiringRelativePath)=>wiringRelativePath.startsWith([
317
+ 'presentation',
318
+ 'rest'
319
+ ].join(node_path.sep));
320
+ const wireClassDefinitions = (source)=>[
321
+ ...codeOnly(source).matchAll(/(?:export\s+)?const\s+(\w+)\s*=\s*(?:\w+\(\s*)*wireClass\(\s*(\w+)\s*,/g)
322
+ ].map(([, wireName, className])=>({
323
+ wireName,
324
+ className
325
+ }));
326
+ const wiredClassNames = (source, wireName, initializerStart, branched)=>{
327
+ const definitions = wireClassDefinitions(source);
328
+ if (!branched) return definitions.filter((x)=>x.wireName === wireName).map((x)=>x.className);
329
+ const openIndex = source.indexOf('(', initializerStart);
330
+ const branches = codeOnly(source).slice(openIndex, closingIndex(source, openIndex));
331
+ const referenced = new Set(branches.match(/\w+/g));
332
+ return definitions.filter((x)=>referenced.has(x.wireName)).map((x)=>x.className);
333
+ };
334
+ const readWiredModule = (wireFile, contextPath)=>{
335
+ const wiringRelativePath = node_path.relative(node_path.join(contextPath, 'wiring'), wireFile);
336
+ if (isEndpointWire(wiringRelativePath)) return;
337
+ const source = new File(wireFile).data;
338
+ const wireName = `wire${new UnknownFormatNaming(node_path.basename(wireFile, '.ts').replace(/^wire-/, '')).ClassName}`;
339
+ const exportMatch = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*`).exec(source);
340
+ if (!exportMatch) return;
341
+ const branched = source.slice(exportMatch.index + exportMatch[0].length).startsWith('envBranchedWire(');
342
+ const imports = namedImports(source, wireFile);
343
+ const implementations = wiredClassNames(source, wireName, exportMatch.index + exportMatch[0].length, branched).flatMap((className)=>{
344
+ const file = imports.get(className);
345
+ return file ? [
346
+ {
347
+ className,
348
+ file
349
+ }
350
+ ] : [];
351
+ });
352
+ if (!implementations.length) return;
353
+ const typeName = wireName.slice(4);
354
+ const [wiringFolder] = wiringRelativePath.split(node_path.sep);
355
+ const typeFileSegments = branchedTypeFiles[wiringFolder]?.(node_path.basename(wireFile, '.ts').replace(/^wire-/, ''));
356
+ const typeFile = branched ? typeFileSegments && node_path.join(contextPath, ...typeFileSegments) : implementations[0].file;
357
+ const layer = typeFile && layerOf(typeFile, contextPath);
358
+ const implementationsLayer = layerOf(implementations[0].file, contextPath);
359
+ if (!typeFile || !layer || !implementationsLayer) return;
360
+ return {
361
+ wireName,
362
+ typeName,
363
+ wireFile,
364
+ typeFile,
365
+ layer,
366
+ implementations,
367
+ branched,
368
+ implementationsLayer,
369
+ kind: wiringFolder
370
+ };
371
+ };
372
+ const findWiredModules = (contextPath)=>{
373
+ const result = [];
374
+ const walk = (folderPath)=>{
375
+ if (!node_fs.existsSync(folderPath)) return;
376
+ for (const entry of node_fs.readdirSync(folderPath, {
377
+ withFileTypes: true
378
+ })){
379
+ const entryPath = node_path.join(folderPath, entry.name);
380
+ if (entry.isDirectory()) walk(entryPath);
381
+ else if (/^wire-.*(?<!\.spec)\.ts$/.test(entry.name)) {
382
+ const wiredModule = readWiredModule(entryPath, contextPath);
383
+ if (wiredModule) result.push(wiredModule);
384
+ }
385
+ }
386
+ };
387
+ walk(node_path.join(contextPath, 'wiring'));
388
+ return result.sort((a, b)=>a.typeName.localeCompare(b.typeName));
389
+ };
390
+ const isCommandOrQuery = (module)=>'commands' === module.kind || 'queries' === module.kind;
391
+ const isExecution = (module)=>isCommandOrQuery(module) && 'execution' === node_path.basename(node_path.dirname(module.typeFile));
392
+ const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate);
393
+ const kindRules = {
394
+ 'application-services': (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind,
395
+ 'use-cases': (candidate)=>'use-cases' !== candidate.kind,
396
+ repositories: (candidate)=>'repositories' !== candidate.kind,
397
+ commands: commandOrQueryRule,
398
+ queries: commandOrQueryRule
399
+ };
400
+ const wiring_implementationType = (consumer, implementation)=>consumer.branched ? node_path.basename(node_path.dirname(implementation.file)) : void 0;
401
+ const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${node_path.basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
402
+ const isSuggestedEndpointGenerator = (candidate)=>candidate.typeName.toLowerCase().includes('endpoint');
403
+ const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
404
+ const availableDependencies = (consumer, implementation, candidates)=>{
405
+ const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
406
+ return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate) && !wired.includes(candidate.wireName));
407
+ };
408
+ const relativeImport = (fromFile, toFile)=>{
409
+ const relativePath = node_path.relative(node_path.dirname(fromFile), toFile).replace(/\.ts$/, '').split(node_path.sep).join('/');
410
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
411
+ };
412
+ const codeOnly = (source)=>{
413
+ let result = '';
414
+ let index = 0;
415
+ const blank = (text)=>text.replace(/[^\n]/g, ' ');
416
+ while(index < source.length){
417
+ const pair = source.slice(index, index + 2);
418
+ const char = source[index];
419
+ let end = index + 1;
420
+ if ('//' === pair) {
421
+ const lineEnd = source.indexOf('\n', index);
422
+ end = -1 === lineEnd ? source.length : lineEnd;
423
+ result += blank(source.slice(index, end));
424
+ } else if ('/*' === pair) {
425
+ const commentEnd = source.indexOf('*/', index + 2);
426
+ end = -1 === commentEnd ? source.length : commentEnd + 2;
427
+ result += blank(source.slice(index, end));
428
+ } else if ('=>' === pair) {
429
+ end = index + 2;
430
+ result += ' ';
431
+ } else if ("'" === char || '"' === char || '`' === char) {
432
+ while(end < source.length && source[end] !== char)end += '\\' === source[end] ? 2 : 1;
433
+ end = Math.min(end + 1, source.length);
434
+ result += char + blank(source.slice(index + 1, end - 1));
435
+ result += end - 1 > index ? source[end - 1] : '';
436
+ } else result += char;
437
+ index = end;
438
+ }
439
+ return result;
440
+ };
441
+ const addImport = (source, importLine)=>{
442
+ if (source.split('\n').some((line)=>line.trim() === importLine)) return source;
443
+ const lastImport = [
444
+ ...codeOnly(source).matchAll(/^import\s(?:[^'"]*?from\s*)?['"][^'"]*['"]/gm)
445
+ ].at(-1);
446
+ if (!lastImport) return `${importLine}\n\n${source}`;
447
+ const importEnd = lastImport.index + lastImport[0].length;
448
+ const lineEnd = source.indexOf('\n', importEnd);
449
+ const insertAt = -1 === lineEnd ? source.length : lineEnd;
450
+ return `${source.slice(0, insertAt)}\n${importLine}${source.slice(insertAt)}`;
451
+ };
452
+ const brackets = {
453
+ '(': ')',
454
+ '[': ']',
455
+ '{': '}',
456
+ '<': '>'
457
+ };
458
+ const closingIndex = (source, openIndex)=>{
459
+ const code = codeOnly(source);
460
+ let depth = 0;
461
+ for(let index = openIndex; index < code.length; index++){
462
+ const char = code[index];
463
+ if (char === code[openIndex]) depth++;
464
+ else if (char === brackets[code[openIndex]]) {
465
+ depth--;
466
+ if (0 === depth) return index;
467
+ }
468
+ }
469
+ return -1;
470
+ };
471
+ const splitTopLevel = (content)=>{
472
+ const code = codeOnly(content);
473
+ const items = [];
474
+ let depth = 0;
475
+ let itemStart = 0;
476
+ for(let index = 0; index <= code.length; index++){
477
+ const char = code[index];
478
+ if (void 0 !== char && char in brackets) depth++;
479
+ else if (Object.values(brackets).includes(char)) depth--;
480
+ if (index === code.length || ',' === char && 0 === depth) {
481
+ const item = content.slice(itemStart, index);
482
+ const itemCode = code.slice(itemStart, index);
483
+ const first = itemCode.search(/\S/);
484
+ const last = itemCode.search(/\S\s*$/);
485
+ if (-1 !== first) items.push(item.slice(first, last + 1));
486
+ itemStart = index + 1;
487
+ }
488
+ }
489
+ return items;
490
+ };
491
+ const appendItems = (content, items)=>{
492
+ const code = codeOnly(content);
493
+ const lastCode = code.search(/\S\s*$/);
494
+ if (-1 === lastCode) return items.join(', ');
495
+ const trailingComma = ',' === code[lastCode];
496
+ if (!content.includes('\n')) {
497
+ const added = trailingComma ? ` ${items.join(', ')},` : `, ${items.join(', ')}`;
498
+ return content.slice(0, lastCode + 1) + added + content.slice(lastCode + 1);
499
+ }
500
+ const indent = content.match(/\n([ \t]*)\S/)?.[1] ?? '';
501
+ const withComma = trailingComma ? content : `${content.slice(0, lastCode + 1)},${content.slice(lastCode + 1)}`;
502
+ const lineEndIndex = withComma.indexOf('\n', lastCode + 1);
503
+ const lineEnd = -1 === lineEndIndex ? withComma.length : lineEndIndex;
504
+ const added = trailingComma ? items.map((x)=>`\n${indent}${x},`).join('') : items.map((x)=>`\n${indent}${x}`).join(',');
505
+ return withComma.slice(0, lineEnd) + added + withComma.slice(lineEnd);
506
+ };
507
+ const addConstructorParameters = (source, className, parameters)=>{
508
+ const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
509
+ if (!classMatch) throw new Error(`Class ${className} not found`);
510
+ const bodyStart = classMatch.index + classMatch[0].length;
511
+ const bodyEnd = closingIndex(source, bodyStart - 1);
512
+ const body = source.slice(bodyStart, bodyEnd);
513
+ const constructorIndex = codeOnly(body).search(/\bconstructor\s*\(/);
514
+ const renderParameters = (allParameters, indent)=>1 === allParameters.length ? allParameters[0] : `\n${allParameters.map((x)=>`${indent} ${x}`).join(',\n')}\n${indent}`;
515
+ if (-1 === constructorIndex) {
516
+ const constructorBody = /\bextends\b/.test(classMatch[0]) ? '{\n super()\n }' : '{}';
517
+ const constructorLine = ` constructor(${renderParameters(parameters, ' ')}) ${constructorBody}`;
518
+ const newBody = body.trim() ? `\n${constructorLine}\n${body.replace(/^\s*\n/, '\n')}` : `\n${constructorLine}\n`;
519
+ return source.slice(0, bodyStart) + newBody + source.slice(bodyEnd);
520
+ }
521
+ const openIndex = bodyStart + body.indexOf('(', constructorIndex);
522
+ const closeIndex = closingIndex(source, openIndex);
523
+ const content = source.slice(openIndex + 1, closeIndex);
524
+ if (content.includes('\n')) return source.slice(0, openIndex + 1) + appendItems(content, parameters) + source.slice(closeIndex);
525
+ const lineStart = source.lastIndexOf('\n', openIndex) + 1;
526
+ const indent = source.slice(lineStart).match(/^\s*/)?.[0] ?? '';
527
+ return source.slice(0, openIndex + 1) + renderParameters([
528
+ ...splitTopLevel(content),
529
+ ...parameters
530
+ ], indent) + source.slice(closeIndex);
531
+ };
532
+ const wireListRange = (source, className)=>{
533
+ const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
534
+ if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
535
+ const openIndex = match.index + match[0].length - 1;
536
+ return {
537
+ openIndex,
538
+ closeIndex: closingIndex(source, openIndex)
539
+ };
540
+ };
541
+ const wiredDependencyNames = (source, className)=>{
542
+ const { openIndex, closeIndex } = wireListRange(source, className);
543
+ return splitTopLevel(source.slice(openIndex + 1, closeIndex));
544
+ };
545
+ const addWireDependencies = (source, className, wireNames)=>{
546
+ const { openIndex, closeIndex } = wireListRange(source, className);
547
+ return source.slice(0, openIndex + 1) + appendItems(source.slice(openIndex + 1, closeIndex), wireNames) + source.slice(closeIndex);
548
+ };
549
+ const parameterName = (typeName)=>typeName.substring(0, 1).toLowerCase() + typeName.substring(1);
550
+ const wireDependencies = (consumer, implementation, dependencies)=>{
551
+ const wireFile = new File(consumer.wireFile);
552
+ let wireSource = wireFile.data;
553
+ for (const dependency of dependencies)wireSource = addImport(wireSource, `import { ${dependency.wireName} } from '${relativeImport(consumer.wireFile, dependency.wireFile)}'`);
554
+ wireFile.update(addWireDependencies(wireSource, implementation.className, dependencies.map((x)=>x.wireName)));
555
+ const classFile = new File(implementation.file);
556
+ let classSource = classFile.data;
557
+ for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
558
+ classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
559
+ };
560
+ const kindTitles = {
561
+ repositories: 'Repositories',
562
+ 'domain-services': 'Domain services',
563
+ 'application-ports': 'Ports',
564
+ 'application-services': 'Application services',
565
+ queries: 'Queries',
566
+ commands: 'Commands',
567
+ 'use-cases': 'Use cases',
568
+ 'infrastructure-services': 'Infrastructure services',
569
+ 'presentation-services': 'Presentation services'
570
+ };
571
+ const groupedChoices = (items, suggested = [])=>{
572
+ const suggestedChoices = suggested.length ? [
573
+ new Separator('── Suggested'),
574
+ ...suggested.map((x)=>({
575
+ name: x.label,
576
+ value: x
577
+ }))
578
+ ] : [];
579
+ const kinds = [
580
+ ...new Set([
581
+ ...Object.keys(kindTitles),
582
+ ...items.map((x)=>x.module.kind)
583
+ ])
584
+ ];
585
+ return [
586
+ ...suggestedChoices,
587
+ ...kinds.flatMap((kind)=>{
588
+ const group = items.filter((x)=>x.module.kind === kind && !suggested.includes(x));
589
+ return group.length ? [
590
+ new Separator(`── ${kindTitles[kind] ?? kind}`),
591
+ ...group.map((x)=>({
592
+ name: x.label,
593
+ value: x
594
+ }))
595
+ ] : [];
596
+ })
597
+ ];
598
+ };
599
+ const groupedPageSize = 20;
600
+ const contextAndSharedModules = (boundedContextFolder)=>{
601
+ const sharedFolder = new Folder(new ProjectRoot().path).subitem([
602
+ ConfigFile.Instance.data.rootFolder,
603
+ 'shared'
604
+ ]);
605
+ const isShared = sharedFolder.path === boundedContextFolder.path;
606
+ return [
607
+ ...findWiredModules(boundedContextFolder.path).map((x)=>({
608
+ module: x,
609
+ label: x.typeName
610
+ })),
611
+ ...isShared ? [] : findWiredModules(sharedFolder.path).map((x)=>({
612
+ module: x,
613
+ label: `${x.typeName} (shared)`
614
+ }))
615
+ ];
616
+ };
617
+ const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations)=>{
618
+ const options = contextAndSharedModules(boundedContextFolder);
619
+ let asked = false;
620
+ for (const implementation of implementations){
621
+ const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
622
+ const candidates = options.filter((x)=>available.includes(x.module));
623
+ if (!candidates.length) continue;
624
+ asked = true;
625
+ const type = wiring_implementationType(consumer, implementation);
626
+ const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
627
+ const dependencies = await prompts_checkbox({
628
+ message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
629
+ choices: groupedChoices(candidates, suggested),
630
+ pageSize: groupedPageSize,
631
+ loop: false
632
+ });
633
+ if (dependencies.length) wireDependencies(consumer, implementation, dependencies.map((x)=>x.module));
634
+ }
635
+ return asked;
636
+ };
637
+ const wireNewModuleDependencies = async (boundedContextFolder, wireFile)=>{
638
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
639
+ if (consumer) await promptDependencies(boundedContextFolder, consumer);
640
+ };
641
+ const wireDependency = async (boundedContextFolder)=>{
642
+ const modules = findWiredModules(boundedContextFolder.path);
643
+ if (!modules.length) return void console.log('No wired modules here yet.');
644
+ const { module: consumer, implementation } = await prompts_select({
645
+ message: 'Module:',
646
+ choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
647
+ const type = wiring_implementationType(x, implementation);
648
+ return {
649
+ module: x,
650
+ label: type ? `${x.typeName} (${type})` : x.typeName,
651
+ implementation
652
+ };
653
+ }))),
654
+ pageSize: groupedPageSize,
655
+ loop: false
656
+ });
657
+ if (!await promptDependencies(boundedContextFolder, consumer, [
658
+ implementation
659
+ ])) console.log('No dependencies available for this module.');
660
+ };
661
+ const promptEndpointDependencies = async (boundedContextFolder)=>{
662
+ const options = contextAndSharedModules(boundedContextFolder);
663
+ const generators = options.filter((x)=>'presentation-services' === x.module.kind);
664
+ const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
665
+ 'queries',
666
+ 'commands',
667
+ 'use-cases'
668
+ ].includes(x.kind)).map((x)=>({
669
+ module: x,
670
+ label: x.typeName
671
+ }));
672
+ const endpointGenerator = generators.length ? (await prompts_select({
673
+ message: 'Endpoint generator:',
674
+ choices: groupedChoices(generators, generators.filter((x)=>isSuggestedEndpointGenerator(x.module))),
675
+ pageSize: groupedPageSize,
676
+ loop: false
677
+ })).module : void 0;
678
+ const handler = handlers.length ? (await prompts_select({
679
+ message: 'Handler:',
680
+ choices: groupedChoices(handlers),
681
+ pageSize: groupedPageSize,
682
+ loop: false
683
+ })).module : void 0;
684
+ return {
685
+ endpointGenerator,
686
+ handler
687
+ };
688
+ };
250
689
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
251
690
  const aggregateName = await input({
252
691
  message: 'Aggregate name:'
@@ -346,7 +785,7 @@ describe('${aggregateNaming.withSpaces} repository', () => {
346
785
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
347
786
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
348
787
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
349
- boundedContextFolder.subitem([
788
+ const wireFile = boundedContextFolder.subitem([
350
789
  'wiring',
351
790
  'repositories'
352
791
  ]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
@@ -362,6 +801,7 @@ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
362
801
  production: wire${implementationNaming.ClassName}Implementation
363
802
  })
364
803
  `.trim());
804
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
365
805
  }
366
806
  }
367
807
  };
@@ -438,18 +878,19 @@ describe('${naming.withSpaces}', () => {
438
878
  })
439
879
  `.trim());
440
880
  }
441
- if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
881
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
882
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
442
883
  import { wireClass } from '@domain-first/wire'
443
884
  import { envBranchedWire } from '../../../${'shared' === boundedContextFolder.name ? '' : '../'}shared/wiring/env-branched-wire'
444
885
  ${implementationTypes.map((x)=>({
445
- naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
446
- implementation: x
447
- })).map(({ naming: { ClassName, fileName }, implementation })=>`import { ${ClassName} } from '../../infrastructure/application-adapters/${implementation}/${fileName}'`).join('\n')}
886
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
887
+ implementation: x
888
+ })).map(({ naming: { ClassName, fileName }, implementation })=>`import { ${ClassName} } from '../../infrastructure/application-adapters/${implementation}/${fileName}'`).join('\n')}
448
889
 
449
890
  ${implementationTypes.map((x)=>({
450
- naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
451
- implementation: x
452
- })).map(({ naming: { ClassName }, implementation })=>`const wire${new UnknownFormatNaming(implementation).ClassName}Implementation = wireClass(${ClassName}, [])`).join('\n\n')}
891
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
892
+ implementation: x
893
+ })).map(({ naming: { ClassName }, implementation })=>`const wire${new UnknownFormatNaming(implementation).ClassName}Implementation = wireClass(${ClassName}, [])`).join('\n\n')}
453
894
 
454
895
  export const wire${naming.ClassName} = envBranchedWire({
455
896
  test: wire${new UnknownFormatNaming(`${implementationTypes.at(-1)}-implementation`).ClassName},
@@ -458,6 +899,8 @@ export const wire${naming.ClassName} = envBranchedWire({
458
899
  })
459
900
 
460
901
  `.trim());
902
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
903
+ }
461
904
  };
462
905
  const scaffoldNewApplicationService = async (boundedContextFolder)=>{
463
906
  const name = await input({
@@ -496,7 +939,8 @@ describe('${naming.withSpaces}', () => {
496
939
  })
497
940
  })
498
941
  `.trim());
499
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-application-service.ts`, `
942
+ if (withWiring) {
943
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-application-service.ts`, `
500
944
  import { wireClass } from '@domain-first/wire'
501
945
  import { ${naming.ClassName}ApplicationService } from '../../application/services/${naming.fileName}-application-service'
502
946
 
@@ -505,6 +949,8 @@ export const wire${naming.ClassName}ApplicationService = wireClass(
505
949
  []
506
950
  )
507
951
  `.trim());
952
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
953
+ }
508
954
  };
509
955
  const scaffoldNewBoundedContextUseCase = async ()=>{
510
956
  const name = await input({
@@ -645,7 +1091,7 @@ describe('${naming.withSpaces} command', () => {
645
1091
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
646
1092
  const implementationNaming = new UnknownFormatNaming(implementationType);
647
1093
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
648
- boundedContextFolder.subitem([
1094
+ const wireFile = boundedContextFolder.subitem([
649
1095
  'wiring',
650
1096
  'commands'
651
1097
  ]).createFile(`wire-${naming.fileName}-command.ts`, `
@@ -661,6 +1107,7 @@ export const wire${naming.ClassName}Command = envBranchedWire({
661
1107
  production: wire${implementationNaming.ClassName}Implementation
662
1108
  })
663
1109
  `.trim());
1110
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
664
1111
  }
665
1112
  return;
666
1113
  }
@@ -718,6 +1165,10 @@ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
718
1165
  })
719
1166
  })
720
1167
  `.trim());
1168
+ if (withWiring) await wireNewModuleDependencies(boundedContextFolder, boundedContextFolder.subitem([
1169
+ 'wiring',
1170
+ 'commands'
1171
+ ]).file(`wire-${naming.fileName}-command.ts`));
721
1172
  };
722
1173
  const noAggregate = 'No aggregate';
723
1174
  const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
@@ -806,10 +1257,11 @@ describe('${naming.withSpaces}', () => {
806
1257
  })
807
1258
  })
808
1259
  `.trim());
809
- if (withWiring) boundedContextFolder.subitem([
810
- 'wiring',
811
- 'domain-services'
812
- ]).createFile(`wire-${naming.fileName}-domain-service.ts`, `
1260
+ if (withWiring) {
1261
+ const wireFile = boundedContextFolder.subitem([
1262
+ 'wiring',
1263
+ 'domain-services'
1264
+ ]).createFile(`wire-${naming.fileName}-domain-service.ts`, `
813
1265
  import { wireClass } from '@domain-first/wire'
814
1266
  import { ${naming.ClassName}DomainService } from '../../domain/services/${naming.fileName}-domain-service'
815
1267
 
@@ -818,6 +1270,8 @@ export const wire${naming.ClassName}DomainService = wireClass(
818
1270
  []
819
1271
  )
820
1272
  `.trim());
1273
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1274
+ }
821
1275
  };
822
1276
  const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
823
1277
  const currentErrorFolder = boundedContextFolder.subitem([
@@ -912,33 +1366,40 @@ export const restHandlers = restWires.map(x => x().handle)
912
1366
  'put'
913
1367
  ]
914
1368
  });
915
- const path = (await input({
1369
+ const routeSegments = (await input({
916
1370
  message: 'Relative path (split by "/"):'
917
1371
  })).split('/').filter((x)=>!!x);
918
1372
  const controllerFolder = restPresentationFolder.subitem([
919
1373
  controller
920
1374
  ]);
921
- const endpointFolder = controllerFolder.subitem(path);
922
- const nameBase = `${controller}-${path.length ? `${path.join('-')}-` : ''}${method}-endpoint`;
1375
+ const endpointFolder = controllerFolder.subitem(routeSegments);
1376
+ const nameBase = `${controller}-${routeSegments.length ? `${routeSegments.join('-')}-` : ''}${method}-endpoint`;
923
1377
  const endpointNaming = new UnknownFormatNaming(nameBase);
1378
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1379
+ const { endpointGenerator, handler } = withWiring ? await promptEndpointDependencies(boundedContextFolder) : {
1380
+ endpointGenerator: void 0,
1381
+ handler: void 0
1382
+ };
1383
+ const endpointFile = node_path.join(endpointFolder.path, `${method.toUpperCase()}.ts`);
924
1384
  endpointFolder.createFile(`${method.toUpperCase()}.ts`, `
925
- import { EndpointGenerator } from '@domain-first/handlers-rest'
1385
+ ${endpointGenerator ? `import type { ${endpointGenerator.typeName} } from '${relativeImport(endpointFile, endpointGenerator.typeFile)}'` : "import { EndpointGenerator } from '@domain-first/handlers-rest'"}${handler ? `
1386
+ import type { ${handler.typeName} } from '${relativeImport(endpointFile, handler.typeFile)}'` : ''}
926
1387
 
927
1388
  export class ${endpointNaming.ClassName} {
928
1389
  constructor(
929
- private readonly endpointGenerator: EndpointGenerator,
930
- private readonly handler: never
1390
+ private readonly endpointGenerator: ${endpointGenerator?.typeName ?? 'EndpointGenerator'},
1391
+ private readonly handler: ${handler?.typeName ?? 'never'}
931
1392
  ) {}
932
1393
 
933
1394
  get handle() {
934
1395
  return this.endpointGenerator(this.handler.handle, {
935
- route: { method: '${method}', path: ['${boundedContextFolder.name}', '${controller}'${path.length ? `, ${path.map((x)=>`'${x}'`).join(', ')}` : ''}] },
1396
+ route: { method: '${method}', path: ['${boundedContextFolder.name}', '${controller}'${routeSegments.length ? `, ${routeSegments.map((x)=>`'${x}'`).join(', ')}` : ''}] },
936
1397
  tags: ['${boundedContextFolder.name}: ${controller}'],
937
1398
  })
938
1399
  }
939
1400
  }
940
1401
  `.trim());
941
- if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
1402
+ if (withWiring) {
942
1403
  const wiringFolder = boundedContextFolder.subitem([
943
1404
  'wiring',
944
1405
  'presentation',
@@ -947,13 +1408,19 @@ export class ${endpointNaming.ClassName} {
947
1408
  ]);
948
1409
  const wireNameBase = `wire-${nameBase}`;
949
1410
  const wireNaming = new UnknownFormatNaming(wireNameBase);
1411
+ const wireFile = node_path.join(wiringFolder.path, `${wireNaming.fileName}.ts`);
1412
+ const dependencies = endpointGenerator ? [
1413
+ endpointGenerator,
1414
+ handler
1415
+ ].filter((x)=>!!x) : [];
950
1416
  wiringFolder.createFile(`${wireNaming.fileName}.ts`, `
951
1417
  import { wireClass } from '@domain-first/wire'
952
- import { ${endpointNaming.ClassName} } from '../../../../presentation/rest/${controller}/${path.length ? `${path.join('/')}/` : ''}${method.toUpperCase()}'
1418
+ import { ${endpointNaming.ClassName} } from '${relativeImport(wireFile, endpointFile)}'
1419
+ ${dependencies.map((x)=>`import { ${x.wireName} } from '${relativeImport(wireFile, x.wireFile)}'`).join('\n')}
953
1420
 
954
1421
  export const wire${endpointNaming.ClassName} = wireClass(
955
1422
  ${endpointNaming.ClassName},
956
- []
1423
+ [${dependencies.map((x)=>x.wireName).join(', ')}]
957
1424
  )
958
1425
  `.trim());
959
1426
  wiringFolder.file('index.ts').addLine(`export * from './${wireNaming.fileName}'`);
@@ -996,7 +1463,8 @@ describe('${naming.withSpaces}', () => {
996
1463
  })
997
1464
  })
998
1465
  `.trim());
999
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
1466
+ if (withWiring) {
1467
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
1000
1468
  import { wireClass } from '@domain-first/wire'
1001
1469
  import { ${naming.ClassName}InfrastructureService } from '../../infrastructure/services/${naming.fileName}-infrastructure-service'
1002
1470
 
@@ -1005,6 +1473,8 @@ export const wire${naming.ClassName}InfrastructureService = wireClass(
1005
1473
  []
1006
1474
  )
1007
1475
  `.trim());
1476
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1477
+ }
1008
1478
  };
1009
1479
  const scaffoldNewPresentationService = async (boundedContextFolder)=>{
1010
1480
  const name = await input({
@@ -1043,7 +1513,8 @@ describe('${naming.withSpaces}', () => {
1043
1513
  })
1044
1514
  })
1045
1515
  `.trim());
1046
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1516
+ if (withWiring) {
1517
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1047
1518
  import { wireClass } from '@domain-first/wire'
1048
1519
  import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
1049
1520
 
@@ -1052,6 +1523,8 @@ export const wire${naming.ClassName}PresentationService = wireClass(
1052
1523
  []
1053
1524
  )
1054
1525
  `.trim());
1526
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1527
+ }
1055
1528
  };
1056
1529
  const scaffoldNewQuery = async (boundedContextFolder)=>{
1057
1530
  const queriesFolder = boundedContextFolder.subitem([
@@ -1170,7 +1643,7 @@ describe('${naming.withSpaces} query', () => {
1170
1643
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
1171
1644
  const implementationNaming = new UnknownFormatNaming(implementationType);
1172
1645
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
1173
- boundedContextFolder.subitem([
1646
+ const wireFile = boundedContextFolder.subitem([
1174
1647
  'wiring',
1175
1648
  'queries'
1176
1649
  ]).createFile(`wire-${naming.fileName}-query.ts`, `
@@ -1186,6 +1659,7 @@ export const wire${naming.ClassName}Query = envBranchedWire({
1186
1659
  production: wire${implementationNaming.ClassName}Implementation
1187
1660
  })
1188
1661
  `.trim());
1662
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1189
1663
  }
1190
1664
  return;
1191
1665
  }
@@ -1243,6 +1717,10 @@ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
1243
1717
  })
1244
1718
  })
1245
1719
  `.trim());
1720
+ if (withWiring) await wireNewModuleDependencies(boundedContextFolder, boundedContextFolder.subitem([
1721
+ 'wiring',
1722
+ 'queries'
1723
+ ]).file(`wire-${naming.fileName}-query.ts`));
1246
1724
  };
1247
1725
  const scaffoldNewUseCase = async (boundedContextFolder)=>{
1248
1726
  const useCasesFolder = boundedContextFolder.subitem([
@@ -1294,10 +1772,11 @@ describe('${naming.withSpaces} use case', () => {
1294
1772
  })
1295
1773
  })
1296
1774
  `.trim());
1297
- if (withWiring) boundedContextFolder.subitem([
1298
- 'wiring',
1299
- 'use-cases'
1300
- ]).createFile(`wire-${naming.fileName}-use-case.ts`, `
1775
+ if (withWiring) {
1776
+ const wireFile = boundedContextFolder.subitem([
1777
+ 'wiring',
1778
+ 'use-cases'
1779
+ ]).createFile(`wire-${naming.fileName}-use-case.ts`, `
1301
1780
  import { wireClass } from '@domain-first/wire'
1302
1781
  import { ${naming.ClassName}UseCase } from '../../application/use-cases/${naming.fileName}-use-case'
1303
1782
 
@@ -1307,14 +1786,38 @@ export const wire${naming.ClassName}UseCase = wireClass(
1307
1786
  )
1308
1787
 
1309
1788
  `.trim());
1789
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1790
+ }
1310
1791
  };
1792
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1793
+ class NestedName {
1794
+ folders;
1795
+ fileName;
1796
+ ClassName;
1797
+ classNameSegments;
1798
+ constructor(rawSource){
1799
+ const segments = splitSegments(rawSource);
1800
+ this.folders = segments.slice(0, -1);
1801
+ this.fileName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1802
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1803
+ this.ClassName = this.classNameSegments.join('');
1804
+ }
1805
+ static validate = (rawSource)=>{
1806
+ const segments = splitSegments(rawSource);
1807
+ if (!segments.length) return 'Name is required';
1808
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1809
+ return true;
1810
+ };
1811
+ }
1311
1812
  const scaffoldReactPage = async (presentationReactFolder)=>{
1312
1813
  const name = await input({
1313
- message: 'Provide name:'
1814
+ message: 'Provide name (folders split by "/"):',
1815
+ validate: NestedName.validate
1314
1816
  });
1315
- const { ClassName, fileName } = new UnknownFormatNaming(name);
1817
+ const { folders, ClassName, fileName } = new NestedName(name);
1316
1818
  presentationReactFolder.subitem([
1317
- 'pages'
1819
+ 'pages',
1820
+ ...folders
1318
1821
  ]).createFile(`${fileName}-page.tsx`, `
1319
1822
  import { type FC } from 'react'
1320
1823
 
@@ -1378,7 +1881,8 @@ export const Default: Story = {
1378
1881
  };
1379
1882
  const scaffoldReactWidget = async (presentationReactFolder)=>{
1380
1883
  const widgetName = await input({
1381
- message: 'Name: '
1884
+ message: 'Name (folders split by "/"): ',
1885
+ validate: NestedName.validate
1382
1886
  });
1383
1887
  const widgetType = await prompts_select({
1384
1888
  choices: [
@@ -1388,11 +1892,16 @@ const scaffoldReactWidget = async (presentationReactFolder)=>{
1388
1892
  ],
1389
1893
  message: 'Type: '
1390
1894
  });
1391
- const { ClassName, fileName } = new UnknownFormatNaming(widgetName);
1895
+ const { folders, ClassName, fileName, classNameSegments } = new NestedName(widgetName);
1392
1896
  const folder = presentationReactFolder.subitem([
1393
1897
  'widgets',
1898
+ ...folders,
1394
1899
  fileName
1395
1900
  ]);
1901
+ const storyTitle = [
1902
+ 'Widgets',
1903
+ ...classNameSegments
1904
+ ].join('/');
1396
1905
  const widgetFileName = `${fileName}-widget`;
1397
1906
  const uiFileName = `${fileName}-widget-ui`;
1398
1907
  const uiModelFileName = `use-${fileName}-ui-model`;
@@ -1447,7 +1956,7 @@ import type { Meta, StoryObj } from '${storybookFramework}'
1447
1956
  import { ${ClassName}WidgetUI } from './${uiFileName}'
1448
1957
 
1449
1958
  const meta = {
1450
- title: 'Widgets/${ClassName}',
1959
+ title: '${storyTitle}',
1451
1960
  component: ${ClassName}WidgetUI
1452
1961
  } satisfies Meta<typeof ${ClassName}WidgetUI>
1453
1962
 
@@ -1585,9 +2094,11 @@ const main = async ()=>{
1585
2094
  'Domain',
1586
2095
  'Application',
1587
2096
  'Infrastructure',
1588
- 'Presentation'
1589
- ]
2097
+ 'Presentation',
2098
+ ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? 'Wire dependency' : void 0
2099
+ ].filter((x)=>!!x)
1590
2100
  });
2101
+ if ('Wire dependency' === layer) return void await wireDependency(boundedContextFolder);
1591
2102
  if ('Domain' === layer) {
1592
2103
  const operation = await prompts_select({
1593
2104
  message: 'Domain layer operation:',