@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.cjs CHANGED
@@ -113,6 +113,12 @@ class File extends FileSystemItem {
113
113
  replacesFile: true
114
114
  });
115
115
  }
116
+ update = (content)=>{
117
+ pendingFiles.set(this.path, {
118
+ content,
119
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
120
+ });
121
+ };
116
122
  addLine = (newLine, separator = '\n')=>{
117
123
  const content = this.exists ? this.data : '';
118
124
  pendingFiles.set(this.path, {
@@ -277,6 +283,439 @@ class UnknownFormatNaming {
277
283
  return this.fileName.replaceAll('-', ' ');
278
284
  }
279
285
  }
286
+ const wiring_layers = [
287
+ 'domain',
288
+ 'application',
289
+ 'infrastructure',
290
+ 'presentation'
291
+ ];
292
+ const visibleLayers = {
293
+ domain: [
294
+ 'domain'
295
+ ],
296
+ application: [
297
+ 'domain',
298
+ 'application'
299
+ ],
300
+ infrastructure: [
301
+ 'domain',
302
+ 'infrastructure'
303
+ ],
304
+ presentation: [
305
+ 'application',
306
+ 'presentation'
307
+ ]
308
+ };
309
+ const branchedTypeFiles = {
310
+ repositories: (fileBase)=>[
311
+ 'domain',
312
+ 'aggregates',
313
+ fileBase.replace(/-repository$/, ''),
314
+ `${fileBase}.ts`
315
+ ],
316
+ commands: (fileBase)=>[
317
+ 'application',
318
+ 'commands',
319
+ 'execution',
320
+ `${fileBase}.ts`
321
+ ],
322
+ queries: (fileBase)=>[
323
+ 'application',
324
+ 'queries',
325
+ 'execution',
326
+ `${fileBase}.ts`
327
+ ],
328
+ 'application-ports': (fileBase)=>[
329
+ 'application',
330
+ 'ports',
331
+ `${fileBase}.ts`
332
+ ]
333
+ };
334
+ const layerOf = (file, contextPath)=>{
335
+ const [firstSegment] = external_node_path_default().relative(contextPath, file).split(external_node_path_default().sep);
336
+ return wiring_layers.find((layer)=>layer === firstSegment);
337
+ };
338
+ const namedImports = (source, fromFile)=>{
339
+ const result = new Map();
340
+ for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
341
+ const cleanName = name.replace(/^\s*type\s+/, '').trim();
342
+ if (cleanName) result.set(cleanName, `${external_node_path_default().resolve(external_node_path_default().dirname(fromFile), importPath)}.ts`);
343
+ }
344
+ return result;
345
+ };
346
+ const isEndpointWire = (wiringRelativePath)=>wiringRelativePath.startsWith([
347
+ 'presentation',
348
+ 'rest'
349
+ ].join(external_node_path_default().sep));
350
+ const wireClassDefinitions = (source)=>[
351
+ ...codeOnly(source).matchAll(/(?:export\s+)?const\s+(\w+)\s*=\s*(?:\w+\(\s*)*wireClass\(\s*(\w+)\s*,/g)
352
+ ].map(([, wireName, className])=>({
353
+ wireName,
354
+ className
355
+ }));
356
+ const wiredClassNames = (source, wireName, initializerStart, branched)=>{
357
+ const definitions = wireClassDefinitions(source);
358
+ if (!branched) return definitions.filter((x)=>x.wireName === wireName).map((x)=>x.className);
359
+ const openIndex = source.indexOf('(', initializerStart);
360
+ const branches = codeOnly(source).slice(openIndex, closingIndex(source, openIndex));
361
+ const referenced = new Set(branches.match(/\w+/g));
362
+ return definitions.filter((x)=>referenced.has(x.wireName)).map((x)=>x.className);
363
+ };
364
+ const readWiredModule = (wireFile, contextPath)=>{
365
+ const wiringRelativePath = external_node_path_default().relative(external_node_path_default().join(contextPath, 'wiring'), wireFile);
366
+ if (isEndpointWire(wiringRelativePath)) return;
367
+ const source = new File(wireFile).data;
368
+ const wireName = `wire${new UnknownFormatNaming(external_node_path_default().basename(wireFile, '.ts').replace(/^wire-/, '')).ClassName}`;
369
+ const exportMatch = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*`).exec(source);
370
+ if (!exportMatch) return;
371
+ const branched = source.slice(exportMatch.index + exportMatch[0].length).startsWith('envBranchedWire(');
372
+ const imports = namedImports(source, wireFile);
373
+ const implementations = wiredClassNames(source, wireName, exportMatch.index + exportMatch[0].length, branched).flatMap((className)=>{
374
+ const file = imports.get(className);
375
+ return file ? [
376
+ {
377
+ className,
378
+ file
379
+ }
380
+ ] : [];
381
+ });
382
+ if (!implementations.length) return;
383
+ const typeName = wireName.slice(4);
384
+ const [wiringFolder] = wiringRelativePath.split(external_node_path_default().sep);
385
+ const typeFileSegments = branchedTypeFiles[wiringFolder]?.(external_node_path_default().basename(wireFile, '.ts').replace(/^wire-/, ''));
386
+ const typeFile = branched ? typeFileSegments && external_node_path_default().join(contextPath, ...typeFileSegments) : implementations[0].file;
387
+ const layer = typeFile && layerOf(typeFile, contextPath);
388
+ const implementationsLayer = layerOf(implementations[0].file, contextPath);
389
+ if (!typeFile || !layer || !implementationsLayer) return;
390
+ return {
391
+ wireName,
392
+ typeName,
393
+ wireFile,
394
+ typeFile,
395
+ layer,
396
+ implementations,
397
+ branched,
398
+ implementationsLayer,
399
+ kind: wiringFolder
400
+ };
401
+ };
402
+ const findWiredModules = (contextPath)=>{
403
+ const result = [];
404
+ const walk = (folderPath)=>{
405
+ if (!external_node_fs_default().existsSync(folderPath)) return;
406
+ for (const entry of external_node_fs_default().readdirSync(folderPath, {
407
+ withFileTypes: true
408
+ })){
409
+ const entryPath = external_node_path_default().join(folderPath, entry.name);
410
+ if (entry.isDirectory()) walk(entryPath);
411
+ else if (/^wire-.*(?<!\.spec)\.ts$/.test(entry.name)) {
412
+ const wiredModule = readWiredModule(entryPath, contextPath);
413
+ if (wiredModule) result.push(wiredModule);
414
+ }
415
+ }
416
+ };
417
+ walk(external_node_path_default().join(contextPath, 'wiring'));
418
+ return result.sort((a, b)=>a.typeName.localeCompare(b.typeName));
419
+ };
420
+ const isCommandOrQuery = (module)=>'commands' === module.kind || 'queries' === module.kind;
421
+ const isExecution = (module)=>isCommandOrQuery(module) && 'execution' === external_node_path_default().basename(external_node_path_default().dirname(module.typeFile));
422
+ const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate);
423
+ const kindRules = {
424
+ 'application-services': (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind,
425
+ 'use-cases': (candidate)=>'use-cases' !== candidate.kind,
426
+ repositories: (candidate)=>'repositories' !== candidate.kind,
427
+ commands: commandOrQueryRule,
428
+ queries: commandOrQueryRule
429
+ };
430
+ const wiring_implementationType = (consumer, implementation)=>consumer.branched ? external_node_path_default().basename(external_node_path_default().dirname(implementation.file)) : void 0;
431
+ const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${external_node_path_default().basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
432
+ const isSuggestedEndpointGenerator = (candidate)=>candidate.typeName.toLowerCase().includes('endpoint');
433
+ const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
434
+ const availableDependencies = (consumer, implementation, candidates)=>{
435
+ const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
436
+ return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate) && !wired.includes(candidate.wireName));
437
+ };
438
+ const relativeImport = (fromFile, toFile)=>{
439
+ const relativePath = external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile).replace(/\.ts$/, '').split(external_node_path_default().sep).join('/');
440
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
441
+ };
442
+ const codeOnly = (source)=>{
443
+ let result = '';
444
+ let index = 0;
445
+ const blank = (text)=>text.replace(/[^\n]/g, ' ');
446
+ while(index < source.length){
447
+ const pair = source.slice(index, index + 2);
448
+ const char = source[index];
449
+ let end = index + 1;
450
+ if ('//' === pair) {
451
+ const lineEnd = source.indexOf('\n', index);
452
+ end = -1 === lineEnd ? source.length : lineEnd;
453
+ result += blank(source.slice(index, end));
454
+ } else if ('/*' === pair) {
455
+ const commentEnd = source.indexOf('*/', index + 2);
456
+ end = -1 === commentEnd ? source.length : commentEnd + 2;
457
+ result += blank(source.slice(index, end));
458
+ } else if ('=>' === pair) {
459
+ end = index + 2;
460
+ result += ' ';
461
+ } else if ("'" === char || '"' === char || '`' === char) {
462
+ while(end < source.length && source[end] !== char)end += '\\' === source[end] ? 2 : 1;
463
+ end = Math.min(end + 1, source.length);
464
+ result += char + blank(source.slice(index + 1, end - 1));
465
+ result += end - 1 > index ? source[end - 1] : '';
466
+ } else result += char;
467
+ index = end;
468
+ }
469
+ return result;
470
+ };
471
+ const addImport = (source, importLine)=>{
472
+ if (source.split('\n').some((line)=>line.trim() === importLine)) return source;
473
+ const lastImport = [
474
+ ...codeOnly(source).matchAll(/^import\s(?:[^'"]*?from\s*)?['"][^'"]*['"]/gm)
475
+ ].at(-1);
476
+ if (!lastImport) return `${importLine}\n\n${source}`;
477
+ const importEnd = lastImport.index + lastImport[0].length;
478
+ const lineEnd = source.indexOf('\n', importEnd);
479
+ const insertAt = -1 === lineEnd ? source.length : lineEnd;
480
+ return `${source.slice(0, insertAt)}\n${importLine}${source.slice(insertAt)}`;
481
+ };
482
+ const brackets = {
483
+ '(': ')',
484
+ '[': ']',
485
+ '{': '}',
486
+ '<': '>'
487
+ };
488
+ const closingIndex = (source, openIndex)=>{
489
+ const code = codeOnly(source);
490
+ let depth = 0;
491
+ for(let index = openIndex; index < code.length; index++){
492
+ const char = code[index];
493
+ if (char === code[openIndex]) depth++;
494
+ else if (char === brackets[code[openIndex]]) {
495
+ depth--;
496
+ if (0 === depth) return index;
497
+ }
498
+ }
499
+ return -1;
500
+ };
501
+ const splitTopLevel = (content)=>{
502
+ const code = codeOnly(content);
503
+ const items = [];
504
+ let depth = 0;
505
+ let itemStart = 0;
506
+ for(let index = 0; index <= code.length; index++){
507
+ const char = code[index];
508
+ if (void 0 !== char && char in brackets) depth++;
509
+ else if (Object.values(brackets).includes(char)) depth--;
510
+ if (index === code.length || ',' === char && 0 === depth) {
511
+ const item = content.slice(itemStart, index);
512
+ const itemCode = code.slice(itemStart, index);
513
+ const first = itemCode.search(/\S/);
514
+ const last = itemCode.search(/\S\s*$/);
515
+ if (-1 !== first) items.push(item.slice(first, last + 1));
516
+ itemStart = index + 1;
517
+ }
518
+ }
519
+ return items;
520
+ };
521
+ const appendItems = (content, items)=>{
522
+ const code = codeOnly(content);
523
+ const lastCode = code.search(/\S\s*$/);
524
+ if (-1 === lastCode) return items.join(', ');
525
+ const trailingComma = ',' === code[lastCode];
526
+ if (!content.includes('\n')) {
527
+ const added = trailingComma ? ` ${items.join(', ')},` : `, ${items.join(', ')}`;
528
+ return content.slice(0, lastCode + 1) + added + content.slice(lastCode + 1);
529
+ }
530
+ const indent = content.match(/\n([ \t]*)\S/)?.[1] ?? '';
531
+ const withComma = trailingComma ? content : `${content.slice(0, lastCode + 1)},${content.slice(lastCode + 1)}`;
532
+ const lineEndIndex = withComma.indexOf('\n', lastCode + 1);
533
+ const lineEnd = -1 === lineEndIndex ? withComma.length : lineEndIndex;
534
+ const added = trailingComma ? items.map((x)=>`\n${indent}${x},`).join('') : items.map((x)=>`\n${indent}${x}`).join(',');
535
+ return withComma.slice(0, lineEnd) + added + withComma.slice(lineEnd);
536
+ };
537
+ const addConstructorParameters = (source, className, parameters)=>{
538
+ const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
539
+ if (!classMatch) throw new Error(`Class ${className} not found`);
540
+ const bodyStart = classMatch.index + classMatch[0].length;
541
+ const bodyEnd = closingIndex(source, bodyStart - 1);
542
+ const body = source.slice(bodyStart, bodyEnd);
543
+ const constructorIndex = codeOnly(body).search(/\bconstructor\s*\(/);
544
+ const renderParameters = (allParameters, indent)=>1 === allParameters.length ? allParameters[0] : `\n${allParameters.map((x)=>`${indent} ${x}`).join(',\n')}\n${indent}`;
545
+ if (-1 === constructorIndex) {
546
+ const constructorBody = /\bextends\b/.test(classMatch[0]) ? '{\n super()\n }' : '{}';
547
+ const constructorLine = ` constructor(${renderParameters(parameters, ' ')}) ${constructorBody}`;
548
+ const newBody = body.trim() ? `\n${constructorLine}\n${body.replace(/^\s*\n/, '\n')}` : `\n${constructorLine}\n`;
549
+ return source.slice(0, bodyStart) + newBody + source.slice(bodyEnd);
550
+ }
551
+ const openIndex = bodyStart + body.indexOf('(', constructorIndex);
552
+ const closeIndex = closingIndex(source, openIndex);
553
+ const content = source.slice(openIndex + 1, closeIndex);
554
+ if (content.includes('\n')) return source.slice(0, openIndex + 1) + appendItems(content, parameters) + source.slice(closeIndex);
555
+ const lineStart = source.lastIndexOf('\n', openIndex) + 1;
556
+ const indent = source.slice(lineStart).match(/^\s*/)?.[0] ?? '';
557
+ return source.slice(0, openIndex + 1) + renderParameters([
558
+ ...splitTopLevel(content),
559
+ ...parameters
560
+ ], indent) + source.slice(closeIndex);
561
+ };
562
+ const wireListRange = (source, className)=>{
563
+ const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
564
+ if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
565
+ const openIndex = match.index + match[0].length - 1;
566
+ return {
567
+ openIndex,
568
+ closeIndex: closingIndex(source, openIndex)
569
+ };
570
+ };
571
+ const wiredDependencyNames = (source, className)=>{
572
+ const { openIndex, closeIndex } = wireListRange(source, className);
573
+ return splitTopLevel(source.slice(openIndex + 1, closeIndex));
574
+ };
575
+ const addWireDependencies = (source, className, wireNames)=>{
576
+ const { openIndex, closeIndex } = wireListRange(source, className);
577
+ return source.slice(0, openIndex + 1) + appendItems(source.slice(openIndex + 1, closeIndex), wireNames) + source.slice(closeIndex);
578
+ };
579
+ const parameterName = (typeName)=>typeName.substring(0, 1).toLowerCase() + typeName.substring(1);
580
+ const wireDependencies = (consumer, implementation, dependencies)=>{
581
+ const wireFile = new File(consumer.wireFile);
582
+ let wireSource = wireFile.data;
583
+ for (const dependency of dependencies)wireSource = addImport(wireSource, `import { ${dependency.wireName} } from '${relativeImport(consumer.wireFile, dependency.wireFile)}'`);
584
+ wireFile.update(addWireDependencies(wireSource, implementation.className, dependencies.map((x)=>x.wireName)));
585
+ const classFile = new File(implementation.file);
586
+ let classSource = classFile.data;
587
+ for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
588
+ classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
589
+ };
590
+ const kindTitles = {
591
+ repositories: 'Repositories',
592
+ 'domain-services': 'Domain services',
593
+ 'application-ports': 'Ports',
594
+ 'application-services': 'Application services',
595
+ queries: 'Queries',
596
+ commands: 'Commands',
597
+ 'use-cases': 'Use cases',
598
+ 'infrastructure-services': 'Infrastructure services',
599
+ 'presentation-services': 'Presentation services'
600
+ };
601
+ const groupedChoices = (items, suggested = [])=>{
602
+ const suggestedChoices = suggested.length ? [
603
+ new prompts_namespaceObject.Separator('── Suggested'),
604
+ ...suggested.map((x)=>({
605
+ name: x.label,
606
+ value: x
607
+ }))
608
+ ] : [];
609
+ const kinds = [
610
+ ...new Set([
611
+ ...Object.keys(kindTitles),
612
+ ...items.map((x)=>x.module.kind)
613
+ ])
614
+ ];
615
+ return [
616
+ ...suggestedChoices,
617
+ ...kinds.flatMap((kind)=>{
618
+ const group = items.filter((x)=>x.module.kind === kind && !suggested.includes(x));
619
+ return group.length ? [
620
+ new prompts_namespaceObject.Separator(`── ${kindTitles[kind] ?? kind}`),
621
+ ...group.map((x)=>({
622
+ name: x.label,
623
+ value: x
624
+ }))
625
+ ] : [];
626
+ })
627
+ ];
628
+ };
629
+ const groupedPageSize = 20;
630
+ const contextAndSharedModules = (boundedContextFolder)=>{
631
+ const sharedFolder = new Folder(new ProjectRoot().path).subitem([
632
+ ConfigFile.Instance.data.rootFolder,
633
+ 'shared'
634
+ ]);
635
+ const isShared = sharedFolder.path === boundedContextFolder.path;
636
+ return [
637
+ ...findWiredModules(boundedContextFolder.path).map((x)=>({
638
+ module: x,
639
+ label: x.typeName
640
+ })),
641
+ ...isShared ? [] : findWiredModules(sharedFolder.path).map((x)=>({
642
+ module: x,
643
+ label: `${x.typeName} (shared)`
644
+ }))
645
+ ];
646
+ };
647
+ const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations)=>{
648
+ const options = contextAndSharedModules(boundedContextFolder);
649
+ let asked = false;
650
+ for (const implementation of implementations){
651
+ const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
652
+ const candidates = options.filter((x)=>available.includes(x.module));
653
+ if (!candidates.length) continue;
654
+ asked = true;
655
+ const type = wiring_implementationType(consumer, implementation);
656
+ const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
657
+ const dependencies = await (0, prompts_namespaceObject.checkbox)({
658
+ message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
659
+ choices: groupedChoices(candidates, suggested),
660
+ pageSize: groupedPageSize,
661
+ loop: false
662
+ });
663
+ if (dependencies.length) wireDependencies(consumer, implementation, dependencies.map((x)=>x.module));
664
+ }
665
+ return asked;
666
+ };
667
+ const wireNewModuleDependencies = async (boundedContextFolder, wireFile)=>{
668
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
669
+ if (consumer) await promptDependencies(boundedContextFolder, consumer);
670
+ };
671
+ const wireDependency = async (boundedContextFolder)=>{
672
+ const modules = findWiredModules(boundedContextFolder.path);
673
+ if (!modules.length) return void console.log('No wired modules here yet.');
674
+ const { module: consumer, implementation } = await (0, prompts_namespaceObject.select)({
675
+ message: 'Module:',
676
+ choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
677
+ const type = wiring_implementationType(x, implementation);
678
+ return {
679
+ module: x,
680
+ label: type ? `${x.typeName} (${type})` : x.typeName,
681
+ implementation
682
+ };
683
+ }))),
684
+ pageSize: groupedPageSize,
685
+ loop: false
686
+ });
687
+ if (!await promptDependencies(boundedContextFolder, consumer, [
688
+ implementation
689
+ ])) console.log('No dependencies available for this module.');
690
+ };
691
+ const promptEndpointDependencies = async (boundedContextFolder)=>{
692
+ const options = contextAndSharedModules(boundedContextFolder);
693
+ const generators = options.filter((x)=>'presentation-services' === x.module.kind);
694
+ const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
695
+ 'queries',
696
+ 'commands',
697
+ 'use-cases'
698
+ ].includes(x.kind)).map((x)=>({
699
+ module: x,
700
+ label: x.typeName
701
+ }));
702
+ const endpointGenerator = generators.length ? (await (0, prompts_namespaceObject.select)({
703
+ message: 'Endpoint generator:',
704
+ choices: groupedChoices(generators, generators.filter((x)=>isSuggestedEndpointGenerator(x.module))),
705
+ pageSize: groupedPageSize,
706
+ loop: false
707
+ })).module : void 0;
708
+ const handler = handlers.length ? (await (0, prompts_namespaceObject.select)({
709
+ message: 'Handler:',
710
+ choices: groupedChoices(handlers),
711
+ pageSize: groupedPageSize,
712
+ loop: false
713
+ })).module : void 0;
714
+ return {
715
+ endpointGenerator,
716
+ handler
717
+ };
718
+ };
280
719
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
281
720
  const aggregateName = await (0, prompts_namespaceObject.input)({
282
721
  message: 'Aggregate name:'
@@ -376,7 +815,7 @@ describe('${aggregateNaming.withSpaces} repository', () => {
376
815
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
377
816
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
378
817
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
379
- boundedContextFolder.subitem([
818
+ const wireFile = boundedContextFolder.subitem([
380
819
  'wiring',
381
820
  'repositories'
382
821
  ]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
@@ -392,6 +831,7 @@ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
392
831
  production: wire${implementationNaming.ClassName}Implementation
393
832
  })
394
833
  `.trim());
834
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
395
835
  }
396
836
  }
397
837
  };
@@ -468,18 +908,19 @@ describe('${naming.withSpaces}', () => {
468
908
  })
469
909
  `.trim());
470
910
  }
471
- if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
911
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
912
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
472
913
  import { wireClass } from '@domain-first/wire'
473
914
  import { envBranchedWire } from '../../../${'shared' === boundedContextFolder.name ? '' : '../'}shared/wiring/env-branched-wire'
474
915
  ${implementationTypes.map((x)=>({
475
- naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
476
- implementation: x
477
- })).map(({ naming: { ClassName, fileName }, implementation })=>`import { ${ClassName} } from '../../infrastructure/application-adapters/${implementation}/${fileName}'`).join('\n')}
916
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
917
+ implementation: x
918
+ })).map(({ naming: { ClassName, fileName }, implementation })=>`import { ${ClassName} } from '../../infrastructure/application-adapters/${implementation}/${fileName}'`).join('\n')}
478
919
 
