@domain-first/project-structure 8.7.0 → 8.8.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.
Files changed (33) hide show
  1. package/README.md +2 -0
  2. package/dist/287.js +1275 -1127
  3. package/dist/561.js +19 -3
  4. package/dist/780.js +9 -2
  5. package/dist/agent-cli.d.ts +35 -4
  6. package/dist/agent-requests.d.ts +22 -0
  7. package/dist/backend-module-move.d.ts +16 -0
  8. package/dist/config-file.d.ts +38 -18
  9. package/dist/graph.cjs +9 -2
  10. package/dist/implementation-options-schema.d.ts +19 -9
  11. package/dist/in-memory-db.d.ts +5 -6
  12. package/dist/index.cjs +1635 -1464
  13. package/dist/init.cjs +53 -59
  14. package/dist/integration-tests.d.ts +39 -0
  15. package/dist/integration-tests.spec.d.ts +1 -0
  16. package/dist/integration.cjs +1635 -1464
  17. package/dist/lint.cjs +9 -2
  18. package/dist/react.cjs +1635 -1464
  19. package/dist/upgrade-steps.d.ts +19 -4
  20. package/dist/upgrade.cjs +9 -2
  21. package/dist/use-cases/prompt-implementation-type.d.ts +2 -0
  22. package/package.json +1 -1
  23. package/skills/df-ps-implement/SKILL.md +2 -1
  24. package/skills/df-ps-scaffold/SKILL.md +2 -1
  25. package/skills/df-ps-scaffold/references/agent-mode.md +1 -1
  26. package/skills/df-ps-scaffold/references/agent-operations.md +2 -2
  27. package/skills/df-ps-scaffold/references/generators.md +31 -7
  28. package/skills/df-ps-scaffold/references/units/aggregate.md +3 -2
  29. package/skills/df-ps-scaffold/references/units/command-query.md +3 -2
  30. package/skills/df-ps-scaffold/references/units/helper.md +1 -1
  31. package/skills/df-ps-scaffold/references/units/implementation.md +1 -1
  32. package/skills/df-ps-scaffold/references/units/port.md +2 -1
  33. package/skills/df-ps-scaffold/references/units/services.md +4 -3
package/dist/index.cjs CHANGED
@@ -86,10 +86,17 @@ const implementationKinds = [
86
86
  'ports'
87
87
  ];
88
88
  const implementationLabelSchema = external_zod_default().string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/);
89
- const implementationOptionsSchema = external_zod_default().partialRecord(external_zod_default()["enum"](implementationKinds), external_zod_default().object({
89
+ const implementationGroupSchema = external_zod_default().object({
90
90
  primary: external_zod_default().array(implementationLabelSchema).default([]),
91
91
  test: external_zod_default().array(implementationLabelSchema).default([])
92
- }).strict());
92
+ }).strict();
93
+ const implementationOptionsSchema = external_zod_default().object({
94
+ ...Object.fromEntries(implementationKinds.map((kind)=>[
95
+ kind,
96
+ implementationGroupSchema.optional()
97
+ ])),
98
+ integrationTests: external_zod_default().array(implementationLabelSchema).optional()
99
+ }).strict();
93
100
  const moduleKinds = [
94
101
  'repositories',
95
102
  'domain-services',
@@ -1023,23 +1030,6 @@ export const wireInMemoryDbInfrastructureService = wireClass(
1023
1030
  []
1024
1031
  );
1025
1032
  `;
1026
- const inMemoryDbSpec = (testingLibrary, withWiring)=>`
1027
- import { describe, test, expect, beforeEach } from '${testingLibrary}'
1028
- ${withWiring ? `import { type InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'
1029
- import { wireInMemoryDbInfrastructureService } from '../../wiring/infrastructure-services/wire-in-memory-db-infrastructure-service'` : "import { InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'"}
1030
-
1031
- let inMemoryDbInfrastructureService: InMemoryDbInfrastructureService
1032
-
1033
- beforeEach(() => {
1034
- inMemoryDbInfrastructureService = ${withWiring ? 'wireInMemoryDbInfrastructureService()' : 'new InMemoryDbInfrastructureService()'}
1035
- })
1036
-
1037
- describe('in memory db', () => {
1038
- test('can be ${withWiring ? 'wired' : 'created'}', () => {
1039
- expect(inMemoryDbInfrastructureService).toBeDefined()
1040
- })
1041
- })
1042
- `.trim();
1043
1033
  const in_memory_db_withWiring = ()=>config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
1044
1034
  const in_memory_db_sharedFolder = ()=>new file_system_Folder(new project_root_ProjectRoot().path).subitem([
1045
1035
  config_file_ConfigFile.Instance.data.project.rootFolder,
@@ -1056,13 +1046,11 @@ const in_memory_db_wireFile = ()=>new file_system_File(in_memory_db_sharedFolder
1056
1046
  'wire-in-memory-db-infrastructure-service.ts'
1057
1047
  ]);
1058
1048
  const in_memory_db_scaffoldInMemoryDb = (shared)=>{
1059
- const { testingLibrary } = config_file_ConfigFile.backend;
1060
1049
  const servicesFolder = shared.subitem([
1061
1050
  'infrastructure',
1062
1051
  'services'
1063
1052
  ]);
1064
1053
  servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
1065
- if (testingLibrary) servicesFolder.createFile('in-memory-db-infrastructure-service.spec.ts', inMemoryDbSpec(testingLibrary, in_memory_db_withWiring()));
1066
1054
  if (in_memory_db_withWiring()) shared.subitem([
1067
1055
  'wiring',
1068
1056
  'infrastructure-services'
@@ -1124,9 +1112,6 @@ const wireInMemoryDb = (consumerWireFile, implementationName)=>{
1124
1112
  in_memory_db_wireName
1125
1113
  ]));
1126
1114
  };
1127
- const passInMemoryDb = (specFile, implementationName)=>{
1128
- specFile.update(addImport(specFile.data, `import { ${in_memory_db_className} } from '${relativeImport(specFile.path, serviceFile().path)}'`).replace(`new ${implementationName}()`, `new ${implementationName}(new ${in_memory_db_className}())`));
1129
- };
1130
1115
  const addInMemoryDb = ()=>{
1131
1116
  const config = config_file_ConfigFile.Instance.data;
1132
1117
  if (!config_file_ConfigFile.backend.withInMemoryDb) config_file_ConfigFile.update({
@@ -2635,1385 +2620,1610 @@ const storybook_addStorybook = async ()=>{
2635
2620
  })
2636
2621
  ];
2637
2622
  };
2638
- const wire_branches_defaultEnvBranches = {
2639
- names: [
2640
- 'test',
2641
- 'development',
2642
- 'production'
2643
- ],
2644
- test: 'test'
2645
- };
2646
- const wire_branches_envBranches = ()=>{
2647
- const configured = config_file_ConfigFile.exists ? config_file_ConfigFile.Instance.data.backend?.envBranches : void 0;
2648
- const { names, test } = configured ?? wire_branches_defaultEnvBranches;
2649
- return {
2650
- names,
2651
- test,
2652
- primary: names.filter((name)=>name !== test),
2653
- custom: Boolean(configured)
2654
- };
2623
+ const ignoredFolders = new Set([
2624
+ 'node_modules',
2625
+ '.git',
2626
+ '.next',
2627
+ 'dist',
2628
+ 'build',
2629
+ 'out',
2630
+ 'coverage',
2631
+ 'storybook-static'
2632
+ ]);
2633
+ const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
2634
+ const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2635
+ const module_move_walk = (folder)=>{
2636
+ if (!external_node_fs_default().existsSync(folder)) return [];
2637
+ return external_node_fs_default().readdirSync(folder, {
2638
+ withFileTypes: true
2639
+ }).flatMap((entry)=>{
2640
+ const entryPath = external_node_path_default().join(folder, entry.name);
2641
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : module_move_walk(entryPath);
2642
+ return entry.isFile() ? [
2643
+ entryPath
2644
+ ] : [];
2645
+ });
2655
2646
  };
2656
- const offersTestImplementation = ()=>{
2657
- const backend = config_file_ConfigFile.exists ? config_file_ConfigFile.Instance.data.backend : void 0;
2658
- return !(backend?.domainFirstPackages.includes('@domain-first/wire') && backend.envBranches && void 0 === backend.envBranches.test);
2647
+ const toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
2648
+ const readAliases = (projectRoot)=>{
2649
+ const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
2650
+ if (!external_node_fs_default().existsSync(tsconfig)) return [];
2651
+ try {
2652
+ const { compilerOptions = {} } = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(tsconfig, 'utf8')));
2653
+ const base = external_node_path_default().resolve(projectRoot, compilerOptions.baseUrl ?? '.');
2654
+ return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
2655
+ prefix: pattern.slice(0, -1),
2656
+ target: external_node_path_default().resolve(base, target.slice(0, -1))
2657
+ }));
2658
+ } catch {
2659
+ return [];
2660
+ }
2659
2661
  };
2660
- const envBranchedWireArgument = (testWire, primaryWire)=>{
2661
- const { test, primary } = wire_branches_envBranches();
2662
- return `{\n${[
2663
- ...test ? [
2664
- ` ${test}: ${testWire}`
2665
- ] : [],
2666
- ...primary.map((name)=>` ${name}: ${primaryWire}`)
2667
- ].join(',\n')}\n}`;
2662
+ const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
2663
+ const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
2664
+ const importPaths = (file)=>{
2665
+ const withoutExtension = file.replace(codeExtension, '');
2666
+ return 'index' === external_node_path_default().basename(withoutExtension) ? [
2667
+ withoutExtension,
2668
+ external_node_path_default().dirname(withoutExtension)
2669
+ ] : [
2670
+ withoutExtension
2671
+ ];
2668
2672
  };
2669
- const integrationFolder = 'specs/integration';
2670
- const testcontainersScripts = {
2671
- 'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
2673
+ const projectImports = (projectRoot)=>{
2674
+ const aliases = readAliases(projectRoot);
2675
+ const resolve = (specifier, fromFile)=>{
2676
+ if (specifier.startsWith('.')) return {
2677
+ resolved: external_node_path_default().resolve(external_node_path_default().dirname(fromFile), specifier),
2678
+ alias: void 0
2679
+ };
2680
+ const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
2681
+ return alias ? {
2682
+ resolved: external_node_path_default().resolve(alias.target, specifier.slice(alias.prefix.length)),
2683
+ alias
2684
+ } : void 0;
2685
+ };
2686
+ const specifierFor = (fromFile, toPath, alias)=>{
2687
+ const aliased = alias && toPosix(external_node_path_default().relative(alias.target, toPath));
2688
+ if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
2689
+ const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
2690
+ return relative.startsWith('.') ? relative : `./${relative}`;
2691
+ };
2692
+ const codeFiles = new Map(module_move_walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
2693
+ file,
2694
+ external_node_fs_default().readFileSync(file, 'utf8')
2695
+ ]));
2696
+ const importsOf = (file)=>[
2697
+ ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
2698
+ ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
2699
+ return {
2700
+ resolve,
2701
+ specifierFor,
2702
+ codeFiles,
2703
+ importsOf
2704
+ };
2672
2705
  };
2673
- const testcontainersVitestConfig = (inlineHandlersNext)=>{
2674
- const server = inlineHandlersNext ? `,
2675
- server: {
2676
- deps: {
2677
- // Imports \`next/headers\` without an extension, which only a bundler can resolve
2678
- inline: ['@domain-first/handlers-next']
2706
+ const stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content, stopAtFor })=>{
2707
+ const stopFor = (file)=>stopAtFor?.(file) ?? stopAt;
2708
+ const { resolve, specifierFor, codeFiles } = projectImports(projectRoot);
2709
+ const barrels = new Set();
2710
+ const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
2711
+ for(let found = true; found;){
2712
+ found = false;
2713
+ for (const [file, content] of codeFiles){
2714
+ if (moves.has(file) || isBarrel(file)) continue;
2715
+ const reExportsModule = [
2716
+ ...content.matchAll(reExportPattern)
2717
+ ].some(([, , specifier])=>{
2718
+ const resolution = resolve(specifier, file);
2719
+ return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
2720
+ });
2721
+ if (reExportsModule) {
2722
+ for (const importPath of importPaths(file))barrels.add(importPath);
2723
+ found = true;
2679
2724
  }
2680
- }` : '';
2681
- return `import { fileURLToPath } from 'node:url';
2682
- import { defineConfig } from 'vitest/config';
2683
-
2684
- // Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
2685
- export default defineConfig({
2686
- // Paths below are relative to the project root, not this folder
2687
- root: fileURLToPath(new URL('../..', import.meta.url)),
2688
- resolve: {
2689
- tsconfigPaths: true
2690
- },
2691
- test: {
2692
- include: ['${integrationFolder}/**/*.spec.ts'],
2693
- // Development implementations work with the real database
2694
- env: { NODE_ENV: 'development' },
2695
- globalSetup: ['${integrationFolder}/global-setup.ts'],
2696
- setupFiles: ['${integrationFolder}/setup-env.ts'],
2697
- // Pulling the image on the first run takes a while
2698
- hookTimeout: 120_000${server}
2725
+ }
2699
2726
  }
2700
- });
2701
- `;
2702
- };
2703
- const testcontainersGlobalSetup = (migrationCommand)=>{
2704
- const migrations = migrationCommand ? `
2705
- // dotenv in the Prisma config does not override an already set variable
2706
- execSync(${JSON.stringify(migrationCommand)}, {
2707
- cwd: project.config.root,
2708
- env: { ...process.env, DATABASE_URL: databaseUrl },
2709
- // On failure the error carries the command's output
2710
- stdio: 'pipe'
2711
- });
2712
- ` : `
2713
- // Apply your migrations to databaseUrl here.
2714
- `;
2715
- return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
2716
- import type { TestProject } from 'vitest/node';
2717
-
2718
- declare module 'vitest' {
2719
- export interface ProvidedContext {
2720
- databaseUrl: string;
2727
+ const rewrite = (content, oldFile, newFile)=>{
2728
+ let referencesModule = false;
2729
+ const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
2730
+ const resolution = resolve(specifier, oldFile);
2731
+ if (!resolution) return match;
2732
+ const moved = movedPath(resolution.resolved);
2733
+ if (moved || isBarrel(resolution.resolved)) referencesModule = true;
2734
+ if (!moved && oldFile === newFile) return match;
2735
+ const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
2736
+ return `${keyword}${quote}${next}${quote}`;
2737
+ });
2738
+ const changed = everyFile(rewritten);
2739
+ if (!referencesModule && !moves.has(oldFile)) return changed;
2740
+ return rename(changed, {
2741
+ moved: moves.has(oldFile)
2742
+ });
2743
+ };
2744
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new file_system_File(file).moveTo(newFile, stopFor(file));
2745
+ const updated = [];
2746
+ for (const [file, content] of codeFiles){
2747
+ const newFile = moves.get(file);
2748
+ const next = rewrite(content, file, newFile ?? file);
2749
+ if (newFile && newFile !== file) {
2750
+ new file_system_File(newFile).data = next;
2751
+ new file_system_File(file).delete(stopFor(file));
2752
+ } else if (next !== content) {
2753
+ new file_system_File(file).update(next);
2754
+ if (!newFile) updated.push(file);
2755
+ }
2721
2756
  }
2722
- }
2723
-
2724
- const POSTGRES_IMAGE = 'postgres:15';
2725
- const POSTGRES_PORT = 5432;
2726
- const POSTGRES_USER = 'test';
2727
- const POSTGRES_PASSWORD = 'test';
2728
- const POSTGRES_DB = 'test';
2729
-
2730
- export default async function setup(project: TestProject) {
2731
- const container = await new GenericContainer(POSTGRES_IMAGE)
2732
- .withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
2733
- .withExposedPorts(POSTGRES_PORT)
2734
- // During init PostgreSQL listens on a unix socket only and restarts,
2735
- // so checking over TCP passes once the final server is up
2736
- .withHealthCheck({
2737
- test: [
2738
- 'CMD-SHELL',
2739
- \`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
2740
- ],
2741
- interval: 250,
2742
- timeout: 1000,
2743
- retries: 1000
2744
- })
2745
- .withWaitStrategy(Wait.forHealthCheck())
2746
- .withStartupTimeout(120_000)
2747
- .start();
2748
-
2749
- const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
2750
- ${migrations}
2751
- project.provide('databaseUrl', databaseUrl);
2752
-
2753
- return async () => {
2754
- await container.stop();
2757
+ return {
2758
+ moves: [
2759
+ ...moves
2760
+ ].filter(([from, to])=>from !== to),
2761
+ updated
2755
2762
  };
2756
- }
2757
- `;
2758
- };
2759
- const testcontainersSetupEnv = `import 'dotenv/config';
2760
- import { inject } from 'vitest';
2761
-
2762
- // Runs before each spec's imports: development implementations get the .env
2763
- // config, and DATABASE_URL points to the container instead of the one from .env.
2764
- if (process.env.NODE_ENV !== 'development') {
2765
- throw new Error(
2766
- \`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
2767
- );
2768
- }
2769
-
2770
- process.env.DATABASE_URL = inject('databaseUrl');
2771
- `;
2772
- const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
2773
-
2774
- test('connects to the database in the container', () => {
2775
- expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
2776
- });
2777
- `;
2778
- const excludeFromUnitTests = (content)=>{
2779
- const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
2780
- if (!exclude.test(content)) return;
2781
- const entry = `'${integrationFolder}/**'`;
2782
- return content.replace(exclude, (_, items, comma, whitespace)=>{
2783
- const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
2784
- const separator = void 0 === indent ? ', ' : `,\n${indent}`;
2785
- return `${items}${separator}${entry}${comma}${whitespace}]`;
2786
- }).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
2787
- };
2788
- const testcontainers_stageFile = (filePath, content)=>{
2789
- const file = new file_system_File(filePath);
2790
- if (!file.exists || file.data !== content) file.data = content;
2791
2763
  };
2792
- const addTestcontainers = async ()=>{
2793
- const config = config_file_ConfigFile.Instance.data;
2794
- const root = new project_root_ProjectRoot().path;
2795
- const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
2796
- const manifest = JSON.parse(manifestFile.data);
2797
- const dependencies = {
2798
- ...manifest.dependencies,
2799
- ...manifest.devDependencies
2764
+ const serviceLayout = (layer)=>({
2765
+ title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
2766
+ core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
2767
+ files: ({ name })=>[
2768
+ `${layer}/services/${name}-${layer}-service.ts`,
2769
+ `${layer}/services/${name}-${layer}-service.spec.ts`,
2770
+ `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
2771
+ ],
2772
+ wired: true,
2773
+ sharedKernel: true
2774
+ });
2775
+ const handlerLayout = (kind)=>{
2776
+ const folder = 'command' === kind ? 'commands' : 'queries';
2777
+ const Suffix = 'command' === kind ? 'Command' : 'Query';
2778
+ return {
2779
+ title: 'command' === kind ? 'Commands' : 'Queries',
2780
+ core: (ClassName)=>`${ClassName}${Suffix}`,
2781
+ files: ({ name }, labels)=>[
2782
+ `application/${folder}/${name}-${kind}.ts`,
2783
+ `application/${folder}/${name}-${kind}.spec.ts`,
2784
+ ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
2785
+ `wiring/${folder}/wire-${name}-${kind}.ts`
2786
+ ],
2787
+ implementations: `infrastructure/${folder}`,
2788
+ wired: true,
2789
+ sharedKernel: false
2800
2790
  };
2801
- const selected = await addPackageScripts(manifestFile, testcontainersScripts);
2802
- const withPrisma = new file_system_File(external_node_path_default().resolve(root, config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
2803
- const migrationCommand = withPrisma ? `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
2804
- const folder = external_node_path_default().join(root, integrationFolder);
2805
- testcontainers_stageFile(external_node_path_default().join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
2806
- testcontainers_stageFile(external_node_path_default().join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
2807
- testcontainers_stageFile(external_node_path_default().join(folder, 'setup-env.ts'), testcontainersSetupEnv);
2808
- const example = new file_system_File(external_node_path_default().join(folder, 'database/database.spec.ts'));
2809
- if (!example.exists) example.data = testcontainers_exampleSpec;
2810
- const unitConfig = new file_system_File(external_node_path_default().join(root, 'vitest.config.ts'));
2811
- let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
2812
- if (!excludedFromUnitTests) {
2813
- const excluded = excludeFromUnitTests(unitConfig.data);
2814
- if (excluded) {
2815
- unitConfig.update(excluded);
2816
- excludedFromUnitTests = true;
2817
- }
2818
- }
2819
- const missing = [
2820
- 'vitest',
2821
- 'testcontainers',
2822
- 'dotenv'
2823
- ].filter((name)=>!dependencies[name]);
2824
- return [
2825
- ...missing.length ? [
2826
- `npm install --save-dev ${missing.join(' ')}`
2827
- ] : [],
2828
- `Integration specs run against postgres:15 and get its address in DATABASE_URL. Change the image, credentials and connection string in ${integrationFolder}/global-setup.ts, and the variable name in ${integrationFolder}/setup-env.ts.`,
2829
- ...migrationCommand ? [] : [
2830
- `Apply your migrations in ${integrationFolder}/global-setup.ts.`
2831
- ],
2832
- ...excludedFromUnitTests ? [] : [
2833
- `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
2834
- ],
2835
- ...wire_branches_envBranches().custom ? [
2836
- `${integrationFolder} runs with NODE_ENV=development and ${integrationFolder}/setup-env.ts requires it, but your envBranchedWire branches are custom: make currentBranch in shared-kernel/wiring/env-branched-wire.ts return the branch for integration specs, and adjust setup-env.ts.`
2837
- ] : [],
2838
- 'Docker must be running for integration specs.',
2839
- ...describeScripts(selected, {
2840
- 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
2841
- })
2842
- ];
2843
2791
  };