479
920
  ${implementationTypes.map((x)=>({
480
- naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
481
- implementation: x
482
- })).map(({ naming: { ClassName }, implementation })=>`const wire${new UnknownFormatNaming(implementation).ClassName}Implementation = wireClass(${ClassName}, [])`).join('\n\n')}
921
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
922
+ implementation: x
923
+ })).map(({ naming: { ClassName }, implementation })=>`const wire${new UnknownFormatNaming(implementation).ClassName}Implementation = wireClass(${ClassName}, [])`).join('\n\n')}
483
924
 
484
925
  export const wire${naming.ClassName} = envBranchedWire({
485
926
  test: wire${new UnknownFormatNaming(`${implementationTypes.at(-1)}-implementation`).ClassName},
@@ -488,6 +929,8 @@ export const wire${naming.ClassName} = envBranchedWire({
488
929
  })
489
930
 
490
931
  `.trim());
932
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
933
+ }
491
934
  };
492
935
  const scaffoldNewApplicationService = async (boundedContextFolder)=>{
493
936
  const name = await (0, prompts_namespaceObject.input)({
@@ -526,7 +969,8 @@ describe('${naming.withSpaces}', () => {
526
969
  })
527
970
  })
528
971
  `.trim());
529
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-application-service.ts`, `
972
+ if (withWiring) {
973
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-application-service.ts`, `
530
974
  import { wireClass } from '@domain-first/wire'
531
975
  import { ${naming.ClassName}ApplicationService } from '../../application/services/${naming.fileName}-application-service'
532
976
 
@@ -535,6 +979,8 @@ export const wire${naming.ClassName}ApplicationService = wireClass(
535
979
  []
536
980
  )
537
981
  `.trim());
982
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
983
+ }
538
984
  };
539
985
  const scaffoldNewBoundedContextUseCase = async ()=>{
540
986
  const name = await (0, prompts_namespaceObject.input)({
@@ -675,7 +1121,7 @@ describe('${naming.withSpaces} command', () => {
675
1121
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
676
1122
  const implementationNaming = new UnknownFormatNaming(implementationType);
677
1123
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
678
- boundedContextFolder.subitem([
1124
+ const wireFile = boundedContextFolder.subitem([
679
1125
  'wiring',
680
1126
  'commands'
681
1127
  ]).createFile(`wire-${naming.fileName}-command.ts`, `
@@ -691,6 +1137,7 @@ export const wire${naming.ClassName}Command = envBranchedWire({
691
1137
  production: wire${implementationNaming.ClassName}Implementation
692
1138
  })
693
1139
  `.trim());
1140
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
694
1141
  }
695
1142
  return;
696
1143
  }
@@ -748,6 +1195,10 @@ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
748
1195
  })
749
1196
  })
750
1197
  `.trim());
1198
+ if (withWiring) await wireNewModuleDependencies(boundedContextFolder, boundedContextFolder.subitem([
1199
+ 'wiring',
1200
+ 'commands'
1201
+ ]).file(`wire-${naming.fileName}-command.ts`));
751
1202
  };