2844
- const vitestScripts = {
2845
- test: 'vitest run --reporter=dot --silent=passed-only',
2846
- 'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
2792
+ const domainModelLayout = (kind)=>{
2793
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
2794
+ return {
2795
+ title: 'entity' === kind ? 'Entities' : 'Value objects',
2796
+ core: (ClassName)=>ClassName,
2797
+ files: ({ name, aggregate })=>{
2798
+ const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
2799
+ return [
2800
+ `${base}/${name}.${kind}.ts`,
2801
+ `${base}/${name}.${kind}.spec.ts`
2802
+ ];
2803
+ },
2804
+ wired: false,
2805
+ sharedKernel: true
2806
+ };
2847
2807
  };
2848
- const vitestConfig = (rootFolder, inlineHandlersNext)=>{
2849
- const folder = (subpath)=>JSON.stringify(external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), subpath));
2850
- const server = inlineHandlersNext ? `,
2851
- server: {
2852
- deps: {
2853
- // Imports \`next/headers\` without an extension, which only a bundler can resolve
2854
- inline: ['@domain-first/handlers-next']
2855
- }
2856
- }` : '';
2857
- return `import { configDefaults, defineConfig } from 'vitest/config';
2858
-
2859
- export default defineConfig({
2860
- resolve: {
2861
- tsconfigPaths: true
2808
+ const aggregateOwnFiles = (name)=>[
2809
+ `${name}.aggregate-root.ts`,
2810
+ `${name}.aggregate-root.spec.ts`,
2811
+ `${name}-repository.ts`,
2812
+ `${name}-repository.spec.ts`,
2813
+ 'index.ts'
2814
+ ];
2815
+ const kindLayouts = {
2816
+ aggregate: {
2817
+ title: 'Aggregates',
2818
+ core: (ClassName)=>`${ClassName}Repository`,
2819
+ files: ({ name }, labels)=>[
2820
+ ...aggregateOwnFiles(name).map((file)=>`domain/aggregates/${name}/${file}`),
2821
+ ...labels.map((label)=>`infrastructure/repositories/${label}/${label}-${name}-repository.ts`),
2822
+ `wiring/repositories/wire-${name}-repository.ts`
2823
+ ],
2824
+ implementations: 'infrastructure/repositories',
2825
+ wired: true,
2826
+ sharedKernel: false
2862
2827
  },
2863
- test: {
2864
- // Playwright runs end-to-end specs, test:integration runs integration ones
2865
- exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
2866
- coverage: {
2867
- provider: 'v8',
2868
- include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
2869
- exclude: [
2870
- '**/*.spec.ts',
2871
- ${folder('shared-kernel/infrastructure/**')},
2872
- ${folder('bounded-contexts/*/infrastructure/**')},
2873
- ${folder('bounded-contexts/*/presentation/rest/**')},
2874
- ${folder('shared-kernel/wiring/**')},
2875
- ${folder('bounded-contexts/*/wiring/**')}
2828
+ entity: domainModelLayout('entity'),
2829
+ 'value-object': domainModelLayout('value-object'),
2830
+ 'domain-service': serviceLayout('domain'),
2831
+ 'application-service': serviceLayout('application'),
2832
+ 'infrastructure-service': serviceLayout('infrastructure'),
2833
+ 'presentation-service': serviceLayout('presentation'),
2834
+ 'use-case': {
2835
+ title: 'Use cases',
2836
+ core: (ClassName)=>`${ClassName}UseCase`,
2837
+ files: ({ name })=>[
2838
+ `application/use-cases/${name}-use-case.ts`,
2839
+ `application/use-cases/${name}-use-case.spec.ts`,
2840
+ `wiring/use-cases/wire-${name}-use-case.ts`
2876
2841
  ],
2877
- reporter: [['text', { skipFull: true }], 'html']
2878
- }${server}
2842
+ wired: true,
2843
+ sharedKernel: false
2844
+ },
2845
+ command: handlerLayout('command'),
2846
+ query: handlerLayout('query'),
2847
+ port: {
2848
+ title: 'Ports',
2849
+ core: (ClassName)=>ClassName,
2850
+ files: ({ name }, labels)=>[
2851
+ `application/ports/${name}.ts`,
2852
+ `application/ports/${name}.spec.ts`,
2853
+ ...labels.map((label)=>`infrastructure/application-adapters/${label}/${label}-${name}.ts`),
2854
+ `wiring/application-ports/wire-${name}.ts`
2855
+ ],
2856
+ implementations: 'infrastructure/application-adapters',
2857
+ wired: true,
2858
+ sharedKernel: true
2879
2859
  }
2880
- });
2881
- `;
2882
2860
  };
2883
- const addVitest = async ()=>{
2884
- const config = config_file_ConfigFile.Instance.data;
2885
- if (config_file_ConfigFile.backend.testingLibrary && 'vitest' !== config_file_ConfigFile.backend.testingLibrary && !await interaction_confirm({
2886
- key: 'replaceTestingLibrary',
2887
- requestRequired: true,
2888
- message: `Replace testing library "${config_file_ConfigFile.backend.testingLibrary}" with vitest for generated tests?`,
2889
- default: false
2890
- })) return [];
2891
- const root = new project_root_ProjectRoot().path;
2892
- const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
2893
- const manifest = JSON.parse(manifestFile.data);
2894
- const dependencies = {
2895
- ...manifest.dependencies,
2896
- ...manifest.devDependencies
2861
+ const integrationSpecsFolder = 'specs/integration';
2862
+ const projectRootOf = (folder)=>{
2863
+ let current = folder;
2864
+ while(true){
2865
+ if (external_node_fs_default().existsSync(external_node_path_default().join(current, 'package.json'))) return current;
2866
+ const parent = external_node_path_default().dirname(current);
2867
+ if (parent === current) return;
2868
+ current = parent;
2869
+ }
2870
+ };
2871
+ const integrationSpecFile = (unit, label)=>{
2872
+ const layout = kindLayouts[unit.kind];
2873
+ const place = {
2874
+ ownerPath: unit.ownerPath,
2875
+ name: unit.name
2897
2876
  };
2898
- const selected = await addPackageScripts(manifestFile, vitestScripts);
2899
- const configFile = new file_system_File(external_node_path_default().join(root, 'vitest.config.ts'));
2900
- const content = vitestConfig(config.project.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
2901
- if (!configFile.exists || configFile.data !== content) configFile.data = content;
2902
- if ('vitest' !== config_file_ConfigFile.backend.testingLibrary) config_file_ConfigFile.update({
2903
- backend: {
2904
- ...config_file_ConfigFile.backend,
2905
- testingLibrary: 'vitest'
2906
- }
2907
- });
2908
- addGitignoreEntry(root, '/coverage/');
2909
- const missing = [
2910
- 'vitest',
2911
- '@vitest/coverage-v8'
2912
- ].filter((name)=>!dependencies[name]);
2913
- return [
2914
- ...missing.length ? [
2915
- `npm install --save-dev ${missing.join(' ')}`
2916
- ] : [],
2917
- ...describeScripts(selected, {
2918
- test: 'run unit tests',
2919
- 'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
2920
- })
2921
- ];
2877
+ const source = void 0 === label ? 'infrastructure-service' === unit.kind ? layout.files(place, [])[0] : void 0 : layout.implementations ? layout.files(place, [
2878
+ label
2879
+ ]).find((file)=>file.startsWith(`${layout.implementations}/${label}/`)) : void 0;
2880
+ const projectRoot = projectRootOf(unit.ownerPath);
2881
+ if (!source || !projectRoot) return;
2882
+ return external_node_path_default().join(projectRoot, integrationSpecsFolder, external_node_path_default().basename(unit.ownerPath), source.slice(15).replace(/\.ts$/, '.spec.ts'));
2883
+ };
2884
+ const integrationSpecSubjects = (unit)=>'infrastructure-service' === unit.kind ? [
2885
+ void 0
2886
+ ] : unit.labels;
2887
+ const integrationSpecsStop = (file)=>{
2888
+ const projectRoot = projectRootOf(external_node_path_default().dirname(file));
2889
+ if (!projectRoot) return;
2890
+ const folder = external_node_path_default().join(projectRoot, integrationSpecsFolder);
2891
+ return file.startsWith(`${folder}${external_node_path_default().sep}`) ? folder : void 0;
2922
2892
  };
2923
- const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
2924
- const mergeInstallCommands = (commands)=>{
2925
- const runtime = new Set();
2926
- const development = new Set();
2927
- const rest = [];
2928
- for (const command of commands){
2929
- const match = installCommand.exec(command);
2930
- if (!match) {
2931
- rest.push(command);
2932
- continue;
2933
- }
2934
- for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
2935
- }
2936
- const devOnly = [
2937
- ...development
2938
- ].filter((name)=>!runtime.has(name));
2893
+ const subfolders = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
2894
+ withFileTypes: true
2895
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
2896
+ const namesBySuffix = (folder, suffix)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder).filter((file)=>file.endsWith(suffix) && !file.endsWith('.spec.ts')).map((file)=>file.slice(0, -suffix.length)).sort() : [];
2897
+ const labelsOf = (ownerPath, kind, name)=>{
2898
+ const { implementations } = kindLayouts[kind];
2899
+ if (!implementations) return [];
2900
+ return subfolders(external_node_path_default().join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
2901
+ ownerPath,
2902
+ name
2903
+ }, [
2904
+ label
2905
+ ]).some((file)=>file.startsWith(`${implementations}/`) && external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, file))));
2906
+ };
2907
+ const aggregatesOf = (ownerPath)=>subfolders(external_node_path_default().join(ownerPath, 'domain/aggregates')).filter((name)=>external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, 'domain/aggregates', name, `${name}.aggregate-root.ts`)));
2908
+ const findBackendUnits = (ownerPath)=>{
2909
+ const unit = (kind, name, aggregate)=>({
2910
+ kind,
2911
+ name,
2912
+ ownerPath,
2913
+ aggregate,
2914
+ labels: labelsOf(ownerPath, kind, name)
2915
+ });
2916
+ const aggregates = aggregatesOf(ownerPath);
2917
+ const inAggregates = (kind)=>aggregates.flatMap((aggregate)=>namesBySuffix(external_node_path_default().join(ownerPath, 'domain/aggregates', aggregate, 'entity' === kind ? 'entities' : 'value-objects'), `.${kind}.ts`).map((name)=>unit(kind, name, aggregate)));
2918
+ const at = (folder, suffix, kind)=>namesBySuffix(external_node_path_default().join(ownerPath, folder), suffix).map((name)=>unit(kind, name));
2939
2919
  return [
2940
- ...runtime.size ? [
2941
- `npm install ${[
2942
- ...runtime
2943
- ].join(' ')}`
2944
- ] : [],
2945
- ...devOnly.length ? [
2946
- `npm install --save-dev ${devOnly.join(' ')}`
2947
- ] : [],
2948
- ...rest
2920
+ ...aggregates.map((name)=>unit('aggregate', name)),
2921
+ ...inAggregates('entity'),
2922
+ ...at('domain/entities', '.entity.ts', 'entity'),
2923
+ ...inAggregates('value-object'),
2924
+ ...at('domain/value-objects', '.value-object.ts', 'value-object'),
2925
+ ...at('domain/services', '-domain-service.ts', 'domain-service'),
2926
+ ...at('application/ports', '.ts', 'port'),
2927
+ ...at('application/queries', '-query.ts', 'query'),
2928
+ ...at('application/commands', '-command.ts', 'command'),
2929
+ ...at('application/use-cases', '-use-case.ts', 'use-case'),
2930
+ ...at('application/services', '-application-service.ts', 'application-service'),
2931
+ ...at('infrastructure/services', '-infrastructure-service.ts', 'infrastructure-service'),
2932
+ ...at('presentation/services', '-presentation-service.ts', 'presentation-service')
2949
2933
  ];
2950
2934
  };