752
1203
  const noAggregate = 'No aggregate';
753
1204
  const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
@@ -836,10 +1287,11 @@ describe('${naming.withSpaces}', () => {
836
1287
  })
837
1288
  })
838
1289
  `.trim());
839
- if (withWiring) boundedContextFolder.subitem([
840
- 'wiring',
841
- 'domain-services'
842
- ]).createFile(`wire-${naming.fileName}-domain-service.ts`, `
1290
+ if (withWiring) {
1291
+ const wireFile = boundedContextFolder.subitem([
1292
+ 'wiring',
1293
+ 'domain-services'
1294
+ ]).createFile(`wire-${naming.fileName}-domain-service.ts`, `
843
1295
  import { wireClass } from '@domain-first/wire'
844
1296
  import { ${naming.ClassName}DomainService } from '../../domain/services/${naming.fileName}-domain-service'
845
1297
 
@@ -848,6 +1300,8 @@ export const wire${naming.ClassName}DomainService = wireClass(
848
1300
  []
849
1301
  )
850
1302
  `.trim());
1303
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1304
+ }
851
1305
  };
852
1306
  const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
853
1307
  const currentErrorFolder = boundedContextFolder.subitem([
@@ -942,33 +1396,40 @@ export const restHandlers = restWires.map(x => x().handle)
942
1396
  'put'
943
1397
  ]
944
1398
  });
945
- const path = (await (0, prompts_namespaceObject.input)({
1399
+ const routeSegments = (await (0, prompts_namespaceObject.input)({
946
1400
  message: 'Relative path (split by "/"):'
947
1401
  })).split('/').filter((x)=>!!x);
948
1402
  const controllerFolder = restPresentationFolder.subitem([
949
1403
  controller
950
1404
  ]);
951
- const endpointFolder = controllerFolder.subitem(path);
952
- const nameBase = `${controller}-${path.length ? `${path.join('-')}-` : ''}${method}-endpoint`;
1405
+ const endpointFolder = controllerFolder.subitem(routeSegments);
1406
+ const nameBase = `${controller}-${routeSegments.length ? `${routeSegments.join('-')}-` : ''}${method}-endpoint`;
953
1407
  const endpointNaming = new UnknownFormatNaming(nameBase);
1408
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1409
+ const { endpointGenerator, handler } = withWiring ? await promptEndpointDependencies(boundedContextFolder) : {
1410
+ endpointGenerator: void 0,
1411
+ handler: void 0
1412
+ };
1413
+ const endpointFile = external_node_path_default().join(endpointFolder.path, `${method.toUpperCase()}.ts`);
954
1414
  endpointFolder.createFile(`${method.toUpperCase()}.ts`, `
955
- import { EndpointGenerator } from '@domain-first/handlers-rest'
1415
+ ${endpointGenerator ? `import type { ${endpointGenerator.typeName} } from '${relativeImport(endpointFile, endpointGenerator.typeFile)}'` : "import { EndpointGenerator } from '@domain-first/handlers-rest'"}${handler ? `
1416
+ import type { ${handler.typeName} } from '${relativeImport(endpointFile, handler.typeFile)}'` : ''}
956
1417
 
957
1418
  export class ${endpointNaming.ClassName} {
958
1419
  constructor(
959
- private readonly endpointGenerator: EndpointGenerator,
960
- private readonly handler: never
1420
+ private readonly endpointGenerator: ${endpointGenerator?.typeName ?? 'EndpointGenerator'},
1421
+ private readonly handler: ${handler?.typeName ?? 'never'}
961
1422
  ) {}
962
1423
 
963
1424
  get handle() {
964
1425
  return this.endpointGenerator(this.handler.handle, {
965
- route: { method: '${method}', path: ['${boundedContextFolder.name}', '${controller}'${path.length ? `, ${path.map((x)=>`'${x}'`).join(', ')}` : ''}] },
1426
+ route: { method: '${method}', path: ['${boundedContextFolder.name}', '${controller}'${routeSegments.length ? `, ${routeSegments.map((x)=>`'${x}'`).join(', ')}` : ''}] },
966
1427
  tags: ['${boundedContextFolder.name}: ${controller}'],
967
1428
  })
968
1429
  }
969
1430
  }
970
1431
  `.trim());
971
- if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
1432
+ if (withWiring) {
972
1433
  const wiringFolder = boundedContextFolder.subitem([
973
1434
  'wiring',
974
1435
  'presentation',
@@ -977,13 +1438,19 @@ export class ${endpointNaming.ClassName} {
977
1438
  ]);
978
1439
  const wireNameBase = `wire-${nameBase}`;
979
1440
  const wireNaming = new UnknownFormatNaming(wireNameBase);
1441
+ const wireFile = external_node_path_default().join(wiringFolder.path, `${wireNaming.fileName}.ts`);
1442
+ const dependencies = endpointGenerator ? [
1443
+ endpointGenerator,
1444
+ handler
1445
+ ].filter((x)=>!!x) : [];
980
1446
  wiringFolder.createFile(`${wireNaming.fileName}.ts`, `
981
1447
  import { wireClass } from '@domain-first/wire'
982
- import { ${endpointNaming.ClassName} } from '../../../../presentation/rest/${controller}/${path.length ? `${path.join('/')}/` : ''}${method.toUpperCase()}'
1448
+ import { ${endpointNaming.ClassName} } from '${relativeImport(wireFile, endpointFile)}'
1449
+ ${dependencies.map((x)=>`import { ${x.wireName} } from '${relativeImport(wireFile, x.wireFile)}'`).join('\n')}
983
1450
 
984
1451
  export const wire${endpointNaming.ClassName} = wireClass(
985
1452
  ${endpointNaming.ClassName},
986
- []
1453
+ [${dependencies.map((x)=>x.wireName).join(', ')}]
987
1454
  )
988
1455
  `.trim());
989
1456
  wiringFolder.file('index.ts').addLine(`export * from './${wireNaming.fileName}'`);
@@ -1026,7 +1493,8 @@ describe('${naming.withSpaces}', () => {
1026
1493
  })
1027
1494
  })
1028
1495
  `.trim());
1029
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
1496
+ if (withWiring) {
1497
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
1030
1498
  import { wireClass } from '@domain-first/wire'
1031
1499
  import { ${naming.ClassName}InfrastructureService } from '../../infrastructure/services/${naming.fileName}-infrastructure-service'
1032
1500
 
@@ -1035,6 +1503,8 @@ export const wire${naming.ClassName}InfrastructureService = wireClass(
1035
1503
  []
1036
1504
  )
1037
1505
  `.trim());
1506
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1507
+ }
1038
1508
  };