2951
- const printNextSteps = (nextSteps)=>{
2952
- const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
2953
- const commands = mergeInstallCommands(nextSteps.filter(isCommand));
2954
- const notes = nextSteps.filter((line)=>!isCommand(line));
2955
- const sections = [];
2956
- if (commands.length) sections.push([
2957
- 'Run this command to install the required dependencies:',
2958
- (0, external_node_util_namespaceObject.styleText)([
2959
- 'bold',
2960
- 'cyan'
2961
- ], commands.join(' && '))
2962
- ].join('\n'));
2963
- if (notes.length) sections.push([
2964
- 'Additional information:',
2965
- ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + (0, external_node_util_namespaceObject.styleText)([
2966
- 'bold',
2967
- 'cyan'
2968
- ], path)))
2969
- ].join('\n'));
2970
- if (sections.length) console.log(sections.join('\n\n'));
2971
- };
2972
- const savePendingChanges = async ()=>{
2973
- assertAnswersConsumed();
2974
- const overwrittenFiles = filesToOverwrite({
2975
- changedOnly: isNonInteractive()
2976
- });
2977
- if (isNonInteractive() && overwrittenFiles.length && !answerFor('overwrite', false)) throw new RequestError('OVERWRITE_REQUIRED', 'Set overwrite to true to replace existing files.', {
2978
- files: overwrittenFiles.map((file)=>external_node_path_default().relative(new project_root_ProjectRoot().path, file).split(external_node_path_default().sep).join('/'))
2935
+ const kebabName = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
2936
+ const lowerFirst = (value)=>value[0].toLowerCase() + value.slice(1);
2937
+ const unitMoves = (unit, target)=>{
2938
+ const layout = kindLayouts[unit.kind];
2939
+ const from = layout.files(unit, unit.labels);
2940
+ const to = layout.files(target, unit.labels);
2941
+ const moves = new Map();
2942
+ from.forEach((file, index)=>{
2943
+ const oldPath = external_node_path_default().join(unit.ownerPath, file);
2944
+ if (external_node_fs_default().existsSync(oldPath)) moves.set(oldPath, external_node_path_default().join(target.ownerPath, to[index]));
2979
2945
  });
2980
- if (overwrittenFiles.length) {
2981
- const root = new project_root_ProjectRoot().path;
2982
- report('These files already exist and will be overwritten:');
2983
- for (const filePath of overwrittenFiles)report(` ${external_node_path_default().relative(root, filePath)}`);
2984
- const overwrite = await interaction_confirm({
2985
- key: 'overwrite',
2986
- message: 'Overwrite them?',
2987
- default: false
2988
- });
2989
- if (!overwrite) {
2990
- discardPendingChanges();
2991
- report('Cancelled: nothing was written.');
2992
- return false;
2993
- }
2946
+ for (const label of integrationSpecSubjects(unit)){
2947
+ const oldSpec = integrationSpecFile(unit, label);
2948
+ const newSpec = integrationSpecFile({
2949
+ kind: unit.kind,
2950
+ name: target.name,
2951
+ ownerPath: target.ownerPath
2952
+ }, label);
2953
+ if (oldSpec && newSpec && external_node_fs_default().existsSync(oldSpec)) moves.set(oldSpec, newSpec);
2994
2954
  }
2995
- writePendingChanges();
2955
+ if ('aggregate' === unit.kind) {
2956
+ const oldFolder = external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name);
2957
+ const newFolder = external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.name);
2958
+ const own = new Set(aggregateOwnFiles(unit.name).map((file)=>external_node_path_default().join(oldFolder, file)));
2959
+ for (const file of module_move_walk(oldFolder))if (!own.has(file)) moves.set(file, external_node_path_default().join(newFolder, external_node_path_default().relative(oldFolder, file)));
2960
+ }
2961
+ return moves;
2962
+ };
2963
+ const validateBackendMove = (unit, target, sharedKernelPath)=>{
2964
+ if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
2965
+ if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
2966
+ if (target.ownerPath === unit.ownerPath && target.name === unit.name && target.aggregate === unit.aggregate) return 'Nothing to change: enter a new name or pick another place';
2967
+ for (const [from, to] of unitMoves(unit, target))if (to !== from && external_node_fs_default().existsSync(to)) return `${external_node_path_default().relative(target.ownerPath, to)} already exists`;
2996
2968
  return true;
2997
2969
  };
2998
- const withHandlersRest = ()=>config_file_ConfigFile.Instance.data.backend?.domainFirstPackages.includes('@domain-first/handlers-rest') ?? false;
2999
- const created = (...segments)=>new file_system_File(external_node_path_default().join(new project_root_ProjectRoot().path, ...segments)).exists;
3000
- const createdInRoot = (...segments)=>created(config_file_ConfigFile.Instance.data.project.rootFolder, ...segments);
3001
- const integrationIds = [
3002
- 'storybook',
3003
- 'rest-endpoint-generator',
3004
- 'in-memory-db',
3005
- 'prisma',
3006
- 'vitest',
3007
- 'playwright',
3008
- 'testcontainers',
3009
- 'openapi',
3010
- 'orval'
3011
- ];
3012
- const integrations = [
3013
- {
3014
- id: 'storybook',
3015
- name: 'Storybook (React + Vite)',
3016
- group: 'frontend',
3017
- run: storybook_addStorybook,
3018
- applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
3019
- },
3020
- {
3021
- id: 'rest-endpoint-generator',
3022
- name: 'REST endpoint generator',
3023
- group: 'backend',
3024
- run: addRestEndpointGenerator,
3025
- available: ()=>withHandlersRest(),
3026
- applied: restEndpointGeneratorApplied
3027
- },
3028
- {
3029
- id: 'in-memory-db',
3030
- name: 'In-memory DB',
3031
- group: 'backend',
3032
- run: addInMemoryDb,
3033
- applied: inMemoryDbApplied
3034
- },
3035
- {
3036
- id: 'prisma',
3037
- name: 'Prisma 8 (PostgreSQL, RC)',
3038
- group: 'backend',
3039
- run: addPrisma,
3040
- applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
3041
- },
3042
- {
3043
- id: 'vitest',
3044
- name: 'Vitest',
3045
- group: 'backend',
3046
- run: addVitest,
3047
- applied: ()=>created('vitest.config.ts')
3048
- },
3049
- {
3050
- id: 'playwright',
3051
- name: 'Playwright',
3052
- group: 'frontend',
3053
- run: addPlaywright,
3054
- applied: ()=>created('playwright.config.ts')
3055
- },
3056
- {
3057
- id: 'testcontainers',
3058
- name: 'Integration tests (Testcontainers, PostgreSQL)',
3059
- group: 'backend',
3060
- run: addTestcontainers,
3061
- applied: ()=>created('specs/integration/vitest.config.ts')
3062
- },
3063
- {
3064
- id: 'openapi',
3065
- name: 'OpenAPI',
3066
- group: 'backend',
3067
- run: addOpenapi,
3068
- available: ()=>withHandlersRest(),
3069
- applied: ()=>created(openapiScriptPath)
3070
- },
3071
- {
3072
- id: 'orval',
3073
- name: 'Orval (API client)',
3074
- group: 'frontend',
3075
- run: addOrval,
3076
- available: ()=>withHandlersRest(),
3077
- applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
3078
- }
3079
- ];
3080
- const addIntegration = async ({ save = true } = {})=>{
3081
- const available = integrations.filter(({ group, available })=>('backend' !== group || Boolean(config_file_ConfigFile.Instance.data.backend)) && (available?.() ?? true)).map((value)=>({
3082
- value,
3083
- applied: value.applied()
3084
- }));
3085
- const section = (title, applied)=>{
3086
- const items = [
3087
- 'backend',
3088
- 'frontend'
3089
- ].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
3090
- return items.length ? [
3091
- new prompts_namespaceObject.Separator(title),
3092
- ...items.map(({ value })=>({
3093
- name: `${value.name} · ${value.group}`,
3094
- value
3095
- }))
3096
- ] : [];
2970
+ const ownerOf = (rootFolderPath, file)=>{
2971
+ const [area, context] = external_node_path_default().relative(rootFolderPath, file).split(external_node_path_default().sep);
2972
+ if ('bounded-contexts' === area && context) return {
2973
+ context,
2974
+ path: external_node_path_default().join(rootFolderPath, area, context)
2975
+ };
2976
+ if ('shared-kernel' === area) return {
2977
+ context: void 0,
2978
+ path: external_node_path_default().join(rootFolderPath, area)
3097
2979
  };
3098
- const choices = [
3099
- ...section('New integrations', false),
3100
- ...section('Already applied (select to reapply)', true)
3101
- ];
3102
- const selected = await interaction_checkbox({
3103
- key: 'integrations',
3104
- id: (integration)=>integration.id,
3105
- message: 'Integrations:',
3106
- choices,
3107
- pageSize: choices.length
3108
- });
3109
- const nextSteps = [];
3110
- for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
3111
- if (save && await savePendingChanges()) printNextSteps(nextSteps);
3112
- return nextSteps;
3113
2980
  };
3114
- const integrationDescriptions = ()=>integrations.map((integration)=>({
3115
- id: integration.id,
3116
- name: integration.name,
3117
- group: integration.group,
3118
- available: ('backend' !== integration.group || Boolean(config_file_ConfigFile.Instance.data.backend)) && (integration.available?.() ?? true)
3119
- }));
3120
- const agent_requests_name = implementationLabelSchema;
3121
- const agent_requests_nestedName = external_zod_default().string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*)*$/);
3122
- const agent_requests_id = external_zod_default().string().min(1);
3123
- const agent_requests_implementation = external_zod_default().strictObject({
3124
- type: agent_requests_name,
3125
- save: external_zod_default().boolean().optional().describe('Remember this ordinary type for future runs. Default: false.')
3126
- });
3127
- const agent_requests_dependencies = external_zod_default().record(external_zod_default().string().regex(/^[A-Z][A-Za-z0-9]*$/), external_zod_default().array(agent_requests_id)).describe('Implementation/class name -> exact module IDs from --describe. Omitted entries keep suggested dependencies; [] selects none.');
3128
- const common = {
3129
- overwrite: external_zod_default().boolean().optional(),
3130
- dryRun: external_zod_default().boolean().optional()
2981
+ const inMemoryDbFile = (rootFolderPath)=>external_node_path_default().join(rootFolderPath, 'shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts');
2982
+ const isolationAllows = (rootFolderPath, from, to)=>{
2983
+ const fromOwner = ownerOf(rootFolderPath, from);
2984
+ const toOwner = ownerOf(rootFolderPath, to);
2985
+ if (!fromOwner || !toOwner?.context) return true;
2986
+ if (fromOwner.context) return fromOwner.context === toOwner.context || true === crossContextImportAllowed(from, to);
2987
+ const inside = (folder)=>to === external_node_path_default().join(toOwner.path, folder) || to.startsWith(external_node_path_default().join(toOwner.path, folder) + external_node_path_default().sep);
2988
+ return inside('domain/errors') || from.replace(codeExtension, '') === inMemoryDbFile(rootFolderPath).replace(codeExtension, '') && inside('domain');
3131
2989
  };
3132
- const agent_requests_owner = {
3133
- context: agent_requests_name.describe('A bounded-context name, or shared-kernel.')
2990
+ const moveBackendUnit = (projectRoot, rootFolderPath, unit, target)=>{
2991
+ const layout = kindLayouts[unit.kind];
2992
+ const moves = unitMoves(unit, target);
2993
+ const withoutExtension = new Map([
2994
+ ...moves
2995
+ ].map(([from, to])=>[
2996
+ from.replace(codeExtension, ''),
2997
+ to.replace(codeExtension, '')
2998
+ ]));
2999
+ const folders = 'aggregate' === unit.kind ? [
3000
+ [
3001
+ external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name),
3002
+ external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.name)
3003
+ ]
3004
+ ] : [];
3005
+ const movedPath = (candidate)=>{
3006
+ const extension = candidate.match(codeExtension)?.[0];
3007
+ if (extension) return moves.get(candidate);
3008
+ return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
3009
+ };
3010
+ const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
3011
+ const oldNaming = new UnknownFormatNaming(unit.name);
3012
+ const newNaming = new UnknownFormatNaming(target.name);
3013
+ const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
3014
+ const oldAggregateFolder = unit.aggregate && external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
3015
+ const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === external_node_path_default().join(oldAggregateFolder, 'index'));
3016
+ const mainFile = [
3017
+ ...moves.keys()
3018
+ ][0];
3019
+ const newMainFile = moves.get(mainFile);
3020
+ const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
3021
+ const barrelImporters = leavesAggregate ? [
3022
+ ...codeFiles
3023
+ ].filter(([file, content])=>!moves.has(file) && [
3024
+ ...content.matchAll(namedImports)
3025
+ ].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
3026
+ const violations = [];
3027
+ const relative = (file)=>toPosix(external_node_path_default().relative(projectRoot, file));
3028
+ for (const file of codeFiles.keys()){
3029
+ const from = moves.get(file) ?? file;
3030
+ for (const imported of importsOf(file)){
3031
+ const to = movedPath(imported);
3032
+ if (moves.has(file) || to) {
3033
+ if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
3034
+ relative(from),
3035
+ relative(to ?? imported)
3036
+ ]);
3037
+ }
3038
+ }
3039
+ }
3040
+ for (const [file] of barrelImporters)if (!isolationAllows(rootFolderPath, file, newMainFile)) violations.push([
3041
+ relative(file),
3042
+ relative(newMainFile)
3043
+ ]);
3044
+ if (violations.length) return {
3045
+ violations
3046
+ };
3047
+ const word = (form)=>`(?<![\\w$])${escapeRegExp(form)}(?![\\w$])`;
3048
+ const oldCore = layout.core(oldNaming.ClassName);
3049
+ const newCore = layout.core(newNaming.ClassName);
3050
+ const labelNames = unit.labels.map((label)=>new UnknownFormatNaming(label).ClassName);
3051
+ const prefixes = [
3052
+ ...labelNames,
3053
+ ...layout.wired ? [
3054
+ 'wire',
3055
+ ...labelNames.map((label)=>`wire${label}`)
3056
+ ] : []
3057
+ ];
3058
+ const renames = [
3059
+ {
3060
+ pattern: new RegExp(`(?<![\\w$])(${prefixes.map(escapeRegExp).join('|')})?${escapeRegExp(oldCore)}(?![\\w$])`, 'g'),
3061
+ to: `$1${newCore}`
3062
+ },
3063
+ {
3064
+ pattern: new RegExp(word(lowerFirst(oldCore)), 'g'),
3065
+ to: lowerFirst(newCore)
3066
+ },
3067
+ {
3068
+ pattern: new RegExp(`(describe\\(\\s*['"\`])${escapeRegExp(oldNaming.withSpaces)}(?=[ '"\`])`, 'g'),
3069
+ to: `$1${newNaming.withSpaces}`,
3070
+ movedOnly: true
3071
+ }
3072
+ ];
3073
+ if ('aggregate' === unit.kind) renames.push({
3074
+ pattern: new RegExp(word(oldNaming.ClassName), 'g'),
3075
+ to: newNaming.ClassName
3076
+ }, {
3077
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
3078
+ to: newNaming.variableName,
3079
+ movedOnly: true
3080
+ });
3081
+ if ('entity' === unit.kind || 'value-object' === unit.kind) renames.push({
3082
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
3083
+ to: newNaming.variableName,
3084
+ movedOnly: true
3085
+ });
3086
+ const oldSection = new UnknownFormatNaming(plural(unit.name));
3087
+ const newSection = new UnknownFormatNaming(plural(target.name));
3088
+ const renamesSection = 'aggregate' === unit.kind && unit.name !== target.name;
3089
+ const everyFile = (content)=>renamesSection ? content.replace(new RegExp(`(InMemoryDbInfrastructureService\\[\\s*['"])${oldSection.variableName}(?=['"]\\s*\\])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(inMemoryDbInfrastructureService\\s*\\.\\s*)${oldSection.variableName}(?![\\w$])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(?<![\\w$.])${oldSection.variableName}(\\s*=\\s*this\\.section<[^>]*>\\(\\s*['"])${oldSection.fileName.toUpperCase()}(?=['"])`, 'g'), `${newSection.variableName}$1${newSection.fileName.toUpperCase()}`) : content;
3090
+ const plan = stageModuleMove({
3091
+ projectRoot,
3092
+ stopAt: rootFolderPath,
3093
+ stopAtFor: integrationSpecsStop,
3094
+ moves,
3095
+ movedPath,
3096
+ rename: (content, { moved })=>renames.reduce((result, { pattern, to, movedOnly })=>movedOnly && !moved ? result : result.replace(pattern, to), content),
3097
+ everyFile
3098
+ });
3099
+ if (leavesAggregate && oldAggregateFolder) {
3100
+ const indexFile = new file_system_File(external_node_path_default().join(oldAggregateFolder, 'index.ts'));
3101
+ const exportLine = /^export\s+\*\s+from\s+(['"])([^'"\n]+)\1;?\s*$/;
3102
+ indexFile.update(indexFile.data.split('\n').filter((line)=>{
3103
+ const specifier = line.match(exportLine)?.[2];
3104
+ return !specifier || external_node_path_default().resolve(external_node_path_default().dirname(indexFile.path), specifier) !== newMainFile.replace(codeExtension, '');
3105
+ }).join('\n'));
3106
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
3107
+ for (const [file] of barrelImporters){
3108
+ const importer = new file_system_File(file);
3109
+ let content = importer.data;
3110
+ for (const match of content.matchAll(namedImports)){
3111
+ const [statement, typeOnly = '', names, quote, specifier] = match;
3112
+ if (!isOldBarrel(resolve(specifier, file)?.resolved)) continue;
3113
+ const items = names.split(',').map((item)=>item.trim()).filter((item)=>!!item);
3114
+ const own = new RegExp(`^(?:type\\s+)?${newNaming.ClassName}(?:\\s+as\\s+[\\w$]+)?$`);
3115
+ const moved = items.filter((item)=>own.test(item));
3116
+ if (!moved.length) continue;
3117
+ const rest = items.filter((item)=>!own.test(item));
3118
+ const direct = `import ${typeOnly}{ ${moved.join(', ')} } from ${quote}${projectRelative(file, newMainFile)}${quote}`;
3119
+ content = content.replace(statement, rest.length ? `import ${typeOnly}{ ${rest.join(', ')} } from ${quote}${specifier}${quote}\n${direct}` : direct);
3120
+ }
3121
+ importer.update(content);
3122
+ }
3123
+ }
3124
+ if (target.aggregate && (target.aggregate !== unit.aggregate || target.ownerPath !== unit.ownerPath)) {
3125
+ const kindFolder = 'entity' === unit.kind ? 'entities' : 'value-objects';
3126
+ const indexFile = new file_system_File(external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.aggregate, 'index.ts'));
3127
+ indexFile.addLineIfMissing(`export * from './${kindFolder}/${target.name}.${unit.kind}'`);
3128
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
3129
+ }
3130
+ return plan;
3134
3131
  };
3135
- const agent_requests_wired = {
3136
- dependencies: agent_requests_dependencies.optional()
3132
+ const projectRelative = (fromFile, toFile)=>{
3133
+ const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile.replace(codeExtension, '')));
3134
+ return relative.startsWith('.') ? relative : `./${relative}`;
3137
3135
  };
3138
- const agent_requests_implementations = {
3139
- implementation: agent_requests_implementation,
3140
- testImplementation: agent_requests_implementation.optional(),
3141
- ...agent_requests_wired
3136
+ const importSpecifier = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"\n]+)\1/g;
3137
+ const backend_module_move_importLine = /^\s*(?:import|export)\b[^'"\n]*\bfrom\s*(['"])([^'"\n]+)\1;?\s*$/;
3138
+ const deleteBackendUnit = (projectRoot, rootFolderPath, unit)=>{
3139
+ const files = [
3140
+ ...unitMoves(unit, unit).keys()
3141
+ ];
3142
+ const fileSet = new Set(files);
3143
+ const stems = new Set(files.map((file)=>file.replace(codeExtension, '')));
3144
+ const aggregateFolder = 'aggregate' === unit.kind ? external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name) : void 0;
3145
+ const parentAggregate = unit.aggregate ? external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.aggregate) : void 0;
3146
+ const isUnit = (resolved)=>stems.has(resolved) || !!aggregateFolder && (resolved === aggregateFolder || resolved.startsWith(`${aggregateFolder}${external_node_path_default().sep}`));
3147
+ const isParentBarrel = (resolved)=>!!parentAggregate && (resolved === parentAggregate || resolved === external_node_path_default().join(parentAggregate, 'index'));
3148
+ const { codeFiles, resolve } = projectImports(projectRoot);
3149
+ const resolved = (specifier, file)=>resolve(specifier, file)?.resolved;
3150
+ const withoutUnitImports = (content, file)=>content.split('\n').filter((line)=>{
3151
+ const specifier = line.match(backend_module_move_importLine)?.[2];
3152
+ const target = specifier && resolved(specifier, file);
3153
+ return !(target && isUnit(target));
3154
+ }).join('\n');
3155
+ const cleaned = new Map();
3156
+ const inMemoryDb = inMemoryDbFile(rootFolderPath);
3157
+ if ('aggregate' === unit.kind && codeFiles.has(inMemoryDb)) {
3158
+ const section = new UnknownFormatNaming(plural(unit.name));
3159
+ const original = codeFiles.get(inMemoryDb);
3160
+ const content = withoutUnitImports(original.replace(new RegExp(`^[ \\t]*${escapeRegExp(section.variableName)}\\s*=\\s*this\\.section<[^\\n]*\\n?`, 'm'), ''), inMemoryDb);
3161
+ if (content !== original) cleaned.set(inMemoryDb, content);
3162
+ }
3163
+ if (parentAggregate) {
3164
+ const index = external_node_path_default().join(parentAggregate, 'index.ts');
3165
+ const original = codeFiles.get(index);
3166
+ if (void 0 !== original) {
3167
+ const content = withoutUnitImports(original, index);
3168
+ if (content !== original) cleaned.set(index, content);
3169
+ }
3170
+ }
3171
+ const ClassName = new UnknownFormatNaming(unit.name).ClassName;
3172
+ const namedImports = /import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\2/g;
3173
+ const usedBy = [];
3174
+ const relative = (file)=>toPosix(external_node_path_default().relative(projectRoot, file));
3175
+ for (const [file, original] of codeFiles){
3176
+ if (fileSet.has(file)) continue;
3177
+ const content = cleaned.get(file) ?? original;
3178
+ for (const [, , specifier] of content.matchAll(importSpecifier)){
3179
+ const target = resolved(specifier, file);
3180
+ if (target && isUnit(target)) usedBy.push([
3181
+ relative(file),
3182
+ relative(target)
3183
+ ]);
3184
+ }
3185
+ for (const [, names, , specifier] of content.matchAll(namedImports)){
3186
+ const target = resolved(specifier, file);
3187
+ if (target && isParentBarrel(target) && new RegExp(`(?<![\\w$])${ClassName}(?![\\w$])`).test(names)) usedBy.push([
3188
+ relative(file),
3189
+ `${relative(target)} (${ClassName})`
3190
+ ]);
3191
+ }
3192
+ }
3193
+ if (usedBy.length) return {
3194
+ usedBy
3195
+ };
3196
+ for (const file of files)new file_system_File(file).delete(integrationSpecsStop(file) ?? rootFolderPath);
3197
+ for (const [file, content] of cleaned)new file_system_File(file).update(content);
3198
+ return {
3199
+ deleted: files,
3200
+ updated: [
3201
+ ...cleaned.keys()
3202
+ ]
3203
+ };
3142
3204
  };
3143
- const named = {
3144
- ...common,
3145
- ...agent_requests_owner,
3146
- name: agent_requests_name
3205
+ const contractKinds = [
3206
+ 'aggregate',
3207
+ 'command',
3208
+ 'query',
3209
+ 'port'
3210
+ ];
3211
+ const implementations_withWiring = ()=>config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
3212
+ const withHandlers = ()=>config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers');
3213
+ const contractFile = (unit)=>'aggregate' === unit.kind ? `domain/aggregates/${unit.name}/${unit.name}-repository.ts` : kindLayouts[unit.kind].files(unit, [])[0];
3214
+ const findContracts = (ownerPath)=>findBackendUnits(ownerPath).filter((unit)=>contractKinds.includes(unit.kind) && external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, contractFile(unit))));
3215
+ const implementationWireName = (label)=>`wire${new UnknownFormatNaming(label).ClassName}Implementation`;
3216
+ const contractClassName = (unit)=>kindLayouts[unit.kind].core(new UnknownFormatNaming(unit.name).ClassName);
3217
+ const implementationClassName = (unit, label)=>`${new UnknownFormatNaming(label).ClassName}${contractClassName(unit)}`;
3218
+ const implementationFile = (unit, label)=>{
3219
+ const { implementations } = kindLayouts[unit.kind];
3220
+ return kindLayouts[unit.kind].files(unit, [
3221
+ label
3222
+ ]).find((file)=>file.startsWith(`${implementations}/`));
3147
3223
  };