1039
1509
  const scaffoldNewPresentationService = async (boundedContextFolder)=>{
1040
1510
  const name = await (0, prompts_namespaceObject.input)({
@@ -1073,7 +1543,8 @@ describe('${naming.withSpaces}', () => {
1073
1543
  })
1074
1544
  })
1075
1545
  `.trim());
1076
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1546
+ if (withWiring) {
1547
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1077
1548
  import { wireClass } from '@domain-first/wire'
1078
1549
  import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
1079
1550
 
@@ -1082,6 +1553,8 @@ export const wire${naming.ClassName}PresentationService = wireClass(
1082
1553
  []
1083
1554
  )
1084
1555
  `.trim());
1556
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1557
+ }
1085
1558
  };
1086
1559
  const scaffoldNewQuery = async (boundedContextFolder)=>{
1087
1560
  const queriesFolder = boundedContextFolder.subitem([
@@ -1200,7 +1673,7 @@ describe('${naming.withSpaces} query', () => {
1200
1673
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
1201
1674
  const implementationNaming = new UnknownFormatNaming(implementationType);
1202
1675
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
1203
- boundedContextFolder.subitem([
1676
+ const wireFile = boundedContextFolder.subitem([
1204
1677
  'wiring',
1205
1678
  'queries'
1206
1679
  ]).createFile(`wire-${naming.fileName}-query.ts`, `
@@ -1216,6 +1689,7 @@ export const wire${naming.ClassName}Query = envBranchedWire({
1216
1689
  production: wire${implementationNaming.ClassName}Implementation
1217
1690
  })
1218
1691
  `.trim());
1692
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1219
1693
  }
1220
1694
  return;
1221
1695
  }
@@ -1273,6 +1747,10 @@ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
1273
1747
  })
1274
1748
  })
1275
1749
  `.trim());
1750
+ if (withWiring) await wireNewModuleDependencies(boundedContextFolder, boundedContextFolder.subitem([
1751
+ 'wiring',
1752
+ 'queries'
1753
+ ]).file(`wire-${naming.fileName}-query.ts`));
1276
1754
  };
1277
1755
  const scaffoldNewUseCase = async (boundedContextFolder)=>{
1278
1756
  const useCasesFolder = boundedContextFolder.subitem([
@@ -1324,10 +1802,11 @@ describe('${naming.withSpaces} use case', () => {
1324
1802
  })
1325
1803
  })
1326
1804
  `.trim());