3148
- const agent_requests_operation = (value, shape)=>external_zod_default().strictObject({
3149
- operation: external_zod_default().literal(value),
3150
- ...shape
3151
- });
3152
- const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operation', [
3153
- agent_requests_operation('bounded-context', {
3154
- ...common,
3155
- name: agent_requests_name.refine((value)=>'shared-kernel' !== value, 'shared-kernel is reserved for the Shared Kernel.')
3156
- }),
3157
- agent_requests_operation('aggregate', {
3158
- ...named,
3159
- withRepository: external_zod_default().boolean().optional(),
3160
- implementation: agent_requests_implementation.optional(),
3161
- testImplementation: agent_requests_implementation.optional(),
3162
- ...agent_requests_wired
3163
- }),
3164
- agent_requests_operation('entity', {
3165
- ...named,
3166
- aggregate: agent_requests_name.optional()
3167
- }),
3168
- agent_requests_operation('value-object', {
3169
- ...named,
3170
- aggregate: agent_requests_name.optional()
3171
- }),
3172
- agent_requests_operation('error', {
3173
- ...named,
3174
- namespace: agent_requests_name.optional()
3175
- }),
3176
- agent_requests_operation('error-namespace', named),
3177
- agent_requests_operation('domain-service', {
3178
- ...named,
3179
- ...agent_requests_wired
3180
- }),
3181
- agent_requests_operation('application-service', {
3182
- ...named,
3183
- ...agent_requests_wired
3184
- }),
3185
- agent_requests_operation('infrastructure-service', {
3186
- ...named,
3187
- ...agent_requests_wired
3188
- }),
3189
- agent_requests_operation('helper', {
3190
- ...common,
3191
- ...agent_requests_owner,
3192
- name: agent_requests_nestedName.describe('Kebab-case, folders split by "/": mappers/social-network-type.'),
3193
- implementationType: agent_requests_name.describe('A saved or system implementation type: a helper belongs to one.')
3194
- }),
3195
- agent_requests_operation('presentation-service', {
3196
- ...named,
3197
- ...agent_requests_wired
3198
- }),
3199
- agent_requests_operation('use-case', {
3200
- ...named,
3201
- ...agent_requests_wired
3202
- }),
3203
- agent_requests_operation('command', {
3204
- ...named,
3205
- ...agent_requests_implementations
3206
- }),
3207
- agent_requests_operation('query', {
3208
- ...named,
3209
- ...agent_requests_implementations
3210
- }),
3211
- agent_requests_operation('port', {
3212
- ...named,
3213
- ...agent_requests_implementations
3214
- }),
3215
- agent_requests_operation('implementation', {
3216
- ...common,
3217
- ...agent_requests_owner,
3218
- contract: agent_requests_id.describe('Exact contract ID from --describe.'),
3219
- implementation: agent_requests_implementation,
3220
- environments: external_zod_default().array(agent_requests_name).min(1).optional().describe('Required when the contract wire is envBranchedWire; omit it otherwise.'),
3221
- ...agent_requests_wired
3222
- }),
3223
- agent_requests_operation('endpoint', {
3224
- ...common,
3225
- ...agent_requests_owner,
3226
- controller: agent_requests_name.optional().describe('Omit for the context-root controller (root): `/<context>/<path>`.'),
3227
- method: external_zod_default()["enum"]([
3228
- 'get',
3229
- 'post',
3230
- 'put',
3231
- 'patch',
3232
- 'delete'
3233
- ]),
3234
- path: external_zod_default().string().regex(/^(?:\/?(?:[a-zA-Z0-9_-]+|:[a-zA-Z][a-zA-Z0-9_]*))*\/?$/),
3235
- handler: agent_requests_id.optional().describe('Exact handler module ID from --describe. Required when the context has wired queries, commands or use cases; omit it otherwise.')
3236
- }),
3237
- agent_requests_operation('wire-dependency', {
3238
- ...common,
3239
- ...agent_requests_owner,
3240
- module: agent_requests_id.describe('Exact wiring target ID, including implementation class, from --describe.'),
3241
- dependencies: agent_requests_dependencies
3242
- }),
3243
- agent_requests_operation('delete', {
3244
- ...common,
3245
- ...agent_requests_owner,
3246
- module: agent_requests_id.describe('Exact unit ID from --describe. Refused while other files use it.')
3247
- }),
3248
- agent_requests_operation('move', {
3249
- ...common,
3250
- ...agent_requests_owner,
3251
- module: agent_requests_id.describe('Exact unit ID from --describe.'),
3252
- targetContext: agent_requests_name.optional(),
3253
- name: agent_requests_name.optional(),
3254
- aggregate: agent_requests_name.optional()
3255
- })
3256
- ]);
3257
- const reactRequestSchema = external_zod_default().discriminatedUnion('operation', [
3258
- agent_requests_operation('page', {
3259
- ...common,
3260
- name: agent_requests_nestedName
3261
- }),
3262
- agent_requests_operation('widget', {
3263
- ...common,
3264
- name: agent_requests_nestedName,
3265
- widgetType: external_zod_default()["enum"]([
3266
- 'monolithic',
3267
- 'separated',
3268
- 'headless'
3269
- ]).optional()
3270
- }),
3271
- agent_requests_operation('ui-kit-component', {
3272
- ...common,
3273
- name: agent_requests_name
3274
- }),
3275
- agent_requests_operation('shared-hook', {
3276
- ...common,
3277
- name: agent_requests_name
3278
- }),
3279
- agent_requests_operation('move-page', {
3280
- ...common,
3281
- module: agent_requests_nestedName,
3282
- name: agent_requests_nestedName,
3283
- moveRoute: external_zod_default().boolean().optional().describe('With Next.js and a route at the page path: move it too (default true). Omit it without such a route.')
3284
- }),
3285
- agent_requests_operation('delete-page', {
3286
- ...common,
3287
- module: agent_requests_nestedName,
3288
- deleteRoute: external_zod_default().boolean().optional().describe("With Next.js and the page's own route: delete it too (default true). Omit it without such a route.")
3289
- }),
3290
- agent_requests_operation('delete-widget', {
3291
- ...common,
3292
- module: agent_requests_nestedName
3293
- }),
3294
- agent_requests_operation('move-ui-kit-component', {
3295
- ...common,
3296
- module: agent_requests_name,
3297
- name: agent_requests_name
3298
- }),
3299
- agent_requests_operation('move-shared-hook', {
3300
- ...common,
3301
- module: agent_requests_name,
3302
- name: agent_requests_name
3303
- }),
3304
- agent_requests_operation('delete-ui-kit-component', {
3305
- ...common,
3306
- module: agent_requests_name
3307
- }),
3308
- agent_requests_operation('delete-shared-hook', {
3309
- ...common,
3310
- module: agent_requests_name
3311
- }),
3312
- agent_requests_operation('move-widget', {
3313
- ...common,
3314
- module: agent_requests_nestedName,
3315
- name: agent_requests_nestedName
3224
+ const contractWireFile = (unit)=>kindLayouts[unit.kind].files(unit, []).find((file)=>file.startsWith('wiring/'));
3225
+ const handlerImplementation = (ContractName, ClassName, contractImport)=>withHandlers() ? `
3226
+ import { defineHandler } from '@domain-first/handlers'
3227
+ import { ${ContractName} } from '${contractImport}'
3228
+
3229
+ export class ${ClassName} extends ${ContractName} {
3230
+ constructor() {
3231
+ super()
3232
+ }
3233
+
3234
+ handle = defineHandler({
3235
+ inputSchema: ${ContractName}.inputSchema,
3236
+ outputSchema: ${ContractName}.outputSchema,
3237
+ handler: async (input) => {
3238
+ return {}
3239
+ }
3316
3240
  })
3317
- ]);
3318
- const agent_requests_relativePath = external_zod_default().string().regex(/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/).refine((value)=>!value.split('/').some((part)=>'.' === part || '..' === part), 'Use a project-relative path without . or .. segments.');
3319
- const integrationRequestSchema = agent_requests_operation('add', {
3320
- ...common,
3321
- integrations: external_zod_default().array(external_zod_default()["enum"](integrationIds)).min(1),
3322
- nextAdapter: external_zod_default().boolean().optional(),
3323
- configureReact: external_zod_default().boolean().optional(),
3324
- replaceTestingLibrary: external_zod_default().boolean().optional(),
3325
- withService: external_zod_default().boolean().optional(),
3326
- routePrefix: external_zod_default().string().regex(/^\/?[a-zA-Z0-9_/-]*$/).optional(),
3327
- openapiPath: agent_requests_relativePath.optional(),
3328
- withExtractor: external_zod_default().boolean().optional(),
3329
- swaggerPage: external_zod_default().boolean().optional(),
3330
- targets: external_zod_default().array(external_zod_default()["enum"]([
3331
- 'hooks',
3332
- 'client'
3333
- ])).min(1).optional(),
3334
- scriptConflicts: external_zod_default().record(agent_requests_id, external_zod_default()["enum"]([
3335
- 'keep',
3336
- 'replace',
3337
- 'rename'
3338
- ])).optional(),
3339
- scriptNames: external_zod_default().record(agent_requests_id, external_zod_default().string().regex(/^[a-zA-Z0-9:_-]+$/)).optional()
3340
- });
3341
- const requestSchemaFor = (command)=>({
3342
- 'df-scaffold': scaffoldRequestSchema,
3343
- 'df-react': reactRequestSchema,
3344
- 'df-integration': integrationRequestSchema
3345
- })[command];
3346
- const ignoredFolders = new Set([
3347
- 'node_modules',
3348
- '.git',
3349
- '.next',
3350
- 'dist',
3351
- 'build',
3352
- 'out',
3353
- 'coverage',
3354
- 'storybook-static'
3355
- ]);
3356
- const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
3357
- const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
3358
- const module_move_walk = (folder)=>{
3359
- if (!external_node_fs_default().existsSync(folder)) return [];
3360
- return external_node_fs_default().readdirSync(folder, {
3361
- withFileTypes: true
3362
- }).flatMap((entry)=>{
3363
- const entryPath = external_node_path_default().join(folder, entry.name);
3364
- if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : module_move_walk(entryPath);
3365
- return entry.isFile() ? [
3366
- entryPath
3367
- ] : [];
3368
- });
3369
- };
3370
- const toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
3371
- const readAliases = (projectRoot)=>{
3372
- const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
3373
- if (!external_node_fs_default().existsSync(tsconfig)) return [];
3374
- try {
3375
- const { compilerOptions = {} } = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(tsconfig, 'utf8')));
3376
- const base = external_node_path_default().resolve(projectRoot, compilerOptions.baseUrl ?? '.');
3377
- return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
3378
- prefix: pattern.slice(0, -1),
3379
- target: external_node_path_default().resolve(base, target.slice(0, -1))
3380
- }));
3381
- } catch {
3382
- return [];
3241
+ }
3242
+ `.trim() : `
3243
+ import { ${ContractName} } from '${contractImport}'
3244
+
3245
+ export class ${ClassName} extends ${ContractName} {
3246
+ constructor() {
3247
+ super()
3383
3248
  }
3384
- };
3385
- const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
3386
- const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
3387
- const importPaths = (file)=>{
3388
- const withoutExtension = file.replace(codeExtension, '');
3389
- return 'index' === external_node_path_default().basename(withoutExtension) ? [
3390
- withoutExtension,
3391
- external_node_path_default().dirname(withoutExtension)
3392
- ] : [
3393
- withoutExtension
3249
+ }
3250
+ `.trim();
3251
+ const createImplementation = (ownerFolder, unit, label)=>{
3252
+ const naming = new UnknownFormatNaming(unit.name);
3253
+ const ContractName = contractClassName(unit);
3254
+ const className = implementationClassName(unit, label);
3255
+ const [folder, fileName] = [
3256
+ external_node_path_default().dirname(implementationFile(unit, label)),
3257
+ external_node_path_default().basename(implementationFile(unit, label))
3394
3258
  ];
3259
+ const implementationFolder = ownerFolder.subitem(folder.split('/'));
3260
+ const inMemoryDb = !implementations_withWiring() && usesInMemoryDb(label);
3261
+ switch(unit.kind){
3262
+ case 'aggregate':
3263
+ {
3264
+ const contractImport = `../../../domain/aggregates/${unit.name}`;
3265
+ if (inMemoryDb) {
3266
+ const section = addInMemoryDbSection(naming, ownerFolder.subitem([
3267
+ 'domain',
3268
+ 'aggregates',
3269
+ unit.name
3270
+ ]).path);
3271
+ const file = implementationFolder.createFile(fileName, `
3272
+ ${inMemoryDbTypeImport(implementationFolder.subitem([
3273
+ fileName
3274
+ ]).path)}
3275
+ import { ${ContractName} } from '${contractImport}'
3276
+
3277
+ export class ${className} implements ${ContractName} {
3278
+ ${inMemoryDbSectionMembers(section, false)}
3279
+ }
3280
+ `.trim());
3281
+ return {
3282
+ file,
3283
+ className
3284
+ };
3285
+ }
3286
+ const file = implementationFolder.createFile(fileName, `
3287
+ import { ${ContractName} } from '${contractImport}'
3288
+
3289
+ export class ${className} implements ${ContractName} {
3290
+ constructor() {}
3291
+ }
3292
+
3293
+ `.trim());
3294
+ return {
3295
+ file,
3296
+ className
3297
+ };
3298
+ }
3299
+ case 'command':
3300
+ case 'query':
3301
+ {
3302
+ const folderName = 'command' === unit.kind ? 'commands' : 'queries';
3303
+ const file = implementationFolder.createFile(fileName, handlerImplementation(ContractName, className, `../../../application/${folderName}/${naming.fileName}-${unit.kind}`));
3304
+ if (inMemoryDb) injectInMemoryDb(file, className);
3305
+ return {
3306
+ file,
3307
+ className
3308
+ };
3309
+ }
3310
+ case 'port':
3311
+ {
3312
+ const file = implementationFolder.createFile(fileName, `
3313
+ import { ${ContractName} } from '../../../application/ports/${naming.fileName}'
3314
+
3315
+ export class ${className} extends ${ContractName} {
3316
+
3317
+ }
3318
+ `.trim());
3319
+ return {
3320
+ file,
3321
+ className
3322
+ };
3323
+ }
3324
+ default:
3325
+ throw new Error(`${unit.kind} has no implementations`);
3326
+ }
3395
3327
  };
3396
- const projectImports = (projectRoot)=>{
3397
- const aliases = readAliases(projectRoot);
3398
- const resolve = (specifier, fromFile)=>{
3399
- if (specifier.startsWith('.')) return {
3400
- resolved: external_node_path_default().resolve(external_node_path_default().dirname(fromFile), specifier),
3401
- alias: void 0
3402
- };
3403
- const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
3404
- return alias ? {
3405
- resolved: external_node_path_default().resolve(alias.target, specifier.slice(alias.prefix.length)),
3406
- alias
3407
- } : void 0;
3408
- };
3409
- const specifierFor = (fromFile, toPath, alias)=>{
3410
- const aliased = alias && toPosix(external_node_path_default().relative(alias.target, toPath));
3411
- if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
3412
- const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
3413
- return relative.startsWith('.') ? relative : `./${relative}`;
3414
- };
3415
- const codeFiles = new Map(module_move_walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
3416
- file,
3417
- external_node_fs_default().readFileSync(file, 'utf8')
3418
- ]));
3419
- const importsOf = (file)=>[
3420
- ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
3421
- ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
3422
- return {
3423
- resolve,
3424
- specifierFor,
3425
- codeFiles,
3426
- importsOf
3328
+ const inMemoryRepositoryWiring = (ownerFolder, unit, wireFile)=>(implementation, dependency)=>{
3329
+ if ('aggregate' !== unit.kind || !isInMemoryDb(dependency)) return false;
3330
+ keepInMemoryDbSection(new file_system_File(implementation.file), addInMemoryDbSection(new UnknownFormatNaming(unit.name), ownerFolder.subitem([
3331
+ 'domain',
3332
+ 'aggregates',
3333
+ unit.name
3334
+ ]).path));
3335
+ wireInMemoryDb(wireFile, implementation.className);
3336
+ return true;
3427
3337
  };
3428
- };
3429
- const stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content, stopAtFor })=>{
3430
- const stopFor = (file)=>stopAtFor?.(file) ?? stopAt;
3431
- const { resolve, specifierFor, codeFiles } = projectImports(projectRoot);
3432
- const barrels = new Set();
3433
- const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
3434
- for(let found = true; found;){
3435
- found = false;
3436
- for (const [file, content] of codeFiles){
3437
- if (moves.has(file) || isBarrel(file)) continue;
3438
- const reExportsModule = [
3439
- ...content.matchAll(reExportPattern)
3440
- ].some(([, , specifier])=>{
3441
- const resolution = resolve(specifier, file);
3442
- return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
3443
- });
3444
- if (reExportsModule) {
3445
- for (const importPath of importPaths(file))barrels.add(importPath);
3446
- found = true;
3338
+ const integration_tests_withWiring = ()=>config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
3339
+ const integrationSpecsAvailable = ()=>integration_tests_withWiring() && new file_system_File(external_node_path_default().join(new project_root_ProjectRoot().path, integrationSpecsFolder, 'vitest.config.ts')).exists;
3340
+ const systemImplementationTypes = new Set([
3341
+ inMemoryImplementationType,
3342
+ crossContextImplementation
3343
+ ]);
3344
+ const integrationTestTypes = ()=>config_file_ConfigFile.backend.implementations?.integrationTests ?? [];
3345
+ const setIntegrationTestTypes = (types)=>{
3346
+ const backend = config_file_ConfigFile.backend;
3347
+ config_file_ConfigFile.update({
3348
+ backend: {
3349
+ ...backend,
3350
+ implementations: {
3351
+ ...backend.implementations,
3352
+ integrationTests: [
3353
+ ...new Set(types)
3354
+ ]
3447
3355
  }
3448
3356
  }
3449
- }
3450
- const rewrite = (content, oldFile, newFile)=>{
3451
- let referencesModule = false;
3452
- const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
3453
- const resolution = resolve(specifier, oldFile);
3454
- if (!resolution) return match;
3455
- const moved = movedPath(resolution.resolved);
3456
- if (moved || isBarrel(resolution.resolved)) referencesModule = true;
3457
- if (!moved && oldFile === newFile) return match;
3458
- const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
3459
- return `${keyword}${quote}${next}${quote}`;
3460
- });
3461
- const changed = everyFile(rewritten);
3462
- if (!referencesModule && !moves.has(oldFile)) return changed;
3463
- return rename(changed, {
3464
- moved: moves.has(oldFile)
3357
+ });
3358
+ };
3359
+ const integration_tests_importPath = (fromFile, toFile)=>{
3360
+ const relative = external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile).replace(/\.ts$/, '').split(external_node_path_default().sep).join('/');
3361
+ return relative.startsWith('.') ? relative : `./${relative}`;
3362
+ };
3363
+ const exportImplementationWire = (wireFile, label)=>{
3364
+ if (!wireFile.exists) return false;
3365
+ const name = implementationWireName(label);
3366
+ const declaration = new RegExp(`^(export\\s+)?const\\s+${name}\\b`, 'm');
3367
+ const match = wireFile.data.match(declaration);
3368
+ if (!match) return false;
3369
+ if (!match[1]) wireFile.update(wireFile.data.replace(declaration, `export const ${name}`));
3370
+ return true;
3371
+ };
3372
+ const renderSpec = ({ title, className, classFile, wireImport, wireFile, factory, specPath })=>`
3373
+ import { describe, test, expect } from 'vitest'
3374
+ import { ${className} } from '${integration_tests_importPath(specPath, classFile)}'
3375
+ import { ${wireImport} } from '${integration_tests_importPath(specPath, wireFile)}'
3376
+
3377
+ describe('${title}', () => {
3378
+ test('can be wired', () => {
3379
+ expect(${factory}()).toBeInstanceOf(${className})
3380
+ })
3381
+
3382
+ test.todo('works against the infrastructure')
3383
+ })
3384
+ `.trimStart();
3385
+ const scaffoldIntegrationSpec = (unit, label)=>{
3386
+ const specPath = integrationSpecFile(unit, label);
3387
+ if (!specPath) return;
3388
+ const spec = new file_system_File(specPath);
3389
+ if (spec.exists) return;
3390
+ const layout = kindLayouts[unit.kind];
3391
+ const naming = new UnknownFormatNaming(unit.name);
3392
+ const core = layout.core(naming.ClassName);
3393
+ const files = layout.files({
3394
+ ownerPath: unit.ownerPath,
3395
+ name: unit.name
3396
+ }, void 0 === label ? [] : [
3397
+ label
3398
+ ]);
3399
+ const wireFile = new file_system_File(external_node_path_default().join(unit.ownerPath, files.find((file)=>file.startsWith('wiring/'))));
3400
+ if (void 0 === label) {
3401
+ const factory = `wire${core}`;
3402
+ spec.data = renderSpec({
3403
+ title: naming.withSpaces,
3404
+ className: core,
3405
+ classFile: external_node_path_default().join(unit.ownerPath, files[0]),
3406
+ wireImport: factory,
3407
+ wireFile: wireFile.path,
3408
+ factory,
3409
+ specPath
3465
3410
  });
3466
- };
3467
- for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new file_system_File(file).moveTo(newFile, stopFor(file));
3468
- const updated = [];
3469
- for (const [file, content] of codeFiles){
3470
- const newFile = moves.get(file);
3471
- const next = rewrite(content, file, newFile ?? file);
3472
- if (newFile && newFile !== file) {
3473
- new file_system_File(newFile).data = next;
3474
- new file_system_File(file).delete(stopFor(file));
3475
- } else if (next !== content) {
3476
- new file_system_File(file).update(next);
3477
- if (!newFile) updated.push(file);
3478
- }
3411
+ return spec;
3479
3412
  }
3480
- return {
3481
- moves: [
3482
- ...moves
3483
- ].filter(([from, to])=>from !== to),
3484
- updated
3485
- };
3486
- };
3487
- const serviceLayout = (layer)=>({
3488
- title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
3489
- core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
3490
- files: ({ name })=>[
3491
- `${layer}/services/${name}-${layer}-service.ts`,
3492
- `${layer}/services/${name}-${layer}-service.spec.ts`,
3493
- `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
3494
- ],
3495
- wired: true,
3496
- sharedKernel: true
3413
+ const className = `${new UnknownFormatNaming(label).ClassName}${core}`;
3414
+ if (!exportImplementationWire(wireFile, label)) return void report(`No integration spec for ${className}: ${wireFile.path} has no ${implementationWireName(label)} factory.`);
3415
+ const factory = `wire${className}`;
3416
+ const wireImport = `${implementationWireName(label)} as ${factory}`;
3417
+ const title = 'aggregate' === unit.kind ? `${naming.withSpaces} repository` : 'port' === unit.kind ? naming.withSpaces : `${naming.withSpaces} ${unit.kind}`;
3418
+ spec.data = renderSpec({
3419
+ title: `${title} (${label})`,
3420
+ className,
3421
+ classFile: external_node_path_default().join(unit.ownerPath, files.find((file)=>file.startsWith(`${layout.implementations}/${label}/`))),
3422
+ wireImport,
3423
+ wireFile: wireFile.path,
3424
+ factory,
3425
+ specPath
3426
+ });
3427
+ return spec;
3428
+ };
3429
+ const unusedAnswer = ()=>new RequestError('UNUSED_PARAMETERS', 'implementation.integrationTests applies only to a newly entered primary implementation type, with the Testcontainers integration and wiring.', {
3430
+ fields: [
3431
+ 'implementation.integrationTests'
3432
+ ]
3497
3433
  });
3498
- const handlerLayout = (kind)=>{
3499
- const folder = 'command' === kind ? 'commands' : 'queries';
3500
- const Suffix = 'command' === kind ? 'Command' : 'Query';
3501
- return {
3502
- title: 'command' === kind ? 'Commands' : 'Queries',
3503
- core: (ClassName)=>`${ClassName}${Suffix}`,
3504
- files: ({ name }, labels)=>[
3505
- `application/${folder}/${name}-${kind}.ts`,
3506
- `application/${folder}/${name}-${kind}.spec.ts`,
3507
- ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
3508
- `wiring/${folder}/wire-${name}-${kind}.ts`
3509
- ],
3510
- implementations: `infrastructure/${folder}`,
3511
- wired: true,
3512
- sharedKernel: false
3513
- };
3434
+ const wantsIntegrationTests = async (label, { entered, save })=>{
3435
+ const answer = isNonInteractive() ? answerFor('implementation')?.integrationTests : void 0;
3436
+ const applies = integrationSpecsAvailable() && entered && !systemImplementationTypes.has(label) && !integrationTestTypes().includes(label);
3437
+ if (!applies) {
3438
+ if (void 0 !== answer) throw unusedAnswer();
3439
+ return integrationSpecsAvailable() && integrationTestTypes().includes(label);
3440
+ }
3441
+ const wanted = isNonInteractive() ? answer ?? true : await interaction_confirm({
3442
+ message: `Generate integration tests for ${label} implementations?`,
3443
+ default: true
3444
+ });
3445
+ if (wanted && save) setIntegrationTestTypes([
3446
+ ...integrationTestTypes(),
3447
+ label
3448
+ ]);
3449
+ return wanted;
3514
3450
  };
3515
- const domainModelLayout = (kind)=>{
3516
- const folder = 'entity' === kind ? 'entities' : 'value-objects';
3451
+ const wantsServiceIntegrationSpec = async ()=>integrationSpecsAvailable() && await interaction_confirm({
3452
+ key: 'integrationSpec',
3453
+ message: 'Generate an integration spec?',
3454
+ default: false
3455
+ });
3456
+ const wire_branches_defaultEnvBranches = {
3457
+ names: [
3458
+ 'test',
3459
+ 'development',
3460
+ 'production'
3461
+ ],
3462
+ test: 'test'
3463
+ };
3464
+ const wire_branches_envBranches = ()=>{
3465
+ const configured = config_file_ConfigFile.exists ? config_file_ConfigFile.Instance.data.backend?.envBranches : void 0;
3466
+ const { names, test } = configured ?? wire_branches_defaultEnvBranches;
3517
3467
  return {
3518
- title: 'entity' === kind ? 'Entities' : 'Value objects',
3519
- core: (ClassName)=>ClassName,
3520
- files: ({ name, aggregate })=>{
3521
- const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
3522
- return [
3523
- `${base}/${name}.${kind}.ts`,
3524
- `${base}/${name}.${kind}.spec.ts`
3525
- ];
3526
- },
3527
- wired: false,
3528
- sharedKernel: true
3468
+ names,
3469
+ test,
3470
+ primary: names.filter((name)=>name !== test),
3471
+ custom: Boolean(configured)
3529
3472
  };
3530
3473
  };
3531
- const aggregateOwnFiles = (name)=>[
3532
- `${name}.aggregate-root.ts`,
3533
- `${name}.aggregate-root.spec.ts`,
3534
- `${name}-repository.ts`,
3535
- `${name}-repository.spec.ts`,
3536
- 'index.ts'
3537
- ];
3538
- const kindLayouts = {
3539
- aggregate: {
3540
- title: 'Aggregates',
3541
- core: (ClassName)=>`${ClassName}Repository`,
3542
- files: ({ name }, labels)=>[
3543
- ...aggregateOwnFiles(name).map((file)=>`domain/aggregates/${name}/${file}`),
3544
- ...labels.map((label)=>`infrastructure/repositories/${label}/${label}-${name}-repository.ts`),
3545
- `wiring/repositories/wire-${name}-repository.ts`
3546
- ],
3547
- implementations: 'infrastructure/repositories',
3548
- wired: true,
3549
- sharedKernel: false
3550
- },
3551
- entity: domainModelLayout('entity'),
3552
- 'value-object': domainModelLayout('value-object'),
3553
- 'domain-service': serviceLayout('domain'),
3554
- 'application-service': serviceLayout('application'),
3555
- 'infrastructure-service': serviceLayout('infrastructure'),
3556
- 'presentation-service': serviceLayout('presentation'),
3557
- 'use-case': {
3558
- title: 'Use cases',
3559
- core: (ClassName)=>`${ClassName}UseCase`,
3560
- files: ({ name })=>[
3561
- `application/use-cases/${name}-use-case.ts`,
3562
- `application/use-cases/${name}-use-case.spec.ts`,
3563
- `wiring/use-cases/wire-${name}-use-case.ts`
3564
- ],
3565
- wired: true,
3566
- sharedKernel: false
3474
+ const offersTestImplementation = ()=>{
3475
+ const backend = config_file_ConfigFile.exists ? config_file_ConfigFile.Instance.data.backend : void 0;
3476
+ return !(backend?.domainFirstPackages.includes('@domain-first/wire') && backend.envBranches && void 0 === backend.envBranches.test);
3477
+ };
3478
+ const envBranchedWireArgument = (testWire, primaryWire)=>{
3479
+ const { test, primary } = wire_branches_envBranches();
3480
+ return `{\n${[
3481
+ ...test ? [
3482
+ ` ${test}: ${testWire}`
3483
+ ] : [],
3484
+ ...primary.map((name)=>` ${name}: ${primaryWire}`)
3485
+ ].join(',\n')}\n}`;
3486
+ };
3487
+ const integrationFolder = 'specs/integration';
3488
+ const testcontainersScripts = {
3489
+ 'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
3490
+ };
3491
+ const testcontainersVitestConfig = (inlineHandlersNext)=>{
3492
+ const server = inlineHandlersNext ? `,
3493
+ server: {
3494
+ deps: {
3495
+ // Imports \`next/headers\` without an extension, which only a bundler can resolve
3496
+ inline: ['@domain-first/handlers-next']
3497
+ }
3498
+ }` : '';
3499
+ return `import { fileURLToPath } from 'node:url';
3500
+ import { defineConfig } from 'vitest/config';
3501
+
3502
+ // Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
3503
+ export default defineConfig({
3504
+ // Paths below are relative to the project root, not this folder
3505
+ root: fileURLToPath(new URL('../..', import.meta.url)),
3506
+ resolve: {
3507
+ tsconfigPaths: true
3567
3508
  },
3568
- command: handlerLayout('command'),
3569
- query: handlerLayout('query'),
3570
- port: {
3571
- title: 'Ports',
3572
- core: (ClassName)=>ClassName,
3573
- files: ({ name }, labels)=>[
3574
- `application/ports/${name}.ts`,
3575
- `application/ports/${name}.spec.ts`,
3576
- ...labels.map((label)=>`infrastructure/application-adapters/${label}/${label}-${name}.ts`),
3577
- `wiring/application-ports/wire-${name}.ts`
3578
- ],
3579
- implementations: 'infrastructure/application-adapters',
3580
- wired: true,
3581
- sharedKernel: true
3509
+ test: {
3510
+ include: ['${integrationFolder}/**/*.spec.ts'],
3511
+ // Development implementations work with the real database
3512
+ env: { NODE_ENV: 'development' },
3513
+ globalSetup: ['${integrationFolder}/global-setup.ts'],
3514
+ setupFiles: ['${integrationFolder}/setup-env.ts'],
3515
+ // Pulling the image on the first run takes a while
3516
+ hookTimeout: 120_000${server}
3582
3517
  }
3518
+ });
3519
+ `;
3583
3520
  };
3584
- const subfolders = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
3585
- withFileTypes: true
3586
- }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
3587
- const namesBySuffix = (folder, suffix)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder).filter((file)=>file.endsWith(suffix) && !file.endsWith('.spec.ts')).map((file)=>file.slice(0, -suffix.length)).sort() : [];
3588
- const labelsOf = (ownerPath, kind, name)=>{
3589
- const { implementations } = kindLayouts[kind];
3590
- if (!implementations) return [];
3591
- return subfolders(external_node_path_default().join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
3592
- ownerPath,
3593
- name
3594
- }, [
3595
- label
3596
- ]).some((file)=>file.startsWith(`${implementations}/`) && external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, file))));
3521
+ const testcontainersGlobalSetup = (migrationCommand)=>{
3522
+ const migrations = migrationCommand ? `
3523
+ // dotenv in the Prisma config does not override an already set variable
3524
+ execSync(${JSON.stringify(migrationCommand)}, {
3525
+ cwd: project.config.root,
3526
+ env: { ...process.env, DATABASE_URL: databaseUrl },
3527
+ // On failure the error carries the command's output
3528
+ stdio: 'pipe'
3529
+ });
3530
+ ` : `
3531
+ // Apply your migrations to databaseUrl here.
3532
+ `;
3533
+ return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
3534
+ import type { TestProject } from 'vitest/node';
3535
+
3536
+ declare module 'vitest' {
3537
+ export interface ProvidedContext {
3538
+ databaseUrl: string;
3539
+ }
3540
+ }
3541
+
3542
+ const POSTGRES_IMAGE = 'postgres:15';
3543
+ const POSTGRES_PORT = 5432;
3544
+ const POSTGRES_USER = 'test';
3545
+ const POSTGRES_PASSWORD = 'test';
3546
+ const POSTGRES_DB = 'test';
3547
+
3548
+ export default async function setup(project: TestProject) {
3549
+ const container = await new GenericContainer(POSTGRES_IMAGE)
3550
+ .withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
3551
+ .withExposedPorts(POSTGRES_PORT)
3552
+ // During init PostgreSQL listens on a unix socket only and restarts,
3553
+ // so checking over TCP passes once the final server is up
3554
+ .withHealthCheck({
3555
+ test: [
3556
+ 'CMD-SHELL',
3557
+ \`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
3558
+ ],
3559
+ interval: 250,
3560
+ timeout: 1000,
3561
+ retries: 1000
3562
+ })
3563
+ .withWaitStrategy(Wait.forHealthCheck())
3564
+ .withStartupTimeout(120_000)
3565
+ .start();
3566
+
3567
+ const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
3568
+ ${migrations}
3569
+ project.provide('databaseUrl', databaseUrl);
3570
+
3571
+ return async () => {
3572
+ await container.stop();
3573
+ };
3574
+ }
3575
+ `;
3597
3576
  };
3598
- const aggregatesOf = (ownerPath)=>subfolders(external_node_path_default().join(ownerPath, 'domain/aggregates')).filter((name)=>external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, 'domain/aggregates', name, `${name}.aggregate-root.ts`)));
3599
- const findBackendUnits = (ownerPath)=>{
3600
- const unit = (kind, name, aggregate)=>({
3601
- kind,
3602
- name,
3603
- ownerPath,
3604
- aggregate,
3605
- labels: labelsOf(ownerPath, kind, name)
3577
+ const testcontainersSetupEnv = `import 'dotenv/config';
3578
+ import { inject } from 'vitest';
3579
+
3580
+ // Runs before each spec's imports: development implementations get the .env
3581
+ // config, and DATABASE_URL points to the container instead of the one from .env.
3582
+ if (process.env.NODE_ENV !== 'development') {
3583
+ throw new Error(
3584
+ \`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
3585
+ );
3586
+ }
3587
+
3588
+ process.env.DATABASE_URL = inject('databaseUrl');
3589
+ `;
3590
+ const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
3591
+
3592
+ test('connects to the database in the container', () => {
3593
+ expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
3594
+ });
3595
+ `;
3596
+ const excludeFromUnitTests = (content)=>{
3597
+ const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
3598
+ if (!exclude.test(content)) return;
3599
+ const entry = `'${integrationFolder}/**'`;
3600
+ return content.replace(exclude, (_, items, comma, whitespace)=>{
3601
+ const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
3602
+ const separator = void 0 === indent ? ', ' : `,\n${indent}`;
3603
+ return `${items}${separator}${entry}${comma}${whitespace}]`;
3604
+ }).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
3605
+ };
3606
+ const testcontainers_stageFile = (filePath, content)=>{
3607
+ const file = new file_system_File(filePath);
3608
+ if (!file.exists || file.data !== content) file.data = content;
3609
+ };
3610
+ const configureIntegrationTests = async (root)=>{
3611
+ if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) return;
3612
+ const kindsOf = new Map();
3613
+ for (const kind of implementationKinds)for (const label of savedImplementations(kind, 'primary'))if (!systemImplementationTypes.has(label)) kindsOf.set(label, [
3614
+ ...kindsOf.get(label) ?? [],
3615
+ kind
3616
+ ]);
3617
+ const current = integrationTestTypes();
3618
+ if (kindsOf.size) {
3619
+ const selected = await interaction_checkbox({
3620
+ key: 'integrationTestTypes',
3621
+ message: 'Integration tests for implementation types:',
3622
+ choices: [
3623
+ ...kindsOf
3624
+ ].map(([value, kinds])=>({
3625
+ name: `${value} (${kinds.join(', ')})`,
3626
+ value,
3627
+ checked: current.includes(value)
3628
+ }))
3606
3629
  });
3607
- const aggregates = aggregatesOf(ownerPath);
3608
- const inAggregates = (kind)=>aggregates.flatMap((aggregate)=>namesBySuffix(external_node_path_default().join(ownerPath, 'domain/aggregates', aggregate, 'entity' === kind ? 'entities' : 'value-objects'), `.${kind}.ts`).map((name)=>unit(kind, name, aggregate)));
3609
- const at = (folder, suffix, kind)=>namesBySuffix(external_node_path_default().join(ownerPath, folder), suffix).map((name)=>unit(kind, name));
3610
- return [
3611
- ...aggregates.map((name)=>unit('aggregate', name)),
3612
- ...inAggregates('entity'),
3613
- ...at('domain/entities', '.entity.ts', 'entity'),
3614
- ...inAggregates('value-object'),
3615
- ...at('domain/value-objects', '.value-object.ts', 'value-object'),
3616
- ...at('domain/services', '-domain-service.ts', 'domain-service'),
3617
- ...at('application/ports', '.ts', 'port'),
3618
- ...at('application/queries', '-query.ts', 'query'),
3619
- ...at('application/commands', '-command.ts', 'command'),
3620
- ...at('application/use-cases', '-use-case.ts', 'use-case'),
3621
- ...at('application/services', '-application-service.ts', 'application-service'),
3622
- ...at('infrastructure/services', '-infrastructure-service.ts', 'infrastructure-service'),
3623
- ...at('presentation/services', '-presentation-service.ts', 'presentation-service')
3630
+ const kept = current.filter((label)=>!kindsOf.has(label));
3631
+ const next = [
3632
+ ...selected,
3633
+ ...kept
3634
+ ];
3635
+ if (next.length !== current.length || next.some((label)=>!current.includes(label))) setIntegrationTestTypes(next);
3636
+ }
3637
+ const types = integrationTestTypes();
3638
+ if (!types.length) return;
3639
+ const testBranch = wire_branches_envBranches().test;
3640
+ const source = new file_system_Folder(root).subitem([
3641
+ config_file_ConfigFile.Instance.data.project.rootFolder
3642
+ ]);
3643
+ const owners = [
3644
+ source.subitem([
3645
+ 'shared-kernel'
3646
+ ]),
3647
+ ...source.subitem([
3648
+ 'bounded-contexts'
3649
+ ]).content.subfolderNames.sort().map((name)=>source.subitem([
3650
+ 'bounded-contexts',
3651
+ name
3652
+ ]))
3624
3653
  ];
3625
- };
3626
- const kebabName = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
3627
- const lowerFirst = (value)=>value[0].toLowerCase() + value.slice(1);
3628
- const unitMoves = (unit, target)=>{
3629
- const layout = kindLayouts[unit.kind];
3630
- const from = layout.files(unit, unit.labels);
3631
- const to = layout.files(target, unit.labels);
3632
- const moves = new Map();
3633
- from.forEach((file, index)=>{
3634
- const oldPath = external_node_path_default().join(unit.ownerPath, file);
3635
- if (external_node_fs_default().existsSync(oldPath)) moves.set(oldPath, external_node_path_default().join(target.ownerPath, to[index]));
3636
- });
3637
- if ('aggregate' === unit.kind) {
3638
- const oldFolder = external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name);
3639
- const newFolder = external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.name);
3640
- const own = new Set(aggregateOwnFiles(unit.name).map((file)=>external_node_path_default().join(oldFolder, file)));
3641
- for (const file of module_move_walk(oldFolder))if (!own.has(file)) moves.set(file, external_node_path_default().join(newFolder, external_node_path_default().relative(oldFolder, file)));
3654
+ for (const owner of owners)for (const unit of findContracts(owner.path)){
3655
+ const wireFile = new file_system_File(external_node_path_default().join(owner.path, contractWireFile(unit)));
3656
+ if (!wireFile.exists) continue;
3657
+ let wired;
3658
+ try {
3659
+ wired = wireBranches(wireFile.data, `wire${contractClassName(unit)}`);
3660
+ } catch {
3661
+ continue;
3662
+ }
3663
+ const primaryWires = new Set([
3664
+ ...wired
3665
+ ].filter(([branch])=>branch !== testBranch).map(([, wire])=>wire));
3666
+ for (const label of unit.labels)if (types.includes(label) && primaryWires.has(implementationWireName(label))) scaffoldIntegrationSpec(unit, label);
3642
3667
  }
3643
- return moves;
3644
- };
3645
- const validateBackendMove = (unit, target, sharedKernelPath)=>{
3646
- if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
3647
- if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
3648
- if (target.ownerPath === unit.ownerPath && target.name === unit.name && target.aggregate === unit.aggregate) return 'Nothing to change: enter a new name or pick another place';
3649
- for (const [from, to] of unitMoves(unit, target))if (to !== from && external_node_fs_default().existsSync(to)) return `${external_node_path_default().relative(target.ownerPath, to)} already exists`;
3650
- return true;
3651
3668
  };
3652
- const ownerOf = (rootFolderPath, file)=>{
3653
- const [area, context] = external_node_path_default().relative(rootFolderPath, file).split(external_node_path_default().sep);
3654
- if ('bounded-contexts' === area && context) return {
3655
- context,
3656
- path: external_node_path_default().join(rootFolderPath, area, context)
3657
- };
3658
- if ('shared-kernel' === area) return {
3659
- context: void 0,
3660
- path: external_node_path_default().join(rootFolderPath, area)
3669
+ const addTestcontainers = async ()=>{
3670
+ const config = config_file_ConfigFile.Instance.data;
3671
+ const root = new project_root_ProjectRoot().path;
3672
+ const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
3673
+ const manifest = JSON.parse(manifestFile.data);
3674
+ const dependencies = {
3675
+ ...manifest.dependencies,
3676
+ ...manifest.devDependencies
3661
3677
  };
3678
+ const selected = await addPackageScripts(manifestFile, testcontainersScripts);
3679
+ const withPrisma = new file_system_File(external_node_path_default().resolve(root, config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
3680
+ const migrationCommand = withPrisma ? `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
3681
+ const folder = external_node_path_default().join(root, integrationFolder);
3682
+ testcontainers_stageFile(external_node_path_default().join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
3683
+ testcontainers_stageFile(external_node_path_default().join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
3684
+ testcontainers_stageFile(external_node_path_default().join(folder, 'setup-env.ts'), testcontainersSetupEnv);
3685
+ const example = new file_system_File(external_node_path_default().join(folder, 'database/database.spec.ts'));
3686
+ if (!example.exists) example.data = testcontainers_exampleSpec;
3687
+ const unitConfig = new file_system_File(external_node_path_default().join(root, 'vitest.config.ts'));
3688
+ let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
3689
+ if (!excludedFromUnitTests) {
3690
+ const excluded = excludeFromUnitTests(unitConfig.data);
3691
+ if (excluded) {
3692
+ unitConfig.update(excluded);
3693
+ excludedFromUnitTests = true;
3694
+ }
3695
+ }
3696
+ await configureIntegrationTests(root);
3697
+ const missing = [
3698
+ 'vitest',
3699
+ 'testcontainers',
3700
+ 'dotenv'
3701
+ ].filter((name)=>!dependencies[name]);
3702
+ return [
3703
+ ...missing.length ? [
3704
+ `npm install --save-dev ${missing.join(' ')}`
3705
+ ] : [],
3706
+ `Integration specs run against postgres:15 and get its address in DATABASE_URL. Change the image, credentials and connection string in ${integrationFolder}/global-setup.ts, and the variable name in ${integrationFolder}/setup-env.ts.`,
3707
+ ...migrationCommand ? [] : [
3708
+ `Apply your migrations in ${integrationFolder}/global-setup.ts.`
3709
+ ],
3710
+ ...excludedFromUnitTests ? [] : [
3711
+ `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
3712
+ ],
3713
+ ...wire_branches_envBranches().custom ? [
3714
+ `${integrationFolder} runs with NODE_ENV=development and ${integrationFolder}/setup-env.ts requires it, but your envBranchedWire branches are custom: make currentBranch in shared-kernel/wiring/env-branched-wire.ts return the branch for integration specs, and adjust setup-env.ts.`
3715
+ ] : [],
3716
+ 'Docker must be running for integration specs.',
3717
+ ...describeScripts(selected, {
3718
+ 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
3719
+ })
3720
+ ];
3662
3721
  };
3663
- const inMemoryDbFile = (rootFolderPath)=>external_node_path_default().join(rootFolderPath, 'shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts');
3664
- const isolationAllows = (rootFolderPath, from, to)=>{
3665
- const fromOwner = ownerOf(rootFolderPath, from);
3666
- const toOwner = ownerOf(rootFolderPath, to);
3667
- if (!fromOwner || !toOwner?.context) return true;
3668
- if (fromOwner.context) return fromOwner.context === toOwner.context || true === crossContextImportAllowed(from, to);
3669
- const inside = (folder)=>to === external_node_path_default().join(toOwner.path, folder) || to.startsWith(external_node_path_default().join(toOwner.path, folder) + external_node_path_default().sep);
3670
- return inside('domain/errors') || from.replace(codeExtension, '') === inMemoryDbFile(rootFolderPath).replace(codeExtension, '') && inside('domain');
3722
+ const vitestScripts = {
3723
+ test: 'vitest run --reporter=dot --silent=passed-only',
3724
+ 'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
3671
3725
  };
3672
- const moveBackendUnit = (projectRoot, rootFolderPath, unit, target)=>{
3673
- const layout = kindLayouts[unit.kind];
3674
- const moves = unitMoves(unit, target);
3675
- const withoutExtension = new Map([
3676
- ...moves
3677
- ].map(([from, to])=>[
3678
- from.replace(codeExtension, ''),
3679
- to.replace(codeExtension, '')
3680
- ]));
3681
- const folders = 'aggregate' === unit.kind ? [
3682
- [
3683
- external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name),
3684
- external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.name)
3685
- ]
3686
- ] : [];
3687
- const movedPath = (candidate)=>{
3688
- const extension = candidate.match(codeExtension)?.[0];
3689
- if (extension) return moves.get(candidate);
3690
- return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
3691
- };
3692
- const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
3693
- const oldNaming = new UnknownFormatNaming(unit.name);
3694
- const newNaming = new UnknownFormatNaming(target.name);
3695
- const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
3696
- const oldAggregateFolder = unit.aggregate && external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
3697
- const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === external_node_path_default().join(oldAggregateFolder, 'index'));
3698
- const mainFile = [
3699
- ...moves.keys()
3700
- ][0];
3701
- const newMainFile = moves.get(mainFile);
3702
- const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
3703
- const barrelImporters = leavesAggregate ? [
3704
- ...codeFiles
3705
- ].filter(([file, content])=>!moves.has(file) && [
3706
- ...content.matchAll(namedImports)
3707
- ].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
3708
- const violations = [];
3709
- const relative = (file)=>toPosix(external_node_path_default().relative(projectRoot, file));
3710
- for (const file of codeFiles.keys()){
3711
- const from = moves.get(file) ?? file;
3712
- for (const imported of importsOf(file)){
3713
- const to = movedPath(imported);
3714
- if (moves.has(file) || to) {
3715
- if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
3716
- relative(from),
3717
- relative(to ?? imported)
3718
- ]);
3726
+ const vitestConfig = (rootFolder, inlineHandlersNext)=>{
3727
+ const folder = (subpath)=>JSON.stringify(external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), subpath));
3728
+ const server = inlineHandlersNext ? `,
3729
+ server: {
3730
+ deps: {
3731
+ // Imports \`next/headers\` without an extension, which only a bundler can resolve
3732
+ inline: ['@domain-first/handlers-next']
3719
3733
  }
3720
- }
3734
+ }` : '';
3735
+ return `import { configDefaults, defineConfig } from 'vitest/config';
3736
+
3737
+ export default defineConfig({
3738
+ resolve: {
3739
+ tsconfigPaths: true
3740
+ },
3741
+ test: {
3742
+ // Playwright runs end-to-end specs, test:integration runs integration ones
3743
+ exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
3744
+ coverage: {
3745
+ provider: 'v8',
3746
+ include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
3747
+ exclude: [
3748
+ '**/*.spec.ts',
3749
+ ${folder('shared-kernel/infrastructure/**')},
3750
+ ${folder('bounded-contexts/*/infrastructure/**')},
3751
+ ${folder('bounded-contexts/*/presentation/rest/**')},
3752
+ ${folder('shared-kernel/wiring/**')},
3753
+ ${folder('bounded-contexts/*/wiring/**')}
3754
+ ],
3755
+ reporter: [['text', { skipFull: true }], 'html']
3756
+ }${server}
3721
3757
  }
3722
- for (const [file] of barrelImporters)if (!isolationAllows(rootFolderPath, file, newMainFile)) violations.push([
3723
- relative(file),
3724
- relative(newMainFile)
3725
- ]);
3726
- if (violations.length) return {
3727
- violations
3758
+ });
3759
+ `;
3760
+ };
3761
+ const addVitest = async ()=>{
3762
+ const config = config_file_ConfigFile.Instance.data;
3763
+ if (config_file_ConfigFile.backend.testingLibrary && 'vitest' !== config_file_ConfigFile.backend.testingLibrary && !await interaction_confirm({
3764
+ key: 'replaceTestingLibrary',
3765
+ requestRequired: true,
3766
+ message: `Replace testing library "${config_file_ConfigFile.backend.testingLibrary}" with vitest for generated tests?`,
3767
+ default: false
3768
+ })) return [];
3769
+ const root = new project_root_ProjectRoot().path;
3770
+ const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
3771
+ const manifest = JSON.parse(manifestFile.data);
3772
+ const dependencies = {
3773
+ ...manifest.dependencies,
3774
+ ...manifest.devDependencies
3728
3775
  };
3729
- const word = (form)=>`(?<![\\w$])${escapeRegExp(form)}(?![\\w$])`;
3730
- const oldCore = layout.core(oldNaming.ClassName);
3731
- const newCore = layout.core(newNaming.ClassName);
3732
- const prefixes = [
3733
- ...unit.labels.map((label)=>new UnknownFormatNaming(label).ClassName),
3734
- ...layout.wired ? [
3735
- 'wire'
3736
- ] : []
3737
- ];
3738
- const renames = [
3739
- {
3740
- pattern: new RegExp(`(?<![\\w$])(${prefixes.map(escapeRegExp).join('|')})?${escapeRegExp(oldCore)}(?![\\w$])`, 'g'),
3741
- to: `$1${newCore}`
3742
- },
3743
- {
3744
- pattern: new RegExp(word(lowerFirst(oldCore)), 'g'),
3745
- to: lowerFirst(newCore)
3746
- },
3747
- {
3748
- pattern: new RegExp(`(describe\\(\\s*['"\`])${escapeRegExp(oldNaming.withSpaces)}(?=[ '"\`])`, 'g'),
3749
- to: `$1${newNaming.withSpaces}`,
3750
- movedOnly: true
3776
+ const selected = await addPackageScripts(manifestFile, vitestScripts);
3777
+ const configFile = new file_system_File(external_node_path_default().join(root, 'vitest.config.ts'));
3778
+ const content = vitestConfig(config.project.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
3779
+ if (!configFile.exists || configFile.data !== content) configFile.data = content;
3780
+ if ('vitest' !== config_file_ConfigFile.backend.testingLibrary) config_file_ConfigFile.update({
3781
+ backend: {
3782
+ ...config_file_ConfigFile.backend,
3783
+ testingLibrary: 'vitest'
3751
3784
  }
3752
- ];
3753
- if ('aggregate' === unit.kind) renames.push({
3754
- pattern: new RegExp(word(oldNaming.ClassName), 'g'),
3755
- to: newNaming.ClassName
3756
- }, {
3757
- pattern: new RegExp(word(oldNaming.variableName), 'g'),
3758
- to: newNaming.variableName,
3759
- movedOnly: true
3760
- });
3761
- if ('entity' === unit.kind || 'value-object' === unit.kind) renames.push({
3762
- pattern: new RegExp(word(oldNaming.variableName), 'g'),
3763
- to: newNaming.variableName,
3764
- movedOnly: true
3765
3785
  });
3766
- const oldSection = new UnknownFormatNaming(plural(unit.name));
3767
- const newSection = new UnknownFormatNaming(plural(target.name));
3768
- const renamesSection = 'aggregate' === unit.kind && unit.name !== target.name;
3769
- const everyFile = (content)=>renamesSection ? content.replace(new RegExp(`(InMemoryDbInfrastructureService\\[\\s*['"])${oldSection.variableName}(?=['"]\\s*\\])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(inMemoryDbInfrastructureService\\s*\\.\\s*)${oldSection.variableName}(?![\\w$])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(?<![\\w$.])${oldSection.variableName}(\\s*=\\s*this\\.section<[^>]*>\\(\\s*['"])${oldSection.fileName.toUpperCase()}(?=['"])`, 'g'), `${newSection.variableName}$1${newSection.fileName.toUpperCase()}`) : content;
3770
- const plan = stageModuleMove({
3771
- projectRoot,
3772
- stopAt: rootFolderPath,
3773
- moves,
3774
- movedPath,
3775
- rename: (content, { moved })=>renames.reduce((result, { pattern, to, movedOnly })=>movedOnly && !moved ? result : result.replace(pattern, to), content),
3776
- everyFile
3777
- });
3778
- if (leavesAggregate && oldAggregateFolder) {
3779
- const indexFile = new file_system_File(external_node_path_default().join(oldAggregateFolder, 'index.ts'));
3780
- const exportLine = /^export\s+\*\s+from\s+(['"])([^'"\n]+)\1;?\s*$/;
3781
- indexFile.update(indexFile.data.split('\n').filter((line)=>{
3782
- const specifier = line.match(exportLine)?.[2];
3783
- return !specifier || external_node_path_default().resolve(external_node_path_default().dirname(indexFile.path), specifier) !== newMainFile.replace(codeExtension, '');
3784
- }).join('\n'));
3785
- if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
3786
- for (const [file] of barrelImporters){
3787
- const importer = new file_system_File(file);
3788
- let content = importer.data;
3789
- for (const match of content.matchAll(namedImports)){
3790
- const [statement, typeOnly = '', names, quote, specifier] = match;
3791
- if (!isOldBarrel(resolve(specifier, file)?.resolved)) continue;
3792
- const items = names.split(',').map((item)=>item.trim()).filter((item)=>!!item);
3793
- const own = new RegExp(`^(?:type\\s+)?${newNaming.ClassName}(?:\\s+as\\s+[\\w$]+)?$`);
3794
- const moved = items.filter((item)=>own.test(item));
3795
- if (!moved.length) continue;
3796
- const rest = items.filter((item)=>!own.test(item));
3797
- const direct = `import ${typeOnly}{ ${moved.join(', ')} } from ${quote}${projectRelative(file, newMainFile)}${quote}`;
3798
- content = content.replace(statement, rest.length ? `import ${typeOnly}{ ${rest.join(', ')} } from ${quote}${specifier}${quote}\n${direct}` : direct);
3799
- }
3800
- importer.update(content);
3786
+ addGitignoreEntry(root, '/coverage/');
3787
+ const missing = [
3788
+ 'vitest',
3789
+ '@vitest/coverage-v8'
3790
+ ].filter((name)=>!dependencies[name]);
3791
+ return [
3792
+ ...missing.length ? [
3793
+ `npm install --save-dev ${missing.join(' ')}`
3794
+ ] : [],
3795
+ ...describeScripts(selected, {
3796
+ test: 'run unit tests',
3797
+ 'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
3798
+ })
3799
+ ];
3800
+ };
3801
+ const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
3802
+ const mergeInstallCommands = (commands)=>{
3803
+ const runtime = new Set();
3804
+ const development = new Set();
3805
+ const rest = [];
3806
+ for (const command of commands){
3807
+ const match = installCommand.exec(command);
3808
+ if (!match) {
3809
+ rest.push(command);
3810
+ continue;
3801
3811
  }
3812
+ for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
3802
3813
  }
3803
- if (target.aggregate && (target.aggregate !== unit.aggregate || target.ownerPath !== unit.ownerPath)) {
3804
- const kindFolder = 'entity' === unit.kind ? 'entities' : 'value-objects';
3805
- const indexFile = new file_system_File(external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.aggregate, 'index.ts'));
3806
- indexFile.addLineIfMissing(`export * from './${kindFolder}/${target.name}.${unit.kind}'`);
3807
- if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
3808
- }
3809
- return plan;
3814
+ const devOnly = [
3815
+ ...development
3816
+ ].filter((name)=>!runtime.has(name));
3817
+ return [
3818
+ ...runtime.size ? [
3819
+ `npm install ${[
3820
+ ...runtime
3821
+ ].join(' ')}`
3822
+ ] : [],
3823
+ ...devOnly.length ? [
3824
+ `npm install --save-dev ${devOnly.join(' ')}`
3825
+ ] : [],
3826
+ ...rest
3827
+ ];
3810
3828
  };
3811
- const projectRelative = (fromFile, toFile)=>{
3812
- const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile.replace(codeExtension, '')));
3813
- return relative.startsWith('.') ? relative : `./${relative}`;
3829
+ const printNextSteps = (nextSteps)=>{
3830
+ const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
3831
+ const commands = mergeInstallCommands(nextSteps.filter(isCommand));
3832
+ const notes = nextSteps.filter((line)=>!isCommand(line));
3833
+ const sections = [];
3834
+ if (commands.length) sections.push([
3835
+ 'Run this command to install the required dependencies:',
3836
+ (0, external_node_util_namespaceObject.styleText)([
3837
+ 'bold',
3838
+ 'cyan'
3839
+ ], commands.join(' && '))
3840
+ ].join('\n'));
3841
+ if (notes.length) sections.push([
3842
+ 'Additional information:',
3843
+ ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + (0, external_node_util_namespaceObject.styleText)([
3844
+ 'bold',
3845
+ 'cyan'
3846
+ ], path)))
3847
+ ].join('\n'));
3848
+ if (sections.length) console.log(sections.join('\n\n'));
3814
3849
  };
3815
- const importSpecifier = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"\n]+)\1/g;
3816
- const backend_module_move_importLine = /^\s*(?:import|export)\b[^'"\n]*\bfrom\s*(['"])([^'"\n]+)\1;?\s*$/;
3817
- const deleteBackendUnit = (projectRoot, rootFolderPath, unit)=>{
3818
- const files = [
3819
- ...unitMoves(unit, unit).keys()
3820
- ];
3821
- const fileSet = new Set(files);
3822
- const stems = new Set(files.map((file)=>file.replace(codeExtension, '')));
3823
- const aggregateFolder = 'aggregate' === unit.kind ? external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name) : void 0;
3824
- const parentAggregate = unit.aggregate ? external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.aggregate) : void 0;
3825
- const isUnit = (resolved)=>stems.has(resolved) || !!aggregateFolder && (resolved === aggregateFolder || resolved.startsWith(`${aggregateFolder}${external_node_path_default().sep}`));
3826
- const isParentBarrel = (resolved)=>!!parentAggregate && (resolved === parentAggregate || resolved === external_node_path_default().join(parentAggregate, 'index'));
3827
- const { codeFiles, resolve } = projectImports(projectRoot);
3828
- const resolved = (specifier, file)=>resolve(specifier, file)?.resolved;
3829
- const withoutUnitImports = (content, file)=>content.split('\n').filter((line)=>{
3830
- const specifier = line.match(backend_module_move_importLine)?.[2];
3831
- const target = specifier && resolved(specifier, file);
3832
- return !(target && isUnit(target));
3833
- }).join('\n');
3834
- const cleaned = new Map();
3835
- const inMemoryDb = inMemoryDbFile(rootFolderPath);
3836
- if ('aggregate' === unit.kind && codeFiles.has(inMemoryDb)) {
3837
- const section = new UnknownFormatNaming(plural(unit.name));
3838
- const original = codeFiles.get(inMemoryDb);
3839
- const content = withoutUnitImports(original.replace(new RegExp(`^[ \\t]*${escapeRegExp(section.variableName)}\\s*=\\s*this\\.section<[^\\n]*\\n?`, 'm'), ''), inMemoryDb);
3840
- if (content !== original) cleaned.set(inMemoryDb, content);
3841
- }
3842
- if (parentAggregate) {
3843
- const index = external_node_path_default().join(parentAggregate, 'index.ts');
3844
- const original = codeFiles.get(index);
3845
- if (void 0 !== original) {
3846
- const content = withoutUnitImports(original, index);
3847
- if (content !== original) cleaned.set(index, content);
3850
+ const savePendingChanges = async ()=>{
3851
+ assertAnswersConsumed();
3852
+ const overwrittenFiles = filesToOverwrite({
3853
+ changedOnly: isNonInteractive()
3854
+ });
3855
+ if (isNonInteractive() && overwrittenFiles.length && !answerFor('overwrite', false)) throw new RequestError('OVERWRITE_REQUIRED', 'Set overwrite to true to replace existing files.', {
3856
+ files: overwrittenFiles.map((file)=>external_node_path_default().relative(new project_root_ProjectRoot().path, file).split(external_node_path_default().sep).join('/'))
3857
+ });
3858
+ if (overwrittenFiles.length) {
3859
+ const root = new project_root_ProjectRoot().path;
3860
+ report('These files already exist and will be overwritten:');
3861
+ for (const filePath of overwrittenFiles)report(` ${external_node_path_default().relative(root, filePath)}`);
3862
+ const overwrite = await interaction_confirm({
3863
+ key: 'overwrite',
3864
+ message: 'Overwrite them?',
3865
+ default: false
3866
+ });
3867
+ if (!overwrite) {
3868
+ discardPendingChanges();
3869
+ report('Cancelled: nothing was written.');
3870
+ return false;
3848
3871
  }
3849
3872
  }
3850
- const ClassName = new UnknownFormatNaming(unit.name).ClassName;
3851
- const namedImports = /import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\2/g;
3852
- const usedBy = [];
3853
- const relative = (file)=>toPosix(external_node_path_default().relative(projectRoot, file));
3854
- for (const [file, original] of codeFiles){
3855
- if (fileSet.has(file)) continue;
3856
- const content = cleaned.get(file) ?? original;
3857
- for (const [, , specifier] of content.matchAll(importSpecifier)){
3858
- const target = resolved(specifier, file);
3859
- if (target && isUnit(target)) usedBy.push([
3860
- relative(file),
3861
- relative(target)
3862
- ]);
3863
- }
3864
- for (const [, names, , specifier] of content.matchAll(namedImports)){
3865
- const target = resolved(specifier, file);
3866
- if (target && isParentBarrel(target) && new RegExp(`(?<![\\w$])${ClassName}(?![\\w$])`).test(names)) usedBy.push([
3867
- relative(file),
3868
- `${relative(target)} (${ClassName})`
3869
- ]);
3870
- }
3873
+ writePendingChanges();
3874
+ return true;
3875
+ };
3876
+ const withHandlersRest = ()=>config_file_ConfigFile.Instance.data.backend?.domainFirstPackages.includes('@domain-first/handlers-rest') ?? false;
3877
+ const created = (...segments)=>new file_system_File(external_node_path_default().join(new project_root_ProjectRoot().path, ...segments)).exists;
3878
+ const createdInRoot = (...segments)=>created(config_file_ConfigFile.Instance.data.project.rootFolder, ...segments);
3879
+ const integrationIds = [
3880
+ 'storybook',
3881
+ 'rest-endpoint-generator',
3882
+ 'in-memory-db',
3883
+ 'prisma',
3884
+ 'vitest',
3885
+ 'playwright',
3886
+ 'testcontainers',
3887
+ 'openapi',
3888
+ 'orval'
3889
+ ];
3890
+ const integrations = [
3891
+ {
3892
+ id: 'storybook',
3893
+ name: 'Storybook (React + Vite)',
3894
+ group: 'frontend',
3895
+ run: storybook_addStorybook,
3896
+ applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
3897
+ },
3898
+ {
3899
+ id: 'rest-endpoint-generator',
3900
+ name: 'REST endpoint generator',
3901
+ group: 'backend',
3902
+ run: addRestEndpointGenerator,
3903
+ available: ()=>withHandlersRest(),
3904
+ applied: restEndpointGeneratorApplied
3905
+ },
3906
+ {
3907
+ id: 'in-memory-db',
3908
+ name: 'In-memory DB',
3909
+ group: 'backend',
3910
+ run: addInMemoryDb,
3911
+ applied: inMemoryDbApplied
3912
+ },
3913
+ {
3914
+ id: 'prisma',
3915
+ name: 'Prisma 8 (PostgreSQL, RC)',
3916
+ group: 'backend',
3917
+ run: addPrisma,
3918
+ applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
3919
+ },
3920
+ {
3921
+ id: 'vitest',
3922
+ name: 'Vitest',
3923
+ group: 'backend',
3924
+ run: addVitest,
3925
+ applied: ()=>created('vitest.config.ts')
3926
+ },
3927
+ {
3928
+ id: 'playwright',
3929
+ name: 'Playwright',
3930
+ group: 'frontend',
3931
+ run: addPlaywright,
3932
+ applied: ()=>created('playwright.config.ts')
3933
+ },
3934
+ {
3935
+ id: 'testcontainers',
3936
+ name: 'Integration tests (Testcontainers, PostgreSQL)',
3937
+ group: 'backend',
3938
+ run: addTestcontainers,
3939
+ applied: ()=>created('specs/integration/vitest.config.ts')
3940
+ },
3941
+ {
3942
+ id: 'openapi',
3943
+ name: 'OpenAPI',
3944
+ group: 'backend',
3945
+ run: addOpenapi,
3946
+ available: ()=>withHandlersRest(),
3947
+ applied: ()=>created(openapiScriptPath)
3948
+ },
3949
+ {
3950
+ id: 'orval',
3951
+ name: 'Orval (API client)',
3952
+ group: 'frontend',
3953
+ run: addOrval,
3954
+ available: ()=>withHandlersRest(),
3955
+ applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
3871
3956
  }
3872
- if (usedBy.length) return {
3873
- usedBy
3874
- };
3875
- for (const file of files)new file_system_File(file).delete(rootFolderPath);
3876
- for (const [file, content] of cleaned)new file_system_File(file).update(content);
3877
- return {
3878
- deleted: files,
3879
- updated: [
3880
- ...cleaned.keys()
3881
- ]
3957
+ ];
3958
+ const addIntegration = async ({ save = true } = {})=>{
3959
+ const available = integrations.filter(({ group, available })=>('backend' !== group || Boolean(config_file_ConfigFile.Instance.data.backend)) && (available?.() ?? true)).map((value)=>({
3960
+ value,
3961
+ applied: value.applied()
3962
+ }));
3963
+ const section = (title, applied)=>{
3964
+ const items = [
3965
+ 'backend',
3966
+ 'frontend'
3967
+ ].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
3968
+ return items.length ? [
3969
+ new prompts_namespaceObject.Separator(title),
3970
+ ...items.map(({ value })=>({
3971
+ name: `${value.name} · ${value.group}`,
3972
+ value
3973
+ }))
3974
+ ] : [];
3882
3975
  };
3976
+ const choices = [
3977
+ ...section('New integrations', false),
3978
+ ...section('Already applied (select to reapply)', true)
3979
+ ];
3980
+ const selected = await interaction_checkbox({
3981
+ key: 'integrations',
3982
+ id: (integration)=>integration.id,
3983
+ message: 'Integrations:',
3984
+ choices,
3985
+ pageSize: choices.length
3986
+ });
3987
+ const nextSteps = [];
3988
+ for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
3989
+ if (save && await savePendingChanges()) printNextSteps(nextSteps);
3990
+ return nextSteps;
3883
3991
  };
3884
- const contractKinds = [
3885
- 'aggregate',
3886
- 'command',
3887
- 'query',
3888
- 'port'
3889
- ];
3890
- const implementations_withWiring = ()=>config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
3891
- const withHandlers = ()=>config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers');
3892
- const contractFile = (unit)=>'aggregate' === unit.kind ? `domain/aggregates/${unit.name}/${unit.name}-repository.ts` : kindLayouts[unit.kind].files(unit, [])[0];
3893
- const findContracts = (ownerPath)=>findBackendUnits(ownerPath).filter((unit)=>contractKinds.includes(unit.kind) && external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, contractFile(unit))));
3894
- const implementationWireName = (label)=>`wire${new UnknownFormatNaming(label).ClassName}Implementation`;
3895
- const contractClassName = (unit)=>kindLayouts[unit.kind].core(new UnknownFormatNaming(unit.name).ClassName);
3896
- const implementationClassName = (unit, label)=>`${new UnknownFormatNaming(label).ClassName}${contractClassName(unit)}`;
3897
- const implementationFile = (unit, label)=>{
3898
- const { implementations } = kindLayouts[unit.kind];
3899
- return kindLayouts[unit.kind].files(unit, [
3900
- label
3901
- ]).find((file)=>file.startsWith(`${implementations}/`));
3992
+ const integrationDescriptions = ()=>integrations.map((integration)=>({
3993
+ id: integration.id,
3994
+ name: integration.name,
3995
+ group: integration.group,
3996
+ available: ('backend' !== integration.group || Boolean(config_file_ConfigFile.Instance.data.backend)) && (integration.available?.() ?? true)
3997
+ }));
3998
+ const agent_requests_name = implementationLabelSchema;
3999
+ const agent_requests_nestedName = external_zod_default().string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*)*$/);
4000
+ const agent_requests_id = external_zod_default().string().min(1);
4001
+ const agent_requests_implementation = external_zod_default().strictObject({
4002
+ type: agent_requests_name,
4003
+ save: external_zod_default().boolean().optional().describe('Remember this ordinary type for future runs. Default: false.'),
4004
+ integrationTests: external_zod_default().boolean().optional().describe('For a newly entered primary type, with the Testcontainers integration and wire: whether its implementations get integration specs. Default: true. With save: true, remembered for the type. Not allowed otherwise.')
4005
+ });
4006
+ const agent_requests_dependencies = external_zod_default().record(external_zod_default().string().regex(/^[A-Z][A-Za-z0-9]*$/), external_zod_default().array(agent_requests_id)).describe('Implementation/class name -> exact module IDs from --describe. Omitted entries keep suggested dependencies; [] selects none.');
4007
+ const common = {
4008
+ overwrite: external_zod_default().boolean().optional(),
4009
+ dryRun: external_zod_default().boolean().optional()
3902
4010
  };
3903
- const contractWireFile = (unit)=>kindLayouts[unit.kind].files(unit, []).find((file)=>file.startsWith('wiring/'));
3904
- const handlerImplementation = (ContractName, ClassName, contractImport)=>withHandlers() ? `
3905
- import { defineHandler } from '@domain-first/handlers'
3906
- import { ${ContractName} } from '${contractImport}'
3907
-
3908
- export class ${ClassName} extends ${ContractName} {
3909
- constructor() {
3910
- super()
3911
- }
3912
-
3913
- handle = defineHandler({
3914
- inputSchema: ${ContractName}.inputSchema,
3915
- outputSchema: ${ContractName}.outputSchema,
3916
- handler: async (input) => {
3917
- return {}
3918
- }
4011
+ const agent_requests_owner = {
4012
+ context: agent_requests_name.describe('A bounded-context name, or shared-kernel.')
4013
+ };
4014
+ const agent_requests_wired = {
4015
+ dependencies: agent_requests_dependencies.optional()
4016
+ };
4017
+ const agent_requests_implementations = {
4018
+ implementation: agent_requests_implementation,
4019
+ testImplementation: agent_requests_implementation.optional(),
4020
+ ...agent_requests_wired
4021
+ };
4022
+ const named = {
4023
+ ...common,
4024
+ ...agent_requests_owner,
4025
+ name: agent_requests_name
4026
+ };
4027
+ const agent_requests_operation = (value, shape)=>external_zod_default().strictObject({
4028
+ operation: external_zod_default().literal(value),
4029
+ ...shape
4030
+ });
4031
+ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operation', [
4032
+ agent_requests_operation('bounded-context', {
4033
+ ...common,
4034
+ name: agent_requests_name.refine((value)=>'shared-kernel' !== value, 'shared-kernel is reserved for the Shared Kernel.')
4035
+ }),
4036
+ agent_requests_operation('aggregate', {
4037
+ ...named,
4038
+ withRepository: external_zod_default().boolean().optional(),
4039
+ implementation: agent_requests_implementation.optional(),
4040
+ testImplementation: agent_requests_implementation.optional(),
4041
+ ...agent_requests_wired
4042
+ }),
4043
+ agent_requests_operation('entity', {
4044
+ ...named,
4045
+ aggregate: agent_requests_name.optional()
4046
+ }),
4047
+ agent_requests_operation('value-object', {
4048
+ ...named,
4049
+ aggregate: agent_requests_name.optional()
4050
+ }),
4051
+ agent_requests_operation('error', {
4052
+ ...named,
4053
+ namespace: agent_requests_name.optional()
4054
+ }),
4055
+ agent_requests_operation('error-namespace', named),
4056
+ agent_requests_operation('domain-service', {
4057
+ ...named,
4058
+ ...agent_requests_wired
4059
+ }),
4060
+ agent_requests_operation('application-service', {
4061
+ ...named,
4062
+ ...agent_requests_wired
4063
+ }),
4064
+ agent_requests_operation('infrastructure-service', {
4065
+ ...named,
4066
+ integrationSpec: external_zod_default().boolean().optional().describe('With the Testcontainers integration and wire: whether the service gets an integration spec. Default: false. Not allowed otherwise.'),
4067
+ ...agent_requests_wired
4068
+ }),
4069
+ agent_requests_operation('helper', {
4070
+ ...common,
4071
+ ...agent_requests_owner,
4072
+ name: agent_requests_nestedName.describe('Kebab-case, folders split by "/": mappers/social-network-type.'),
4073
+ implementationType: agent_requests_name.describe('A saved or system implementation type: a helper belongs to one.')
4074
+ }),
4075
+ agent_requests_operation('presentation-service', {
4076
+ ...named,
4077
+ ...agent_requests_wired
4078
+ }),
4079
+ agent_requests_operation('use-case', {
4080
+ ...named,
4081
+ ...agent_requests_wired
4082
+ }),
4083
+ agent_requests_operation('command', {
4084
+ ...named,
4085
+ ...agent_requests_implementations
4086
+ }),
4087
+ agent_requests_operation('query', {
4088
+ ...named,
4089
+ ...agent_requests_implementations
4090
+ }),
4091
+ agent_requests_operation('port', {
4092
+ ...named,
4093
+ ...agent_requests_implementations
4094
+ }),
4095
+ agent_requests_operation('implementation', {
4096
+ ...common,
4097
+ ...agent_requests_owner,
4098
+ contract: agent_requests_id.describe('Exact contract ID from --describe.'),
4099
+ implementation: agent_requests_implementation,
4100
+ environments: external_zod_default().array(agent_requests_name).min(1).optional().describe('Required when the contract wire is envBranchedWire; omit it otherwise.'),
4101
+ ...agent_requests_wired
4102
+ }),
4103
+ agent_requests_operation('endpoint', {
4104
+ ...common,
4105
+ ...agent_requests_owner,
4106
+ controller: agent_requests_name.optional().describe('Omit for the context-root controller (root): `/<context>/<path>`.'),
4107
+ method: external_zod_default()["enum"]([
4108
+ 'get',
4109
+ 'post',
4110
+ 'put',
4111
+ 'patch',
4112
+ 'delete'
4113
+ ]),
4114
+ path: external_zod_default().string().regex(/^(?:\/?(?:[a-zA-Z0-9_-]+|:[a-zA-Z][a-zA-Z0-9_]*))*\/?$/),
4115
+ handler: agent_requests_id.optional().describe('Exact handler module ID from --describe. Required when the context has wired queries, commands or use cases; omit it otherwise.')
4116
+ }),
4117
+ agent_requests_operation('wire-dependency', {
4118
+ ...common,
4119
+ ...agent_requests_owner,
4120
+ module: agent_requests_id.describe('Exact wiring target ID, including implementation class, from --describe.'),
4121
+ dependencies: agent_requests_dependencies
4122
+ }),
4123
+ agent_requests_operation('delete', {
4124
+ ...common,
4125
+ ...agent_requests_owner,
4126
+ module: agent_requests_id.describe('Exact unit ID from --describe. Refused while other files use it.')
4127
+ }),
4128
+ agent_requests_operation('move', {
4129
+ ...common,
4130
+ ...agent_requests_owner,
4131
+ module: agent_requests_id.describe('Exact unit ID from --describe.'),
4132
+ targetContext: agent_requests_name.optional(),
4133
+ name: agent_requests_name.optional(),
4134
+ aggregate: agent_requests_name.optional()
4135
+ })
4136
+ ]);
4137
+ const reactRequestSchema = external_zod_default().discriminatedUnion('operation', [
4138
+ agent_requests_operation('page', {
4139
+ ...common,
4140
+ name: agent_requests_nestedName
4141
+ }),
4142
+ agent_requests_operation('widget', {
4143
+ ...common,
4144
+ name: agent_requests_nestedName,
4145
+ widgetType: external_zod_default()["enum"]([
4146
+ 'monolithic',
4147
+ 'separated',
4148
+ 'headless'
4149
+ ]).optional()
4150
+ }),
4151
+ agent_requests_operation('ui-kit-component', {
4152
+ ...common,
4153
+ name: agent_requests_name
4154
+ }),
4155
+ agent_requests_operation('shared-hook', {
4156
+ ...common,
4157
+ name: agent_requests_name
4158
+ }),
4159
+ agent_requests_operation('move-page', {
4160
+ ...common,
4161
+ module: agent_requests_nestedName,
4162
+ name: agent_requests_nestedName,
4163
+ moveRoute: external_zod_default().boolean().optional().describe('With Next.js and a route at the page path: move it too (default true). Omit it without such a route.')
4164
+ }),
4165
+ agent_requests_operation('delete-page', {
4166
+ ...common,
4167
+ module: agent_requests_nestedName,
4168
+ deleteRoute: external_zod_default().boolean().optional().describe("With Next.js and the page's own route: delete it too (default true). Omit it without such a route.")
4169
+ }),
4170
+ agent_requests_operation('delete-widget', {
4171
+ ...common,
4172
+ module: agent_requests_nestedName
4173
+ }),
4174
+ agent_requests_operation('move-ui-kit-component', {
4175
+ ...common,
4176
+ module: agent_requests_name,
4177
+ name: agent_requests_name
4178
+ }),
4179
+ agent_requests_operation('move-shared-hook', {
4180
+ ...common,
4181
+ module: agent_requests_name,
4182
+ name: agent_requests_name
4183
+ }),
4184
+ agent_requests_operation('delete-ui-kit-component', {
4185
+ ...common,
4186
+ module: agent_requests_name
4187
+ }),
4188
+ agent_requests_operation('delete-shared-hook', {
4189
+ ...common,
4190
+ module: agent_requests_name
4191
+ }),
4192
+ agent_requests_operation('move-widget', {
4193
+ ...common,
4194
+ module: agent_requests_nestedName,
4195
+ name: agent_requests_nestedName
3919
4196
  })
3920
- }
3921
- `.trim() : `
3922
- import { ${ContractName} } from '${contractImport}'
3923
-
3924
- export class ${ClassName} extends ${ContractName} {
3925
- constructor() {
3926
- super()
3927
- }
3928
- }
3929
- `.trim();
3930
- const createImplementation = (ownerFolder, unit, label)=>{
3931
- const naming = new UnknownFormatNaming(unit.name);
3932
- const ContractName = contractClassName(unit);
3933
- const className = implementationClassName(unit, label);
3934
- const [folder, fileName] = [
3935
- external_node_path_default().dirname(implementationFile(unit, label)),
3936
- external_node_path_default().basename(implementationFile(unit, label))
3937
- ];
3938
- const implementationFolder = ownerFolder.subitem(folder.split('/'));
3939
- const inMemoryDb = !implementations_withWiring() && usesInMemoryDb(label);
3940
- switch(unit.kind){
3941
- case 'aggregate':
3942
- {
3943
- const contractImport = `../../../domain/aggregates/${unit.name}`;
3944
- if (inMemoryDb) {
3945
- const section = addInMemoryDbSection(naming, ownerFolder.subitem([
3946
- 'domain',
3947
- 'aggregates',
3948
- unit.name
3949
- ]).path);
3950
- const file = implementationFolder.createFile(fileName, `
3951
- ${inMemoryDbTypeImport(implementationFolder.subitem([
3952
- fileName
3953
- ]).path)}
3954
- import { ${ContractName} } from '${contractImport}'
3955
-
3956
- export class ${className} implements ${ContractName} {
3957
- ${inMemoryDbSectionMembers(section, false)}
3958
- }
3959
- `.trim());
3960
- return {
3961
- file,
3962
- className
3963
- };
3964
- }
3965
- const file = implementationFolder.createFile(fileName, `
3966
- import { ${ContractName} } from '${contractImport}'
3967
-
3968
- export class ${className} implements ${ContractName} {
3969
- constructor() {}
3970
- }
3971
-
3972
- `.trim());
3973
- return {
3974
- file,
3975
- className
3976
- };
3977
- }
3978
- case 'command':
3979
- case 'query':
3980
- {
3981
- const folderName = 'command' === unit.kind ? 'commands' : 'queries';
3982
- const file = implementationFolder.createFile(fileName, handlerImplementation(ContractName, className, `../../../application/${folderName}/${naming.fileName}-${unit.kind}`));
3983
- if (inMemoryDb) injectInMemoryDb(file, className);
3984
- return {
3985
- file,
3986
- className
3987
- };
3988
- }
3989
- case 'port':
3990
- {
3991
- const file = implementationFolder.createFile(fileName, `
3992
- import { ${ContractName} } from '../../../application/ports/${naming.fileName}'
3993
-
3994
- export class ${className} extends ${ContractName} {
3995
-
3996
- }
3997
- `.trim());
3998
- return {
3999
- file,
4000
- className
4001
- };
4002
- }
4003
- default:
4004
- throw new Error(`${unit.kind} has no implementations`);
4005
- }
4006
- };
4007
- const inMemoryRepositoryWiring = (ownerFolder, unit, wireFile)=>(implementation, dependency)=>{
4008
- if ('aggregate' !== unit.kind || !isInMemoryDb(dependency)) return false;
4009
- keepInMemoryDbSection(new file_system_File(implementation.file), addInMemoryDbSection(new UnknownFormatNaming(unit.name), ownerFolder.subitem([
4010
- 'domain',
4011
- 'aggregates',
4012
- unit.name
4013
- ]).path));
4014
- wireInMemoryDb(wireFile, implementation.className);
4015
- return true;
4016
- };
4197
+ ]);
4198
+ const agent_requests_relativePath = external_zod_default().string().regex(/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/).refine((value)=>!value.split('/').some((part)=>'.' === part || '..' === part), 'Use a project-relative path without . or .. segments.');
4199
+ const integrationRequestSchema = agent_requests_operation('add', {
4200
+ ...common,
4201
+ integrations: external_zod_default().array(external_zod_default()["enum"](integrationIds)).min(1),
4202
+ nextAdapter: external_zod_default().boolean().optional(),
4203
+ configureReact: external_zod_default().boolean().optional(),
4204
+ replaceTestingLibrary: external_zod_default().boolean().optional(),
4205
+ integrationTestTypes: external_zod_default().array(agent_requests_name).optional().describe('testcontainers with wire: saved primary implementation types whose implementations get integration specs. Omitted: the configured list stays.'),
4206
+ withService: external_zod_default().boolean().optional(),
4207
+ routePrefix: external_zod_default().string().regex(/^\/?[a-zA-Z0-9_/-]*$/).optional(),
4208
+ openapiPath: agent_requests_relativePath.optional(),
4209
+ withExtractor: external_zod_default().boolean().optional(),
4210
+ swaggerPage: external_zod_default().boolean().optional(),
4211
+ targets: external_zod_default().array(external_zod_default()["enum"]([
4212
+ 'hooks',
4213
+ 'client'
4214
+ ])).min(1).optional(),
4215
+ scriptConflicts: external_zod_default().record(agent_requests_id, external_zod_default()["enum"]([
4216
+ 'keep',
4217
+ 'replace',
4218
+ 'rename'
4219
+ ])).optional(),
4220
+ scriptNames: external_zod_default().record(agent_requests_id, external_zod_default().string().regex(/^[a-zA-Z0-9:_-]+$/)).optional()
4221
+ });
4222
+ const requestSchemaFor = (command)=>({
4223
+ 'df-scaffold': scaffoldRequestSchema,
4224
+ 'df-react': reactRequestSchema,
4225
+ 'df-integration': integrationRequestSchema
4226
+ })[command];
4017
4227
  const reactKindLayouts = {
4018
4228
  page: {
4019
4229
  folder: 'pages',
@@ -4607,16 +4817,23 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
4607
4817
  if (!implementation) throw new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
4608
4818
  field: key
4609
4819
  });
4820
+ if ('test' === purpose && void 0 !== implementation.integrationTests) throw new RequestError('UNUSED_PARAMETERS', 'Test implementations get no integration specs.', {
4821
+ fields: [
4822
+ `${key}.integrationTests`
4823
+ ]
4824
+ });
4610
4825
  const valid = validateLabel(implementation.type);
4611
4826
  if (true !== valid) throw new RequestError('INVALID_IMPLEMENTATION', valid, {
4612
4827
  field: key
4613
4828
  });
4614
4829
  const label = implementation.type.trim();
4615
4830
  const saveForFutureUse = implementation.save ?? false;
4831
+ const entered = !choices.some((choice)=>choice.value === label);
4616
4832
  if (remember && saveForFutureUse && !system.some((choice)=>choice.value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
4617
4833
  return {
4618
4834
  label,
4619
- saveForFutureUse
4835
+ saveForFutureUse,
4836
+ entered
4620
4837
  };
4621
4838
  }
4622
4839
  const type = await interaction_select({
@@ -4632,7 +4849,8 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
4632
4849
  });
4633
4850
  if ('string' == typeof type) return {
4634
4851
  label: type,
4635
- saveForFutureUse: true
4852
+ saveForFutureUse: true,
4853
+ entered: false
4636
4854
  };
4637
4855
  const saveForFutureUse = type !== enterImplementationTypeOnce;
4638
4856
  const label = (await interaction_input({
@@ -4643,7 +4861,8 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
4643
4861
  if (saveForFutureUse && remember && !choices.some(({ value })=>value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
4644
4862
  return {
4645
4863
  label,
4646
- saveForFutureUse
4864
+ saveForFutureUse,
4865
+ entered: !choices.some(({ value })=>value === label)
4647
4866
  };
4648
4867
  };
4649
4868
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
@@ -4689,7 +4908,12 @@ describe('${aggregateNaming.withSpaces}', () => {
4689
4908
  if (withRepository) {
4690
4909
  aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.ts`, `export abstract class ${aggregateNaming.ClassName}Repository { }`);
4691
4910
  barrelFile.addLine(`export * from './${aggregateNaming.fileName}-repository'`);
4692
- const { label: infrastructureImplementationType } = await promptImplementationType('Repository infrastructure implementation type:', 'repositories');
4911
+ const primary = await promptImplementationType('Repository infrastructure implementation type:', 'repositories');
4912
+ const infrastructureImplementationType = primary.label;
4913
+ const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
4914
+ entered: primary.entered,
4915
+ save: primary.saveForFutureUse
4916
+ });
4693
4917
  let addTestImplementation = false;
4694
4918
  let testImplementationType = '';
4695
4919
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -4713,29 +4937,6 @@ describe('${aggregateNaming.withSpaces}', () => {
4713
4937
  labels: []
4714
4938
  };
4715
4939
  for (const implementation of implementationTypes)createImplementation(boundedContextFolder, repository, new UnknownFormatNaming(implementation).fileName);
4716
- if (scaffoldUnitTests) {
4717
- const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
4718
- const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
4719
- import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
4720
- ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `import { wire${aggregateNaming.ClassName}Repository } from '../../../wiring/repositories/wire-${aggregateNaming.fileName}-repository'
4721
- import type { ${aggregateNaming.ClassName}Repository } from './${aggregateNaming.fileName}-repository'` : `import { ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository } from '../../../infrastructure/repositories/${implementationNaming.fileName}/${implementationNaming.fileName}-${aggregateNaming.fileName}-repository'
4722
-
4723
- type ${aggregateNaming.ClassName}Repository = ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`}
4724
-
4725
- let ${aggregateNaming.variableName}Repository: ${aggregateNaming.ClassName}Repository
4726
-
4727
- beforeEach(() => {
4728
- ${aggregateNaming.variableName}Repository = ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `wire${aggregateNaming.ClassName}Repository()` : `new ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository()`}
4729
- })
4730
-
4731
- describe('${aggregateNaming.withSpaces} repository', () => {
4732
- test('can be ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? 'wired' : 'created via constructor'}', () => {
4733
- expect(${aggregateNaming.variableName}Repository).toBeDefined()
4734
- })
4735
- })
4736
- `.trim());
4737
- if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') && usesInMemoryDb(infrastructureImplementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`);
4738
- }
4739
4940
  if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
4740
4941
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
4741
4942
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
@@ -4752,6 +4953,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
4752
4953
  export const wire${aggregateNaming.ClassName}Repository = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
4753
4954
  `.trim());
4754
4955
  await wireNewModuleDependencies(boundedContextFolder, wireFile, inMemoryRepositoryWiring(boundedContextFolder, repository, wireFile));
4956
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
4957
+ kind: 'aggregate',
4958
+ name: aggregateNaming.fileName,
4959
+ ownerPath: boundedContextFolder.path
4960
+ }, new UnknownFormatNaming(infrastructureImplementationType).fileName);
4755
4961
  }
4756
4962
  }
4757
4963
  };
@@ -4761,7 +4967,6 @@ const scaffoldNewApplicationPort = async (boundedContextFolder)=>{
4761
4967
  message: 'Name: '
4762
4968
  });
4763
4969
  const naming = new UnknownFormatNaming(name);
4764
- const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
4765
4970
  const wiringFolder = boundedContextFolder.subitem([
4766
4971
  'wiring',
4767
4972
  'application-ports'
@@ -4776,9 +4981,14 @@ export abstract class ${naming.ClassName} {
4776
4981
  }
4777
4982
  `.trim());
4778
4983
  const crossContext = hasNeighboringBoundedContext(boundedContextFolder.path);
4779
- const { label: implementationType } = await promptImplementationType('Adapter implementation type:', 'ports', {
4984
+ const primary = await promptImplementationType('Adapter implementation type:', 'ports', {
4780
4985
  crossContext
4781
4986
  });
4987
+ const implementationType = primary.label;
4988
+ const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
4989
+ entered: primary.entered,
4990
+ save: primary.saveForFutureUse
4991
+ });
4782
4992
  const addTestImplementation = offersTestImplementation() && await interaction_confirm({
4783
4993
  key: 'withTestImplementation',
4784
4994
  message: 'With test implementation'
@@ -4801,28 +5011,6 @@ export abstract class ${naming.ClassName} {
4801
5011
  ownerPath: boundedContextFolder.path,
4802
5012
  labels: []
4803
5013
  }, implementation);
4804
- if (scaffoldUnitTests) {
4805
- const implementationNaming = new UnknownFormatNaming(implementationType);
4806
- applicationPortsFolder.createFile(`${naming.fileName}.spec.ts`, `
4807
- import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
4808
- ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `import { type ${naming.ClassName} } from './${naming.fileName}'
4809
- import { wire${naming.ClassName} } from '../../wiring/application-ports/wire-${naming.fileName}'` : `import { ${implementationNaming.ClassName}${naming.ClassName} } from '../../infrastructure/application-adapters/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}'
4810
-
4811
- type ${naming.ClassName} = ${implementationNaming.ClassName}${naming.ClassName}`}
4812
-
4813
- let ${naming.variableName}: ${naming.ClassName}
4814
-
4815
- beforeEach(() => {
4816
- ${naming.variableName} = ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `wire${naming.ClassName}()` : `new ${implementationNaming.ClassName}${naming.ClassName}()`}
4817
- })
4818
-
4819
- describe('${naming.withSpaces}', () => {
4820
- test('can be ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? 'wired' : 'created via constructor'}', () => {
4821
- expect(${naming.variableName}).toBeDefined()
4822
- })
4823
- })
4824
- `.trim());
4825
- }
4826
5014
  if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
4827
5015
  const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
4828
5016
  import { wireClass } from '@domain-first/wire'
@@ -4841,6 +5029,11 @@ export const wire${naming.ClassName} = envBranchedWire(${envBranchedWireArgument
4841
5029
 
4842
5030
  `.trim());
4843
5031
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
5032
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
5033
+ kind: 'port',
5034
+ name: naming.fileName,
5035
+ ownerPath: boundedContextFolder.path
5036
+ }, new UnknownFormatNaming(implementationType).fileName);
4844
5037
  }
4845
5038
  };
4846
5039
  const scaffoldNewApplicationService = async (boundedContextFolder)=>{
@@ -4918,10 +5111,13 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
4918
5111
  key: 'name',
4919
5112
  message: 'Name: '
4920
5113
  });
4921
- const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
4922
5114
  const naming = new UnknownFormatNaming(commandName);
4923
- const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
4924
- const { label: implementationType } = await promptImplementationType('Command infrastructure implementation type:', 'commands');
5115
+ const primary = await promptImplementationType('Command infrastructure implementation type:', 'commands');
5116
+ const implementationType = primary.label;
5117
+ const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
5118
+ entered: primary.entered,
5119
+ save: primary.saveForFutureUse
5120
+ });
4925
5121
  let addTestImplementation = false;
4926
5122
  let testImplementationType = '';
4927
5123
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -4958,29 +5154,6 @@ export abstract class ${naming.ClassName}Command {
4958
5154
  export abstract class ${naming.ClassName}Command {
4959
5155
 
4960
5156
  }`.trim());
4961
- if (scaffoldUnitTests) {
4962
- const implementationNaming = new UnknownFormatNaming(implementationType);
4963
- const specFile = commandsFolder.createFile(`${naming.fileName}-command.spec.ts`, `
4964
- import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
4965
- ${withWiring ? `import { type ${naming.ClassName}Command } from './${naming.fileName}-command'
4966
- import { wire${naming.ClassName}Command } from '../../wiring/commands/wire-${naming.fileName}-command'` : `import { ${implementationNaming.ClassName}${naming.ClassName}Command } from '../../infrastructure/commands/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}-command'
4967
-
4968
- type ${naming.ClassName}Command = ${implementationNaming.ClassName}${naming.ClassName}Command`}
4969
-
4970
- let ${naming.variableName}Command: ${naming.ClassName}Command
4971
-
4972
- beforeEach(() => {
4973
- ${naming.variableName}Command = ${withWiring ? `wire${naming.ClassName}Command()` : `new ${implementationNaming.ClassName}${naming.ClassName}Command()`}
4974
- })
4975
-
4976
- describe('${naming.withSpaces} command', () => {
4977
- test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
4978
- expect(${naming.variableName}Command).toBeDefined()
4979
- })
4980
- })
4981
- `.trim());
4982
- if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Command`);
4983
- }
4984
5157
  if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
4985
5158
  const implementationNaming = new UnknownFormatNaming(implementationType);
4986
5159
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
@@ -4997,6 +5170,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
4997
5170
  export const wire${naming.ClassName}Command = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
4998
5171
  `.trim());
4999
5172
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
5173
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
5174
+ kind: 'command',
5175
+ name: naming.fileName,
5176
+ ownerPath: boundedContextFolder.path
5177
+ }, new UnknownFormatNaming(implementationType).fileName);
5000
5178
  }
5001
5179
  };
5002
5180
  const scaffold_new_domain_object_noAggregate = 'No aggregate';
@@ -5370,7 +5548,7 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5370
5548
  pageSize: 20
5371
5549
  });
5372
5550
  const kind = 'aggregate' === unit.kind ? 'repositories' : 'command' === unit.kind ? 'commands' : 'query' === unit.kind ? 'queries' : 'ports';
5373
- const { label, saveForFutureUse } = await promptImplementationType('Implementation type:', kind, {
5551
+ const { label, saveForFutureUse, entered } = await promptImplementationType('Implementation type:', kind, {
5374
5552
  existing: unit.labels,
5375
5553
  purpose: 'all',
5376
5554
  remember: false,
@@ -5384,12 +5562,23 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5384
5562
  if (branches.test && environments.includes(branches.test)) rememberImplementation(kind, 'test', label);
5385
5563
  if (environments.some((environment)=>environment !== branches.test)) rememberImplementation(kind, 'primary', label);
5386
5564
  };
5387
- if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) return void rememberFor(branches.primary);
5565
+ if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
5566
+ rememberFor(branches.primary);
5567
+ await wantsIntegrationTests(label, {
5568
+ entered: false,
5569
+ save: false
5570
+ });
5571
+ return;
5572
+ }
5388
5573
  const wireFile = new file_system_File(ownerFolder.path).subitem(contractWireFile(unit).split('/'));
5389
5574
  const wireName = `wire${contractClassName(unit)}`;
5390
5575
  const wired = branchesOf(wireFile, wireName);
5391
5576
  if (!wired) {
5392
5577
  rememberFor(branches.primary);
5578
+ await wantsIntegrationTests(label, {
5579
+ entered: false,
5580
+ save: false
5581
+ });
5393
5582
  report(`${wireFile.path} has no ${wireName} = envBranchedWire({...}): wire ${className} there yourself.`);
5394
5583
  return;
5395
5584
  }
@@ -5418,6 +5607,11 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5418
5607
  required: true
5419
5608
  });
5420
5609
  rememberFor(chosenEnvironments);
5610
+ const primaryRole = chosenEnvironments.some((environment)=>environment !== branches.test);
5611
+ const withIntegrationSpec = await wantsIntegrationTests(label, {
5612
+ entered: primaryRole && entered,
5613
+ save: saveForFutureUse
5614
+ }) && primaryRole;
5421
5615
  const before = readWiredModule(wireFile.path, ownerFolder.path);
5422
5616
  wireFile.update(addBranchedImplementation(wireFile.data, wireName, {
5423
5617
  importLine: `import { ${className} } from '${relativeImport(wireFile.path, file.path)}'`,
@@ -5426,6 +5620,7 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5426
5620
  environments: chosenEnvironments
5427
5621
  }));
5428
5622
  const after = readWiredModule(wireFile.path, ownerFolder.path);
5623
+ if (withIntegrationSpec) scaffoldIntegrationSpec(unit, label);
5429
5624
  const unused = (before?.implementations ?? []).filter((x)=>!after?.implementations.some((y)=>y.className === x.className));
5430
5625
  for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
5431
5626
  await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
@@ -5471,16 +5666,6 @@ const scaffoldNewInfrastructureHelper = async (ownerFolder)=>{
5471
5666
  ...name.folders
5472
5667
  ]);
5473
5668
  folder.createFile(`${fileName}.ts`, `export const ${naming.variableName} = () => {}`);
5474
- if (config_file_ConfigFile.backend.testingLibrary) folder.createFile(`${fileName}.spec.ts`, `
5475
- import { describe, test, expect } from '${config_file_ConfigFile.backend.testingLibrary}'
5476
- import { ${naming.variableName} } from './${fileName}'
5477
-
5478
- describe('${naming.withSpaces}', () => {
5479
- test('is defined', () => {
5480
- expect(${naming.variableName}).toBeDefined()
5481
- })
5482
- })
5483
- `.trim());
5484
5669
  };
5485
5670
  const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
5486
5671
  const name = await interaction_input({
@@ -5488,7 +5673,7 @@ const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
5488
5673
  message: 'Name: '
5489
5674
  });
5490
5675
  const naming = new UnknownFormatNaming(name);
5491
- const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
5676
+ const withIntegrationSpec = await wantsServiceIntegrationSpec();
5492
5677
  const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
5493
5678
  const wiringFolder = boundedContextFolder.subitem([
5494
5679
  'wiring',
@@ -5503,23 +5688,6 @@ export class ${naming.ClassName}InfrastructureService {
5503
5688
 
5504
5689
  }
5505
5690
  `.trim());
5506
- if (scaffoldUnitTests) infrastructureServicesFolder.createFile(`${naming.fileName}-infrastructure-service.spec.ts`, `
5507
- import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
5508
- ${withWiring ? `import { type ${naming.ClassName}InfrastructureService } from './${naming.fileName}-infrastructure-service'
5509
- import { wire${naming.ClassName}InfrastructureService } from '../../wiring/infrastructure-services/wire-${naming.fileName}-infrastructure-service'` : `import { ${naming.ClassName}InfrastructureService } from './${naming.fileName}-infrastructure-service'`}
5510
-
5511
- let ${naming.variableName}InfrastructureService: ${naming.ClassName}InfrastructureService
5512
-
5513
- beforeEach(() => {
5514
- ${naming.variableName}InfrastructureService = ${withWiring ? `wire${naming.ClassName}InfrastructureService()` : `new ${naming.ClassName}InfrastructureService()`}
5515
- })
5516
-
5517
- describe('${naming.withSpaces}', () => {
5518
- test('can be ${withWiring ? 'wired' : 'created'}', () => {
5519
- expect(${naming.variableName}InfrastructureService).toBeDefined()
5520
- })
5521
- })
5522
- `.trim());
5523
5691
  if (withWiring) {
5524
5692
  const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
5525
5693
  import { wireClass } from '@domain-first/wire'
@@ -5531,6 +5699,11 @@ export const wire${naming.ClassName}InfrastructureService = wireClass(
5531
5699
  )
5532
5700
  `.trim());
5533
5701
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
5702
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
5703
+ kind: 'infrastructure-service',
5704
+ name: naming.fileName,
5705
+ ownerPath: boundedContextFolder.path
5706
+ });
5534
5707
  }
5535
5708
  };
5536
5709
  const scaffoldNewQuery = async (boundedContextFolder)=>{
@@ -5542,10 +5715,13 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
5542
5715
  key: 'name',
5543
5716
  message: 'Name: '
5544
5717
  });
5545
- const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
5546
5718
  const naming = new UnknownFormatNaming(queryName);
5547
- const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
5548
- const { label: implementationType } = await promptImplementationType('Query infrastructure implementation type:', 'queries');
5719
+ const primary = await promptImplementationType('Query infrastructure implementation type:', 'queries');
5720
+ const implementationType = primary.label;
5721
+ const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
5722
+ entered: primary.entered,
5723
+ save: primary.saveForFutureUse
5724
+ });
5549
5725
  let addTestImplementation = false;
5550
5726
  let testImplementationType = '';
5551
5727
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -5582,29 +5758,6 @@ export abstract class ${naming.ClassName}Query {
5582
5758
  export abstract class ${naming.ClassName}Query {
5583
5759
 
5584
5760
  }`.trim());
5585
- if (scaffoldUnitTests) {
5586
- const implementationNaming = new UnknownFormatNaming(implementationType);
5587
- const specFile = queriesFolder.createFile(`${naming.fileName}-query.spec.ts`, `
5588
- import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
5589
- ${withWiring ? `import { type ${naming.ClassName}Query } from './${naming.fileName}-query'
5590
- import { wire${naming.ClassName}Query } from '../../wiring/queries/wire-${naming.fileName}-query'` : `import { ${implementationNaming.ClassName}${naming.ClassName}Query } from '../../infrastructure/queries/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}-query'
5591
-
5592
- type ${naming.ClassName}Query = ${implementationNaming.ClassName}${naming.ClassName}Query`}
5593
-
5594
- let ${naming.variableName}Query: ${naming.ClassName}Query
5595
-
5596
- beforeEach(() => {
5597
- ${naming.variableName}Query = ${withWiring ? `wire${naming.ClassName}Query()` : `new ${implementationNaming.ClassName}${naming.ClassName}Query()`}
5598
- })
5599
-
5600
- describe('${naming.withSpaces} query', () => {
5601
- test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
5602
- expect(${naming.variableName}Query).toBeDefined()
5603
- })
5604
- })
5605
- `.trim());
5606
- if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Query`);
5607
- }
5608
5761
  if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
5609
5762
  const implementationNaming = new UnknownFormatNaming(implementationType);
5610
5763
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
@@ -5621,6 +5774,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
5621
5774
  export const wire${naming.ClassName}Query = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
5622
5775
  `.trim());
5623
5776
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
5777
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
5778
+ kind: 'query',
5779
+ name: naming.fileName,
5780
+ ownerPath: boundedContextFolder.path
5781
+ }, new UnknownFormatNaming(implementationType).fileName);
5624
5782
  }
5625
5783
  };
5626
5784
  const scaffoldNewUseCase = async (boundedContextFolder)=>{
@@ -5935,6 +6093,7 @@ const describeAgentCommand = (command)=>{
5935
6093
  const owners = configured ? ownerFolders(root) : [];
5936
6094
  const modules = owners.flatMap((owner)=>findWiredModules(owner.folder.path));
5937
6095
  const relative = (file)=>external_node_path_default().relative(root, file).split(external_node_path_default().sep).join('/');
6096
+ const withIntegrationSpecs = Boolean(config?.backend) && integrationSpecsAvailable();
5938
6097
  return {
5939
6098
  schemaVersion: 1,
5940
6099
  command,
@@ -5956,7 +6115,19 @@ const describeAgentCommand = (command)=>{
5956
6115
  contracts: findContracts(owner.folder.path).map((unit)=>({
5957
6116
  id: unitId(unit),
5958
6117
  kind: unit.kind,
5959
- implementations: unit.labels
6118
+ implementations: unit.labels,
6119
+ ...withIntegrationSpecs ? {
6120
+ integrationSpecs: unit.labels.flatMap((implementation)=>{
6121
+ const file = integrationSpecFile(unit, implementation);
6122
+ return file ? [
6123
+ {
6124
+ implementation,
6125
+ file: relative(file),
6126
+ exists: external_node_fs_default().existsSync(file)
6127
+ }
6128
+ ] : [];
6129
+ })
6130
+ } : {}
5960
6131
  })),
5961
6132
  modules: findWiredModules(owner.folder.path).map((module)=>({
5962
6133
  id: moduleId(module),