1327
- if (withWiring) boundedContextFolder.subitem([
1328
- 'wiring',
1329
- 'use-cases'
1330
- ]).createFile(`wire-${naming.fileName}-use-case.ts`, `
1805
+ if (withWiring) {
1806
+ const wireFile = boundedContextFolder.subitem([
1807
+ 'wiring',
1808
+ 'use-cases'
1809
+ ]).createFile(`wire-${naming.fileName}-use-case.ts`, `
1331
1810
  import { wireClass } from '@domain-first/wire'
1332
1811
  import { ${naming.ClassName}UseCase } from '../../application/use-cases/${naming.fileName}-use-case'
1333
1812
 
@@ -1337,14 +1816,38 @@ export const wire${naming.ClassName}UseCase = wireClass(
1337
1816
  )
1338
1817
 
1339
1818
  `.trim());
1819
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1820
+ }
1340
1821
  };
1822
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1823
+ class NestedName {
1824
+ folders;
1825
+ fileName;
1826
+ ClassName;
1827
+ classNameSegments;
1828
+ constructor(rawSource){
1829
+ const segments = splitSegments(rawSource);
1830
+ this.folders = segments.slice(0, -1);
1831
+ this.fileName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1832
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1833
+ this.ClassName = this.classNameSegments.join('');
1834
+ }
1835
+ static validate = (rawSource)=>{
1836
+ const segments = splitSegments(rawSource);
1837
+ if (!segments.length) return 'Name is required';
1838
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1839
+ return true;
1840
+ };
1841
+ }
1341
1842
  const scaffoldReactPage = async (presentationReactFolder)=>{
1342
1843
  const name = await (0, prompts_namespaceObject.input)({
1343
- message: 'Provide name:'
1844
+ message: 'Provide name (folders split by "/"):',
1845
+ validate: NestedName.validate
1344
1846
  });
1345
- const { ClassName, fileName } = new UnknownFormatNaming(name);
1847
+ const { folders, ClassName, fileName } = new NestedName(name);
1346
1848
  presentationReactFolder.subitem([
1347
- 'pages'
1849
+ 'pages',
1850
+ ...folders
1348
1851
  ]).createFile(`${fileName}-page.tsx`, `
1349
1852
  import { type FC } from 'react'
1350
1853
 
@@ -1408,7 +1911,8 @@ export const Default: Story = {
1408
1911
  };
1409
1912
  const scaffoldReactWidget = async (presentationReactFolder)=>{
1410
1913
  const widgetName = await (0, prompts_namespaceObject.input)({
1411
- message: 'Name: '
1914
+ message: 'Name (folders split by "/"): ',
1915
+ validate: NestedName.validate
1412
1916
  });
1413
1917
  const widgetType = await (0, prompts_namespaceObject.select)({
1414
1918
  choices: [
@@ -1418,11 +1922,16 @@ const scaffoldReactWidget = async (presentationReactFolder)=>{
1418
1922
  ],
1419
1923
  message: 'Type: '
1420
1924
  });
1421
- const { ClassName, fileName } = new UnknownFormatNaming(widgetName);
1925
+ const { folders, ClassName, fileName, classNameSegments } = new NestedName(widgetName);
1422
1926
  const folder = presentationReactFolder.subitem([
1423
1927
  'widgets',
1928
+ ...folders,
1424
1929
  fileName
1425
1930
  ]);
1931
+ const storyTitle = [
1932
+ 'Widgets',
1933
+ ...classNameSegments
1934
+ ].join('/');
1426
1935
  const widgetFileName = `${fileName}-widget`;
1427
1936
  const uiFileName = `${fileName}-widget-ui`;
1428
1937
  const uiModelFileName = `use-${fileName}-ui-model`;
@@ -1477,7 +1986,7 @@ import type { Meta, StoryObj } from '${storybookFramework}'
1477
1986
  import { ${ClassName}WidgetUI } from './${uiFileName}'
1478
1987
 
1479
1988
  const meta = {
1480
- title: 'Widgets/${ClassName}',
1989
+ title: '${storyTitle}',
1481
1990
  component: ${ClassName}WidgetUI
1482
1991
  } satisfies Meta<typeof ${ClassName}WidgetUI>
1483
1992
 
@@ -1615,9 +2124,11 @@ const main = async ()=>{
1615
2124
  'Domain',
1616
2125
  'Application',
1617
2126
  'Infrastructure',
1618
- 'Presentation'
1619
- ]
2127
+ 'Presentation',
2128
+ ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? 'Wire dependency' : void 0
2129
+ ].filter((x)=>!!x)
1620
2130
  });
2131
+ if ('Wire dependency' === layer) return void await wireDependency(boundedContextFolder);
1621
2132
  if ('Domain' === layer) {
1622
2133
  const operation = await (0, prompts_namespaceObject.select)({
1623
2134
  message: 'Domain layer operation:',