@domain-first/project-structure 8.7.1 → 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.
@@ -85,10 +85,17 @@ const implementationKinds = [
85
85
  'ports'
86
86
  ];
87
87
  const implementationLabelSchema = external_zod_default().string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/);
88
- const implementationOptionsSchema = external_zod_default().partialRecord(external_zod_default()["enum"](implementationKinds), external_zod_default().object({
88
+ const implementationGroupSchema = external_zod_default().object({
89
89
  primary: external_zod_default().array(implementationLabelSchema).default([]),
90
90
  test: external_zod_default().array(implementationLabelSchema).default([])
91
- }).strict());
91
+ }).strict();
92
+ const implementationOptionsSchema = external_zod_default().object({
93
+ ...Object.fromEntries(implementationKinds.map((kind)=>[
94
+ kind,
95
+ implementationGroupSchema.optional()
96
+ ])),
97
+ integrationTests: external_zod_default().array(implementationLabelSchema).optional()
98
+ }).strict();
92
99
  const moduleKinds = [
93
100
  'repositories',
94
101
  'domain-services',
@@ -2613,1385 +2620,1610 @@ const storybook_addStorybook = async ()=>{
2613
2620
  })
2614
2621
  ];
2615
2622
  };
2616
- const wire_branches_defaultEnvBranches = {
2617
- names: [
2618
- 'test',
2619
- 'development',
2620
- 'production'
2621
- ],
2622
- test: 'test'
2623
- };
2624
- const wire_branches_envBranches = ()=>{
2625
- const configured = config_file_ConfigFile.exists ? config_file_ConfigFile.Instance.data.backend?.envBranches : void 0;
2626
- const { names, test } = configured ?? wire_branches_defaultEnvBranches;
2627
- return {
2628
- names,
2629
- test,
2630
- primary: names.filter((name)=>name !== test),
2631
- custom: Boolean(configured)
2632
- };
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
+ });
2633
2646
  };
2634
- const offersTestImplementation = ()=>{
2635
- const backend = config_file_ConfigFile.exists ? config_file_ConfigFile.Instance.data.backend : void 0;
2636
- 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
+ }
2637
2661
  };
2638
- const envBranchedWireArgument = (testWire, primaryWire)=>{
2639
- const { test, primary } = wire_branches_envBranches();
2640
- return `{\n${[
2641
- ...test ? [
2642
- ` ${test}: ${testWire}`
2643
- ] : [],
2644
- ...primary.map((name)=>` ${name}: ${primaryWire}`)
2645
- ].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
+ ];
2646
2672
  };
2647
- const integrationFolder = 'specs/integration';
2648
- const testcontainersScripts = {
2649
- '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
+ };
2650
2705
  };
2651
- const testcontainersVitestConfig = (inlineHandlersNext)=>{
2652
- const server = inlineHandlersNext ? `,
2653
- server: {
2654
- deps: {
2655
- // Imports \`next/headers\` without an extension, which only a bundler can resolve
2656
- 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;
2657
2724
  }
2658
- }` : '';
2659
- return `import { fileURLToPath } from 'node:url';
2660
- import { defineConfig } from 'vitest/config';
2661
-
2662
- // Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
2663
- export default defineConfig({
2664
- // Paths below are relative to the project root, not this folder
2665
- root: fileURLToPath(new URL('../..', import.meta.url)),
2666
- resolve: {
2667
- tsconfigPaths: true
2668
- },
2669
- test: {
2670
- include: ['${integrationFolder}/**/*.spec.ts'],
2671
- // Development implementations work with the real database
2672
- env: { NODE_ENV: 'development' },
2673
- globalSetup: ['${integrationFolder}/global-setup.ts'],
2674
- setupFiles: ['${integrationFolder}/setup-env.ts'],
2675
- // Pulling the image on the first run takes a while
2676
- hookTimeout: 120_000${server}
2725
+ }
2677
2726
  }
2678
- });
2679
- `;
2680
- };
2681
- const testcontainersGlobalSetup = (migrationCommand)=>{
2682
- const migrations = migrationCommand ? `
2683
- // dotenv in the Prisma config does not override an already set variable
2684
- execSync(${JSON.stringify(migrationCommand)}, {
2685
- cwd: project.config.root,
2686
- env: { ...process.env, DATABASE_URL: databaseUrl },
2687
- // On failure the error carries the command's output
2688
- stdio: 'pipe'
2689
- });
2690
- ` : `
2691
- // Apply your migrations to databaseUrl here.
2692
- `;
2693
- return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
2694
- import type { TestProject } from 'vitest/node';
2695
-
2696
- declare module 'vitest' {
2697
- export interface ProvidedContext {
2698
- 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
+ }
2699
2756
  }
2700
- }
2701
-
2702
- const POSTGRES_IMAGE = 'postgres:15';
2703
- const POSTGRES_PORT = 5432;
2704
- const POSTGRES_USER = 'test';
2705
- const POSTGRES_PASSWORD = 'test';
2706
- const POSTGRES_DB = 'test';
2707
-
2708
- export default async function setup(project: TestProject) {
2709
- const container = await new GenericContainer(POSTGRES_IMAGE)
2710
- .withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
2711
- .withExposedPorts(POSTGRES_PORT)
2712
- // During init PostgreSQL listens on a unix socket only and restarts,
2713
- // so checking over TCP passes once the final server is up
2714
- .withHealthCheck({
2715
- test: [
2716
- 'CMD-SHELL',
2717
- \`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
2718
- ],
2719
- interval: 250,
2720
- timeout: 1000,
2721
- retries: 1000
2722
- })
2723
- .withWaitStrategy(Wait.forHealthCheck())
2724
- .withStartupTimeout(120_000)
2725
- .start();
2726
-
2727
- const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
2728
- ${migrations}
2729
- project.provide('databaseUrl', databaseUrl);
2730
-
2731
- return async () => {
2732
- await container.stop();
2757
+ return {
2758
+ moves: [
2759
+ ...moves
2760
+ ].filter(([from, to])=>from !== to),
2761
+ updated
2733
2762
  };
2734
- }
2735
- `;
2736
2763
  };
2737
- const testcontainersSetupEnv = `import 'dotenv/config';
2738
- import { inject } from 'vitest';
2739
-
2740
- // Runs before each spec's imports: development implementations get the .env
2741
- // config, and DATABASE_URL points to the container instead of the one from .env.
2742
- if (process.env.NODE_ENV !== 'development') {
2743
- throw new Error(
2744
- \`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
2745
- );
2746
- }
2747
-
2748
- process.env.DATABASE_URL = inject('databaseUrl');
2749
- `;
2750
- const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
2751
-
2752
- test('connects to the database in the container', () => {
2753
- expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
2754
- });
2755
- `;
2756
- const excludeFromUnitTests = (content)=>{
2757
- const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
2758
- if (!exclude.test(content)) return;
2759
- const entry = `'${integrationFolder}/**'`;
2760
- return content.replace(exclude, (_, items, comma, whitespace)=>{
2761
- const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
2762
- const separator = void 0 === indent ? ', ' : `,\n${indent}`;
2763
- return `${items}${separator}${entry}${comma}${whitespace}]`;
2764
- }).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
2765
- };
2766
- const testcontainers_stageFile = (filePath, content)=>{
2767
- const file = new file_system_File(filePath);
2768
- if (!file.exists || file.data !== content) file.data = content;
2769
- };
2770
- const addTestcontainers = async ()=>{
2771
- const config = config_file_ConfigFile.Instance.data;
2772
- const root = new project_root_ProjectRoot().path;
2773
- const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
2774
- const manifest = JSON.parse(manifestFile.data);
2775
- const dependencies = {
2776
- ...manifest.dependencies,
2777
- ...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
2778
2790
  };
2779
- const selected = await addPackageScripts(manifestFile, testcontainersScripts);
2780
- const withPrisma = new file_system_File(external_node_path_default().resolve(root, config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
2781
- const migrationCommand = withPrisma ? `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
2782
- const folder = external_node_path_default().join(root, integrationFolder);
2783
- testcontainers_stageFile(external_node_path_default().join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
2784
- testcontainers_stageFile(external_node_path_default().join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
2785
- testcontainers_stageFile(external_node_path_default().join(folder, 'setup-env.ts'), testcontainersSetupEnv);
2786
- const example = new file_system_File(external_node_path_default().join(folder, 'database/database.spec.ts'));
2787
- if (!example.exists) example.data = testcontainers_exampleSpec;
2788
- const unitConfig = new file_system_File(external_node_path_default().join(root, 'vitest.config.ts'));
2789
- let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
2790
- if (!excludedFromUnitTests) {
2791
- const excluded = excludeFromUnitTests(unitConfig.data);
2792
- if (excluded) {
2793
- unitConfig.update(excluded);
2794
- excludedFromUnitTests = true;
2795
- }
2796
- }
2797
- const missing = [
2798
- 'vitest',
2799
- 'testcontainers',
2800
- 'dotenv'
2801
- ].filter((name)=>!dependencies[name]);
2802
- return [
2803
- ...missing.length ? [
2804
- `npm install --save-dev ${missing.join(' ')}`
2805
- ] : [],
2806
- `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.`,
2807
- ...migrationCommand ? [] : [
2808
- `Apply your migrations in ${integrationFolder}/global-setup.ts.`
2809
- ],
2810
- ...excludedFromUnitTests ? [] : [
2811
- `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
2812
- ],
2813
- ...wire_branches_envBranches().custom ? [
2814
- `${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.`
2815
- ] : [],
2816
- 'Docker must be running for integration specs.',
2817
- ...describeScripts(selected, {
2818
- 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
2819
- })
2820
- ];
2821
2791
  };
2822
- const vitestScripts = {
2823
- test: 'vitest run --reporter=dot --silent=passed-only',
2824
- '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
+ };
2825
2807
  };
2826
- const vitestConfig = (rootFolder, inlineHandlersNext)=>{
2827
- const folder = (subpath)=>JSON.stringify(external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), subpath));
2828
- const server = inlineHandlersNext ? `,
2829
- server: {
2830
- deps: {
2831
- // Imports \`next/headers\` without an extension, which only a bundler can resolve
2832
- inline: ['@domain-first/handlers-next']
2833
- }
2834
- }` : '';
2835
- return `import { configDefaults, defineConfig } from 'vitest/config';
2836
-
2837
- export default defineConfig({
2838
- resolve: {
2839
- 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
2840
2827
  },
2841
- test: {
2842
- // Playwright runs end-to-end specs, test:integration runs integration ones
2843
- exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
2844
- coverage: {
2845
- provider: 'v8',
2846
- include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
2847
- exclude: [
2848
- '**/*.spec.ts',
2849
- ${folder('shared-kernel/infrastructure/**')},
2850
- ${folder('bounded-contexts/*/infrastructure/**')},
2851
- ${folder('bounded-contexts/*/presentation/rest/**')},
2852
- ${folder('shared-kernel/wiring/**')},
2853
- ${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`
2854
2841
  ],
2855
- reporter: [['text', { skipFull: true }], 'html']
2856
- }${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
2857
2859
  }
2858
- });
2859
- `;
2860
2860
  };
2861
- const addVitest = async ()=>{
2862
- const config = config_file_ConfigFile.Instance.data;
2863
- if (config_file_ConfigFile.backend.testingLibrary && 'vitest' !== config_file_ConfigFile.backend.testingLibrary && !await interaction_confirm({
2864
- key: 'replaceTestingLibrary',
2865
- requestRequired: true,
2866
- message: `Replace testing library "${config_file_ConfigFile.backend.testingLibrary}" with vitest for generated tests?`,
2867
- default: false
2868
- })) return [];
2869
- const root = new project_root_ProjectRoot().path;
2870
- const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
2871
- const manifest = JSON.parse(manifestFile.data);
2872
- const dependencies = {
2873
- ...manifest.dependencies,
2874
- ...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
2875
2876
  };
2876
- const selected = await addPackageScripts(manifestFile, vitestScripts);
2877
- const configFile = new file_system_File(external_node_path_default().join(root, 'vitest.config.ts'));
2878
- const content = vitestConfig(config.project.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
2879
- if (!configFile.exists || configFile.data !== content) configFile.data = content;
2880
- if ('vitest' !== config_file_ConfigFile.backend.testingLibrary) config_file_ConfigFile.update({
2881
- backend: {
2882
- ...config_file_ConfigFile.backend,
2883
- testingLibrary: 'vitest'
2884
- }
2885
- });
2886
- addGitignoreEntry(root, '/coverage/');
2887
- const missing = [
2888
- 'vitest',
2889
- '@vitest/coverage-v8'
2890
- ].filter((name)=>!dependencies[name]);
2891
- return [
2892
- ...missing.length ? [
2893
- `npm install --save-dev ${missing.join(' ')}`
2894
- ] : [],
2895
- ...describeScripts(selected, {
2896
- test: 'run unit tests',
2897
- 'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
2898
- })
2899
- ];
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;
2900
2892
  };
2901
- const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
2902
- const mergeInstallCommands = (commands)=>{
2903
- const runtime = new Set();
2904
- const development = new Set();
2905
- const rest = [];
2906
- for (const command of commands){
2907
- const match = installCommand.exec(command);
2908
- if (!match) {
2909
- rest.push(command);
2910
- continue;
2911
- }
2912
- for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
2913
- }
2914
- const devOnly = [
2915
- ...development
2916
- ].filter((name)=>!runtime.has(name));
2917
- return [
2918
- ...runtime.size ? [
2919
- `npm install ${[
2920
- ...runtime
2921
- ].join(' ')}`
2922
- ] : [],
2923
- ...devOnly.length ? [
2924
- `npm install --save-dev ${devOnly.join(' ')}`
2925
- ] : [],
2926
- ...rest
2927
- ];
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))));
2928
2906
  };
2929
- const printNextSteps = (nextSteps)=>{
2930
- const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
2931
- const commands = mergeInstallCommands(nextSteps.filter(isCommand));
2932
- const notes = nextSteps.filter((line)=>!isCommand(line));
2933
- const sections = [];
2934
- if (commands.length) sections.push([
2935
- 'Run this command to install the required dependencies:',
2936
- (0, external_node_util_namespaceObject.styleText)([
2937
- 'bold',
2938
- 'cyan'
2939
- ], commands.join(' && '))
2940
- ].join('\n'));
2941
- if (notes.length) sections.push([
2942
- 'Additional information:',
2943
- ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + (0, external_node_util_namespaceObject.styleText)([
2944
- 'bold',
2945
- 'cyan'
2946
- ], path)))
2947
- ].join('\n'));
2948
- if (sections.length) console.log(sections.join('\n\n'));
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));
2919
+ return [
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')
2933
+ ];
2949
2934
  };
2950
- const savePendingChanges = async ()=>{
2951
- assertAnswersConsumed();
2952
- const overwrittenFiles = filesToOverwrite({
2953
- changedOnly: isNonInteractive()
2954
- });
2955
- if (isNonInteractive() && overwrittenFiles.length && !answerFor('overwrite', false)) throw new RequestError('OVERWRITE_REQUIRED', 'Set overwrite to true to replace existing files.', {
2956
- 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]));
2957
2945
  });
2958
- if (overwrittenFiles.length) {
2959
- const root = new project_root_ProjectRoot().path;
2960
- report('These files already exist and will be overwritten:');
2961
- for (const filePath of overwrittenFiles)report(` ${external_node_path_default().relative(root, filePath)}`);
2962
- const overwrite = await interaction_confirm({
2963
- key: 'overwrite',
2964
- message: 'Overwrite them?',
2965
- default: false
2966
- });
2967
- if (!overwrite) {
2968
- discardPendingChanges();
2969
- report('Cancelled: nothing was written.');
2970
- return false;
2971
- }
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);
2972
2954
  }
2973
- 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`;
2974
2968
  return true;
2975
2969
  };
2976
- const withHandlersRest = ()=>config_file_ConfigFile.Instance.data.backend?.domainFirstPackages.includes('@domain-first/handlers-rest') ?? false;
2977
- const created = (...segments)=>new file_system_File(external_node_path_default().join(new project_root_ProjectRoot().path, ...segments)).exists;
2978
- const createdInRoot = (...segments)=>created(config_file_ConfigFile.Instance.data.project.rootFolder, ...segments);
2979
- const integrationIds = [
2980
- 'storybook',
2981
- 'rest-endpoint-generator',
2982
- 'in-memory-db',
2983
- 'prisma',
2984
- 'vitest',
2985
- 'playwright',
2986
- 'testcontainers',
2987
- 'openapi',
2988
- 'orval'
2989
- ];
2990
- const integrations = [
2991
- {
2992
- id: 'storybook',
2993
- name: 'Storybook (React + Vite)',
2994
- group: 'frontend',
2995
- run: storybook_addStorybook,
2996
- applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
2997
- },
2998
- {
2999
- id: 'rest-endpoint-generator',
3000
- name: 'REST endpoint generator',
3001
- group: 'backend',
3002
- run: addRestEndpointGenerator,
3003
- available: ()=>withHandlersRest(),
3004
- applied: restEndpointGeneratorApplied
3005
- },
3006
- {
3007
- id: 'in-memory-db',
3008
- name: 'In-memory DB',
3009
- group: 'backend',
3010
- run: addInMemoryDb,
3011
- applied: inMemoryDbApplied
3012
- },
3013
- {
3014
- id: 'prisma',
3015
- name: 'Prisma 8 (PostgreSQL, RC)',
3016
- group: 'backend',
3017
- run: addPrisma,
3018
- applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
3019
- },
3020
- {
3021
- id: 'vitest',
3022
- name: 'Vitest',
3023
- group: 'backend',
3024
- run: addVitest,
3025
- applied: ()=>created('vitest.config.ts')
3026
- },
3027
- {
3028
- id: 'playwright',
3029
- name: 'Playwright',
3030
- group: 'frontend',
3031
- run: addPlaywright,
3032
- applied: ()=>created('playwright.config.ts')
3033
- },
3034
- {
3035
- id: 'testcontainers',
3036
- name: 'Integration tests (Testcontainers, PostgreSQL)',
3037
- group: 'backend',
3038
- run: addTestcontainers,
3039
- applied: ()=>created('specs/integration/vitest.config.ts')
3040
- },
3041
- {
3042
- id: 'openapi',
3043
- name: 'OpenAPI',
3044
- group: 'backend',
3045
- run: addOpenapi,
3046
- available: ()=>withHandlersRest(),
3047
- applied: ()=>created(openapiScriptPath)
3048
- },
3049
- {
3050
- id: 'orval',
3051
- name: 'Orval (API client)',
3052
- group: 'frontend',
3053
- run: addOrval,
3054
- available: ()=>withHandlersRest(),
3055
- applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
3056
- }
3057
- ];
3058
- const addIntegration = async ({ save = true } = {})=>{
3059
- const available = integrations.filter(({ group, available })=>('backend' !== group || Boolean(config_file_ConfigFile.Instance.data.backend)) && (available?.() ?? true)).map((value)=>({
3060
- value,
3061
- applied: value.applied()
3062
- }));
3063
- const section = (title, applied)=>{
3064
- const items = [
3065
- 'backend',
3066
- 'frontend'
3067
- ].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
3068
- return items.length ? [
3069
- new prompts_namespaceObject.Separator(title),
3070
- ...items.map(({ value })=>({
3071
- name: `${value.name} · ${value.group}`,
3072
- value
3073
- }))
3074
- ] : [];
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)
3075
2979
  };
3076
- const choices = [
3077
- ...section('New integrations', false),
3078
- ...section('Already applied (select to reapply)', true)
3079
- ];
3080
- const selected = await interaction_checkbox({
3081
- key: 'integrations',
3082
- id: (integration)=>integration.id,
3083
- message: 'Integrations:',
3084
- choices,
3085
- pageSize: choices.length
3086
- });
3087
- const nextSteps = [];
3088
- for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
3089
- if (save && await savePendingChanges()) printNextSteps(nextSteps);
3090
- return nextSteps;
3091
- };
3092
- const integrationDescriptions = ()=>integrations.map((integration)=>({
3093
- id: integration.id,
3094
- name: integration.name,
3095
- group: integration.group,
3096
- available: ('backend' !== integration.group || Boolean(config_file_ConfigFile.Instance.data.backend)) && (integration.available?.() ?? true)
3097
- }));
3098
- const agent_requests_name = implementationLabelSchema;
3099
- 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]+)*)*$/);
3100
- const agent_requests_id = external_zod_default().string().min(1);
3101
- const agent_requests_implementation = external_zod_default().strictObject({
3102
- type: agent_requests_name,
3103
- save: external_zod_default().boolean().optional().describe('Remember this ordinary type for future runs. Default: false.')
3104
- });
3105
- 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.');
3106
- const common = {
3107
- overwrite: external_zod_default().boolean().optional(),
3108
- dryRun: external_zod_default().boolean().optional()
3109
2980
  };
3110
- const agent_requests_owner = {
3111
- context: agent_requests_name.describe('A bounded-context name, or shared-kernel.')
3112
- };
3113
- const agent_requests_wired = {
3114
- dependencies: agent_requests_dependencies.optional()
3115
- };
3116
- const agent_requests_implementations = {
3117
- implementation: agent_requests_implementation,
3118
- testImplementation: agent_requests_implementation.optional(),
3119
- ...agent_requests_wired
3120
- };
3121
- const named = {
3122
- ...common,
3123
- ...agent_requests_owner,
3124
- name: agent_requests_name
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');
3125
2989
  };
3126
- const agent_requests_operation = (value, shape)=>external_zod_default().strictObject({
3127
- operation: external_zod_default().literal(value),
3128
- ...shape
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
3129
3080
  });
3130
- const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operation', [
3131
- agent_requests_operation('bounded-context', {
3132
- ...common,
3133
- name: agent_requests_name.refine((value)=>'shared-kernel' !== value, 'shared-kernel is reserved for the Shared Kernel.')
3134
- }),
3135
- agent_requests_operation('aggregate', {
3136
- ...named,
3137
- withRepository: external_zod_default().boolean().optional(),
3138
- implementation: agent_requests_implementation.optional(),
3139
- testImplementation: agent_requests_implementation.optional(),
3140
- ...agent_requests_wired
3141
- }),
3142
- agent_requests_operation('entity', {
3143
- ...named,
3144
- aggregate: agent_requests_name.optional()
3145
- }),
3146
- agent_requests_operation('value-object', {
3147
- ...named,
3148
- aggregate: agent_requests_name.optional()
3149
- }),
3150
- agent_requests_operation('error', {
3151
- ...named,
3152
- namespace: agent_requests_name.optional()
3153
- }),
3154
- agent_requests_operation('error-namespace', named),
3155
- agent_requests_operation('domain-service', {
3156
- ...named,
3157
- ...agent_requests_wired
3158
- }),
3159
- agent_requests_operation('application-service', {
3160
- ...named,
3161
- ...agent_requests_wired
3162
- }),
3163
- agent_requests_operation('infrastructure-service', {
3164
- ...named,
3165
- ...agent_requests_wired
3166
- }),
3167
- agent_requests_operation('helper', {
3168
- ...common,
3169
- ...agent_requests_owner,
3170
- name: agent_requests_nestedName.describe('Kebab-case, folders split by "/": mappers/social-network-type.'),
3171
- implementationType: agent_requests_name.describe('A saved or system implementation type: a helper belongs to one.')
3172
- }),
3173
- agent_requests_operation('presentation-service', {
3174
- ...named,
3175
- ...agent_requests_wired
3176
- }),
3177
- agent_requests_operation('use-case', {
3178
- ...named,
3179
- ...agent_requests_wired
3180
- }),
3181
- agent_requests_operation('command', {
3182
- ...named,
3183
- ...agent_requests_implementations
3184
- }),
3185
- agent_requests_operation('query', {
3186
- ...named,
3187
- ...agent_requests_implementations
3188
- }),
3189
- agent_requests_operation('port', {
3190
- ...named,
3191
- ...agent_requests_implementations
3192
- }),
3193
- agent_requests_operation('implementation', {
3194
- ...common,
3195
- ...agent_requests_owner,
3196
- contract: agent_requests_id.describe('Exact contract ID from --describe.'),
3197
- implementation: agent_requests_implementation,
3198
- environments: external_zod_default().array(agent_requests_name).min(1).optional().describe('Required when the contract wire is envBranchedWire; omit it otherwise.'),
3199
- ...agent_requests_wired
3200
- }),
3201
- agent_requests_operation('endpoint', {
3202
- ...common,
3203
- ...agent_requests_owner,
3204
- controller: agent_requests_name.optional().describe('Omit for the context-root controller (root): `/<context>/<path>`.'),
3205
- method: external_zod_default()["enum"]([
3206
- 'get',
3207
- 'post',
3208
- 'put',
3209
- 'patch',
3210
- 'delete'
3211
- ]),
3212
- path: external_zod_default().string().regex(/^(?:\/?(?:[a-zA-Z0-9_-]+|:[a-zA-Z][a-zA-Z0-9_]*))*\/?$/),
3213
- 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.')
3214
- }),
3215
- agent_requests_operation('wire-dependency', {
3216
- ...common,
3217
- ...agent_requests_owner,
3218
- module: agent_requests_id.describe('Exact wiring target ID, including implementation class, from --describe.'),
3219
- dependencies: agent_requests_dependencies
3220
- }),
3221
- agent_requests_operation('delete', {
3222
- ...common,
3223
- ...agent_requests_owner,
3224
- module: agent_requests_id.describe('Exact unit ID from --describe. Refused while other files use it.')
3225
- }),
3226
- agent_requests_operation('move', {
3227
- ...common,
3228
- ...agent_requests_owner,
3229
- module: agent_requests_id.describe('Exact unit ID from --describe.'),
3230
- targetContext: agent_requests_name.optional(),
3231
- name: agent_requests_name.optional(),
3232
- aggregate: agent_requests_name.optional()
3233
- })
3234
- ]);
3235
- const reactRequestSchema = external_zod_default().discriminatedUnion('operation', [
3236
- agent_requests_operation('page', {
3237
- ...common,
3238
- name: agent_requests_nestedName
3239
- }),
3240
- agent_requests_operation('widget', {
3241
- ...common,
3242
- name: agent_requests_nestedName,
3243
- widgetType: external_zod_default()["enum"]([
3244
- 'monolithic',
3245
- 'separated',
3246
- 'headless'
3247
- ]).optional()
3248
- }),
3249
- agent_requests_operation('ui-kit-component', {
3250
- ...common,
3251
- name: agent_requests_name
3252
- }),
3253
- agent_requests_operation('shared-hook', {
3254
- ...common,
3255
- name: agent_requests_name
3256
- }),
3257
- agent_requests_operation('move-page', {
3258
- ...common,
3259
- module: agent_requests_nestedName,
3260
- name: agent_requests_nestedName,
3261
- 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.')
3262
- }),
3263
- agent_requests_operation('delete-page', {
3264
- ...common,
3265
- module: agent_requests_nestedName,
3266
- 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.")
3267
- }),
3268
- agent_requests_operation('delete-widget', {
3269
- ...common,
3270
- module: agent_requests_nestedName
3271
- }),
3272
- agent_requests_operation('move-ui-kit-component', {
3273
- ...common,
3274
- module: agent_requests_name,
3275
- name: agent_requests_name
3276
- }),
3277
- agent_requests_operation('move-shared-hook', {
3278
- ...common,
3279
- module: agent_requests_name,
3280
- name: agent_requests_name
3281
- }),
3282
- agent_requests_operation('delete-ui-kit-component', {
3283
- ...common,
3284
- module: agent_requests_name
3285
- }),
3286
- agent_requests_operation('delete-shared-hook', {
3287
- ...common,
3288
- module: agent_requests_name
3289
- }),
3290
- agent_requests_operation('move-widget', {
3291
- ...common,
3292
- module: agent_requests_nestedName,
3293
- name: agent_requests_nestedName
3294
- })
3295
- ]);
3296
- 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.');
3297
- const integrationRequestSchema = agent_requests_operation('add', {
3298
- ...common,
3299
- integrations: external_zod_default().array(external_zod_default()["enum"](integrationIds)).min(1),
3300
- nextAdapter: external_zod_default().boolean().optional(),
3301
- configureReact: external_zod_default().boolean().optional(),
3302
- replaceTestingLibrary: external_zod_default().boolean().optional(),
3303
- withService: external_zod_default().boolean().optional(),
3304
- routePrefix: external_zod_default().string().regex(/^\/?[a-zA-Z0-9_/-]*$/).optional(),
3305
- openapiPath: agent_requests_relativePath.optional(),
3306
- withExtractor: external_zod_default().boolean().optional(),
3307
- swaggerPage: external_zod_default().boolean().optional(),
3308
- targets: external_zod_default().array(external_zod_default()["enum"]([
3309
- 'hooks',
3310
- 'client'
3311
- ])).min(1).optional(),
3312
- scriptConflicts: external_zod_default().record(agent_requests_id, external_zod_default()["enum"]([
3313
- 'keep',
3314
- 'replace',
3315
- 'rename'
3316
- ])).optional(),
3317
- scriptNames: external_zod_default().record(agent_requests_id, external_zod_default().string().regex(/^[a-zA-Z0-9:_-]+$/)).optional()
3318
- });
3319
- const requestSchemaFor = (command)=>({
3320
- 'df-scaffold': scaffoldRequestSchema,
3321
- 'df-react': reactRequestSchema,
3322
- 'df-integration': integrationRequestSchema
3323
- })[command];
3324
- const ignoredFolders = new Set([
3325
- 'node_modules',
3326
- '.git',
3327
- '.next',
3328
- 'dist',
3329
- 'build',
3330
- 'out',
3331
- 'coverage',
3332
- 'storybook-static'
3333
- ]);
3334
- const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
3335
- const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
3336
- const module_move_walk = (folder)=>{
3337
- if (!external_node_fs_default().existsSync(folder)) return [];
3338
- return external_node_fs_default().readdirSync(folder, {
3339
- withFileTypes: true
3340
- }).flatMap((entry)=>{
3341
- const entryPath = external_node_path_default().join(folder, entry.name);
3342
- if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : module_move_walk(entryPath);
3343
- return entry.isFile() ? [
3344
- entryPath
3345
- ] : [];
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
3346
3085
  });
3347
- };
3348
- const toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
3349
- const readAliases = (projectRoot)=>{
3350
- const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
3351
- if (!external_node_fs_default().existsSync(tsconfig)) return [];
3352
- try {
3353
- const { compilerOptions = {} } = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(tsconfig, 'utf8')));
3354
- const base = external_node_path_default().resolve(projectRoot, compilerOptions.baseUrl ?? '.');
3355
- return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
3356
- prefix: pattern.slice(0, -1),
3357
- target: external_node_path_default().resolve(base, target.slice(0, -1))
3358
- }));
3359
- } catch {
3360
- return [];
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
+ }
3361
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;
3362
3131
  };
3363
- const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
3364
- const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
3365
- const importPaths = (file)=>{
3366
- const withoutExtension = file.replace(codeExtension, '');
3367
- return 'index' === external_node_path_default().basename(withoutExtension) ? [
3368
- withoutExtension,
3369
- external_node_path_default().dirname(withoutExtension)
3370
- ] : [
3371
- withoutExtension
3372
- ];
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}`;
3373
3135
  };
3374
- const projectImports = (projectRoot)=>{
3375
- const aliases = readAliases(projectRoot);
3376
- const resolve = (specifier, fromFile)=>{
3377
- if (specifier.startsWith('.')) return {
3378
- resolved: external_node_path_default().resolve(external_node_path_default().dirname(fromFile), specifier),
3379
- alias: void 0
3380
- };
3381
- const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
3382
- return alias ? {
3383
- resolved: external_node_path_default().resolve(alias.target, specifier.slice(alias.prefix.length)),
3384
- alias
3385
- } : void 0;
3386
- };
3387
- const specifierFor = (fromFile, toPath, alias)=>{
3388
- const aliased = alias && toPosix(external_node_path_default().relative(alias.target, toPath));
3389
- if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
3390
- const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
3391
- return relative.startsWith('.') ? relative : `./${relative}`;
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
3392
3195
  };
3393
- const codeFiles = new Map(module_move_walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
3394
- file,
3395
- external_node_fs_default().readFileSync(file, 'utf8')
3396
- ]));
3397
- const importsOf = (file)=>[
3398
- ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
3399
- ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
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);
3400
3198
  return {
3401
- resolve,
3402
- specifierFor,
3403
- codeFiles,
3404
- importsOf
3199
+ deleted: files,
3200
+ updated: [
3201
+ ...cleaned.keys()
3202
+ ]
3405
3203
  };
3406
3204
  };
3407
- const stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content, stopAtFor })=>{
3408
- const stopFor = (file)=>stopAtFor?.(file) ?? stopAt;
3409
- const { resolve, specifierFor, codeFiles } = projectImports(projectRoot);
3410
- const barrels = new Set();
3411
- const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
3412
- for(let found = true; found;){
3413
- found = false;
3414
- for (const [file, content] of codeFiles){
3415
- if (moves.has(file) || isBarrel(file)) continue;
3416
- const reExportsModule = [
3417
- ...content.matchAll(reExportPattern)
3418
- ].some(([, , specifier])=>{
3419
- const resolution = resolve(specifier, file);
3420
- return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
3421
- });
3422
- if (reExportsModule) {
3423
- for (const importPath of importPaths(file))barrels.add(importPath);
3424
- found = true;
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}/`));
3223
+ };
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
+ }
3240
+ })
3241
+ }
3242
+ `.trim() : `
3243
+ import { ${ContractName} } from '${contractImport}'
3244
+
3245
+ export class ${ClassName} extends ${ContractName} {
3246
+ constructor() {
3247
+ super()
3248
+ }
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))
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
+ }
3327
+ };
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;
3337
+ };
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
+ ]
3425
3355
  }
3426
3356
  }
3427
- }
3428
- const rewrite = (content, oldFile, newFile)=>{
3429
- let referencesModule = false;
3430
- const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
3431
- const resolution = resolve(specifier, oldFile);
3432
- if (!resolution) return match;
3433
- const moved = movedPath(resolution.resolved);
3434
- if (moved || isBarrel(resolution.resolved)) referencesModule = true;
3435
- if (!moved && oldFile === newFile) return match;
3436
- const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
3437
- return `${keyword}${quote}${next}${quote}`;
3438
- });
3439
- const changed = everyFile(rewritten);
3440
- if (!referencesModule && !moves.has(oldFile)) return changed;
3441
- return rename(changed, {
3442
- 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
3443
3410
  });
3444
- };
3445
- for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new file_system_File(file).moveTo(newFile, stopFor(file));
3446
- const updated = [];
3447
- for (const [file, content] of codeFiles){
3448
- const newFile = moves.get(file);
3449
- const next = rewrite(content, file, newFile ?? file);
3450
- if (newFile && newFile !== file) {
3451
- new file_system_File(newFile).data = next;
3452
- new file_system_File(file).delete(stopFor(file));
3453
- } else if (next !== content) {
3454
- new file_system_File(file).update(next);
3455
- if (!newFile) updated.push(file);
3456
- }
3411
+ return spec;
3457
3412
  }
3458
- return {
3459
- moves: [
3460
- ...moves
3461
- ].filter(([from, to])=>from !== to),
3462
- updated
3463
- };
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;
3464
3428
  };
3465
- const serviceLayout = (layer)=>({
3466
- title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
3467
- core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
3468
- files: ({ name })=>[
3469
- `${layer}/services/${name}-${layer}-service.ts`,
3470
- `${layer}/services/${name}-${layer}-service.spec.ts`,
3471
- `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
3472
- ],
3473
- wired: true,
3474
- sharedKernel: true
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
+ ]
3475
3433
  });
3476
- const handlerLayout = (kind)=>{
3477
- const folder = 'command' === kind ? 'commands' : 'queries';
3478
- const Suffix = 'command' === kind ? 'Command' : 'Query';
3479
- return {
3480
- title: 'command' === kind ? 'Commands' : 'Queries',
3481
- core: (ClassName)=>`${ClassName}${Suffix}`,
3482
- files: ({ name }, labels)=>[
3483
- `application/${folder}/${name}-${kind}.ts`,
3484
- `application/${folder}/${name}-${kind}.spec.ts`,
3485
- ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
3486
- `wiring/${folder}/wire-${name}-${kind}.ts`
3487
- ],
3488
- implementations: `infrastructure/${folder}`,
3489
- wired: true,
3490
- sharedKernel: false
3491
- };
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;
3492
3450
  };
3493
- const domainModelLayout = (kind)=>{
3494
- 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;
3495
3467
  return {
3496
- title: 'entity' === kind ? 'Entities' : 'Value objects',
3497
- core: (ClassName)=>ClassName,
3498
- files: ({ name, aggregate })=>{
3499
- const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
3500
- return [
3501
- `${base}/${name}.${kind}.ts`,
3502
- `${base}/${name}.${kind}.spec.ts`
3503
- ];
3504
- },
3505
- wired: false,
3506
- sharedKernel: true
3468
+ names,
3469
+ test,
3470
+ primary: names.filter((name)=>name !== test),
3471
+ custom: Boolean(configured)
3507
3472
  };
3508
3473
  };
3509
- const aggregateOwnFiles = (name)=>[
3510
- `${name}.aggregate-root.ts`,
3511
- `${name}.aggregate-root.spec.ts`,
3512
- `${name}-repository.ts`,
3513
- `${name}-repository.spec.ts`,
3514
- 'index.ts'
3515
- ];
3516
- const kindLayouts = {
3517
- aggregate: {
3518
- title: 'Aggregates',
3519
- core: (ClassName)=>`${ClassName}Repository`,
3520
- files: ({ name }, labels)=>[
3521
- ...aggregateOwnFiles(name).map((file)=>`domain/aggregates/${name}/${file}`),
3522
- ...labels.map((label)=>`infrastructure/repositories/${label}/${label}-${name}-repository.ts`),
3523
- `wiring/repositories/wire-${name}-repository.ts`
3524
- ],
3525
- implementations: 'infrastructure/repositories',
3526
- wired: true,
3527
- sharedKernel: false
3528
- },
3529
- entity: domainModelLayout('entity'),
3530
- 'value-object': domainModelLayout('value-object'),
3531
- 'domain-service': serviceLayout('domain'),
3532
- 'application-service': serviceLayout('application'),
3533
- 'infrastructure-service': serviceLayout('infrastructure'),
3534
- 'presentation-service': serviceLayout('presentation'),
3535
- 'use-case': {
3536
- title: 'Use cases',
3537
- core: (ClassName)=>`${ClassName}UseCase`,
3538
- files: ({ name })=>[
3539
- `application/use-cases/${name}-use-case.ts`,
3540
- `application/use-cases/${name}-use-case.spec.ts`,
3541
- `wiring/use-cases/wire-${name}-use-case.ts`
3542
- ],
3543
- wired: true,
3544
- 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
3545
3508
  },
3546
- command: handlerLayout('command'),
3547
- query: handlerLayout('query'),
3548
- port: {
3549
- title: 'Ports',
3550
- core: (ClassName)=>ClassName,
3551
- files: ({ name }, labels)=>[
3552
- `application/ports/${name}.ts`,
3553
- `application/ports/${name}.spec.ts`,
3554
- ...labels.map((label)=>`infrastructure/application-adapters/${label}/${label}-${name}.ts`),
3555
- `wiring/application-ports/wire-${name}.ts`
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}
3517
+ }
3518
+ });
3519
+ `;
3520
+ };
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}\`
3556
3558
  ],
3557
- implementations: 'infrastructure/application-adapters',
3558
- wired: true,
3559
- sharedKernel: true
3560
- }
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
+ `;
3561
3576
  };
3562
- const subfolders = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
3563
- withFileTypes: true
3564
- }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
3565
- 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() : [];
3566
- const labelsOf = (ownerPath, kind, name)=>{
3567
- const { implementations } = kindLayouts[kind];
3568
- if (!implementations) return [];
3569
- return subfolders(external_node_path_default().join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
3570
- ownerPath,
3571
- name
3572
- }, [
3573
- label
3574
- ]).some((file)=>file.startsWith(`${implementations}/`) && external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, file))));
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');
3575
3605
  };
3576
- 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`)));
3577
- const findBackendUnits = (ownerPath)=>{
3578
- const unit = (kind, name, aggregate)=>({
3579
- kind,
3580
- name,
3581
- ownerPath,
3582
- aggregate,
3583
- labels: labelsOf(ownerPath, kind, name)
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
+ }))
3584
3629
  });
3585
- const aggregates = aggregatesOf(ownerPath);
3586
- 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)));
3587
- const at = (folder, suffix, kind)=>namesBySuffix(external_node_path_default().join(ownerPath, folder), suffix).map((name)=>unit(kind, name));
3588
- return [
3589
- ...aggregates.map((name)=>unit('aggregate', name)),
3590
- ...inAggregates('entity'),
3591
- ...at('domain/entities', '.entity.ts', 'entity'),
3592
- ...inAggregates('value-object'),
3593
- ...at('domain/value-objects', '.value-object.ts', 'value-object'),
3594
- ...at('domain/services', '-domain-service.ts', 'domain-service'),
3595
- ...at('application/ports', '.ts', 'port'),
3596
- ...at('application/queries', '-query.ts', 'query'),
3597
- ...at('application/commands', '-command.ts', 'command'),
3598
- ...at('application/use-cases', '-use-case.ts', 'use-case'),
3599
- ...at('application/services', '-application-service.ts', 'application-service'),
3600
- ...at('infrastructure/services', '-infrastructure-service.ts', 'infrastructure-service'),
3601
- ...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
+ ]))
3602
3653
  ];
3603
- };
3604
- const kebabName = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
3605
- const lowerFirst = (value)=>value[0].toLowerCase() + value.slice(1);
3606
- const unitMoves = (unit, target)=>{
3607
- const layout = kindLayouts[unit.kind];
3608
- const from = layout.files(unit, unit.labels);
3609
- const to = layout.files(target, unit.labels);
3610
- const moves = new Map();
3611
- from.forEach((file, index)=>{
3612
- const oldPath = external_node_path_default().join(unit.ownerPath, file);
3613
- if (external_node_fs_default().existsSync(oldPath)) moves.set(oldPath, external_node_path_default().join(target.ownerPath, to[index]));
3614
- });
3615
- if ('aggregate' === unit.kind) {
3616
- const oldFolder = external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name);
3617
- const newFolder = external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.name);
3618
- const own = new Set(aggregateOwnFiles(unit.name).map((file)=>external_node_path_default().join(oldFolder, file)));
3619
- 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);
3620
3667
  }
3621
- return moves;
3622
- };
3623
- const validateBackendMove = (unit, target, sharedKernelPath)=>{
3624
- if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
3625
- if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
3626
- 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';
3627
- 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`;
3628
- return true;
3629
3668
  };
3630
- const ownerOf = (rootFolderPath, file)=>{
3631
- const [area, context] = external_node_path_default().relative(rootFolderPath, file).split(external_node_path_default().sep);
3632
- if ('bounded-contexts' === area && context) return {
3633
- context,
3634
- path: external_node_path_default().join(rootFolderPath, area, context)
3635
- };
3636
- if ('shared-kernel' === area) return {
3637
- context: void 0,
3638
- 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
3639
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
+ ];
3640
3721
  };
3641
- const inMemoryDbFile = (rootFolderPath)=>external_node_path_default().join(rootFolderPath, 'shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts');
3642
- const isolationAllows = (rootFolderPath, from, to)=>{
3643
- const fromOwner = ownerOf(rootFolderPath, from);
3644
- const toOwner = ownerOf(rootFolderPath, to);
3645
- if (!fromOwner || !toOwner?.context) return true;
3646
- if (fromOwner.context) return fromOwner.context === toOwner.context || true === crossContextImportAllowed(from, to);
3647
- 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);
3648
- 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'
3649
3725
  };
3650
- const moveBackendUnit = (projectRoot, rootFolderPath, unit, target)=>{
3651
- const layout = kindLayouts[unit.kind];
3652
- const moves = unitMoves(unit, target);
3653
- const withoutExtension = new Map([
3654
- ...moves
3655
- ].map(([from, to])=>[
3656
- from.replace(codeExtension, ''),
3657
- to.replace(codeExtension, '')
3658
- ]));
3659
- const folders = 'aggregate' === unit.kind ? [
3660
- [
3661
- external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name),
3662
- external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.name)
3663
- ]
3664
- ] : [];
3665
- const movedPath = (candidate)=>{
3666
- const extension = candidate.match(codeExtension)?.[0];
3667
- if (extension) return moves.get(candidate);
3668
- return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
3669
- };
3670
- const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
3671
- const oldNaming = new UnknownFormatNaming(unit.name);
3672
- const newNaming = new UnknownFormatNaming(target.name);
3673
- const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
3674
- const oldAggregateFolder = unit.aggregate && external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
3675
- const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === external_node_path_default().join(oldAggregateFolder, 'index'));
3676
- const mainFile = [
3677
- ...moves.keys()
3678
- ][0];
3679
- const newMainFile = moves.get(mainFile);
3680
- const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
3681
- const barrelImporters = leavesAggregate ? [
3682
- ...codeFiles
3683
- ].filter(([file, content])=>!moves.has(file) && [
3684
- ...content.matchAll(namedImports)
3685
- ].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
3686
- const violations = [];
3687
- const relative = (file)=>toPosix(external_node_path_default().relative(projectRoot, file));
3688
- for (const file of codeFiles.keys()){
3689
- const from = moves.get(file) ?? file;
3690
- for (const imported of importsOf(file)){
3691
- const to = movedPath(imported);
3692
- if (moves.has(file) || to) {
3693
- if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
3694
- relative(from),
3695
- relative(to ?? imported)
3696
- ]);
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']
3697
3733
  }
3698
- }
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}
3699
3757
  }
3700
- for (const [file] of barrelImporters)if (!isolationAllows(rootFolderPath, file, newMainFile)) violations.push([
3701
- relative(file),
3702
- relative(newMainFile)
3703
- ]);
3704
- if (violations.length) return {
3705
- 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
3706
3775
  };
3707
- const word = (form)=>`(?<![\\w$])${escapeRegExp(form)}(?![\\w$])`;
3708
- const oldCore = layout.core(oldNaming.ClassName);
3709
- const newCore = layout.core(newNaming.ClassName);
3710
- const prefixes = [
3711
- ...unit.labels.map((label)=>new UnknownFormatNaming(label).ClassName),
3712
- ...layout.wired ? [
3713
- 'wire'
3714
- ] : []
3715
- ];
3716
- const renames = [
3717
- {
3718
- pattern: new RegExp(`(?<![\\w$])(${prefixes.map(escapeRegExp).join('|')})?${escapeRegExp(oldCore)}(?![\\w$])`, 'g'),
3719
- to: `$1${newCore}`
3720
- },
3721
- {
3722
- pattern: new RegExp(word(lowerFirst(oldCore)), 'g'),
3723
- to: lowerFirst(newCore)
3724
- },
3725
- {
3726
- pattern: new RegExp(`(describe\\(\\s*['"\`])${escapeRegExp(oldNaming.withSpaces)}(?=[ '"\`])`, 'g'),
3727
- to: `$1${newNaming.withSpaces}`,
3728
- 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'
3729
3784
  }
3730
- ];
3731
- if ('aggregate' === unit.kind) renames.push({
3732
- pattern: new RegExp(word(oldNaming.ClassName), 'g'),
3733
- to: newNaming.ClassName
3734
- }, {
3735
- pattern: new RegExp(word(oldNaming.variableName), 'g'),
3736
- to: newNaming.variableName,
3737
- movedOnly: true
3738
- });
3739
- if ('entity' === unit.kind || 'value-object' === unit.kind) renames.push({
3740
- pattern: new RegExp(word(oldNaming.variableName), 'g'),
3741
- to: newNaming.variableName,
3742
- movedOnly: true
3743
- });
3744
- const oldSection = new UnknownFormatNaming(plural(unit.name));
3745
- const newSection = new UnknownFormatNaming(plural(target.name));
3746
- const renamesSection = 'aggregate' === unit.kind && unit.name !== target.name;
3747
- 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;
3748
- const plan = stageModuleMove({
3749
- projectRoot,
3750
- stopAt: rootFolderPath,
3751
- moves,
3752
- movedPath,
3753
- rename: (content, { moved })=>renames.reduce((result, { pattern, to, movedOnly })=>movedOnly && !moved ? result : result.replace(pattern, to), content),
3754
- everyFile
3755
3785
  });
3756
- if (leavesAggregate && oldAggregateFolder) {
3757
- const indexFile = new file_system_File(external_node_path_default().join(oldAggregateFolder, 'index.ts'));
3758
- const exportLine = /^export\s+\*\s+from\s+(['"])([^'"\n]+)\1;?\s*$/;
3759
- indexFile.update(indexFile.data.split('\n').filter((line)=>{
3760
- const specifier = line.match(exportLine)?.[2];
3761
- return !specifier || external_node_path_default().resolve(external_node_path_default().dirname(indexFile.path), specifier) !== newMainFile.replace(codeExtension, '');
3762
- }).join('\n'));
3763
- if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
3764
- for (const [file] of barrelImporters){
3765
- const importer = new file_system_File(file);
3766
- let content = importer.data;
3767
- for (const match of content.matchAll(namedImports)){
3768
- const [statement, typeOnly = '', names, quote, specifier] = match;
3769
- if (!isOldBarrel(resolve(specifier, file)?.resolved)) continue;
3770
- const items = names.split(',').map((item)=>item.trim()).filter((item)=>!!item);
3771
- const own = new RegExp(`^(?:type\\s+)?${newNaming.ClassName}(?:\\s+as\\s+[\\w$]+)?$`);
3772
- const moved = items.filter((item)=>own.test(item));
3773
- if (!moved.length) continue;
3774
- const rest = items.filter((item)=>!own.test(item));
3775
- const direct = `import ${typeOnly}{ ${moved.join(', ')} } from ${quote}${projectRelative(file, newMainFile)}${quote}`;
3776
- content = content.replace(statement, rest.length ? `import ${typeOnly}{ ${rest.join(', ')} } from ${quote}${specifier}${quote}\n${direct}` : direct);
3777
- }
3778
- 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;
3779
3811
  }
3812
+ for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
3780
3813
  }
3781
- if (target.aggregate && (target.aggregate !== unit.aggregate || target.ownerPath !== unit.ownerPath)) {
3782
- const kindFolder = 'entity' === unit.kind ? 'entities' : 'value-objects';
3783
- const indexFile = new file_system_File(external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.aggregate, 'index.ts'));
3784
- indexFile.addLineIfMissing(`export * from './${kindFolder}/${target.name}.${unit.kind}'`);
3785
- if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
3786
- }
3787
- 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
+ ];
3788
3828
  };
3789
- const projectRelative = (fromFile, toFile)=>{
3790
- const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile.replace(codeExtension, '')));
3791
- 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'));
3792
3849
  };
3793
- const importSpecifier = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"\n]+)\1/g;
3794
- const backend_module_move_importLine = /^\s*(?:import|export)\b[^'"\n]*\bfrom\s*(['"])([^'"\n]+)\1;?\s*$/;
3795
- const deleteBackendUnit = (projectRoot, rootFolderPath, unit)=>{
3796
- const files = [
3797
- ...unitMoves(unit, unit).keys()
3798
- ];
3799
- const fileSet = new Set(files);
3800
- const stems = new Set(files.map((file)=>file.replace(codeExtension, '')));
3801
- const aggregateFolder = 'aggregate' === unit.kind ? external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name) : void 0;
3802
- const parentAggregate = unit.aggregate ? external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.aggregate) : void 0;
3803
- const isUnit = (resolved)=>stems.has(resolved) || !!aggregateFolder && (resolved === aggregateFolder || resolved.startsWith(`${aggregateFolder}${external_node_path_default().sep}`));
3804
- const isParentBarrel = (resolved)=>!!parentAggregate && (resolved === parentAggregate || resolved === external_node_path_default().join(parentAggregate, 'index'));
3805
- const { codeFiles, resolve } = projectImports(projectRoot);
3806
- const resolved = (specifier, file)=>resolve(specifier, file)?.resolved;
3807
- const withoutUnitImports = (content, file)=>content.split('\n').filter((line)=>{
3808
- const specifier = line.match(backend_module_move_importLine)?.[2];
3809
- const target = specifier && resolved(specifier, file);
3810
- return !(target && isUnit(target));
3811
- }).join('\n');
3812
- const cleaned = new Map();
3813
- const inMemoryDb = inMemoryDbFile(rootFolderPath);
3814
- if ('aggregate' === unit.kind && codeFiles.has(inMemoryDb)) {
3815
- const section = new UnknownFormatNaming(plural(unit.name));
3816
- const original = codeFiles.get(inMemoryDb);
3817
- const content = withoutUnitImports(original.replace(new RegExp(`^[ \\t]*${escapeRegExp(section.variableName)}\\s*=\\s*this\\.section<[^\\n]*\\n?`, 'm'), ''), inMemoryDb);
3818
- if (content !== original) cleaned.set(inMemoryDb, content);
3819
- }
3820
- if (parentAggregate) {
3821
- const index = external_node_path_default().join(parentAggregate, 'index.ts');
3822
- const original = codeFiles.get(index);
3823
- if (void 0 !== original) {
3824
- const content = withoutUnitImports(original, index);
3825
- if (content !== original) cleaned.set(index, content);
3826
- }
3827
- }
3828
- const ClassName = new UnknownFormatNaming(unit.name).ClassName;
3829
- const namedImports = /import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\2/g;
3830
- const usedBy = [];
3831
- const relative = (file)=>toPosix(external_node_path_default().relative(projectRoot, file));
3832
- for (const [file, original] of codeFiles){
3833
- if (fileSet.has(file)) continue;
3834
- const content = cleaned.get(file) ?? original;
3835
- for (const [, , specifier] of content.matchAll(importSpecifier)){
3836
- const target = resolved(specifier, file);
3837
- if (target && isUnit(target)) usedBy.push([
3838
- relative(file),
3839
- relative(target)
3840
- ]);
3841
- }
3842
- for (const [, names, , specifier] of content.matchAll(namedImports)){
3843
- const target = resolved(specifier, file);
3844
- if (target && isParentBarrel(target) && new RegExp(`(?<![\\w$])${ClassName}(?![\\w$])`).test(names)) usedBy.push([
3845
- relative(file),
3846
- `${relative(target)} (${ClassName})`
3847
- ]);
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
- if (usedBy.length) return {
3851
- usedBy
3852
- };
3853
- for (const file of files)new file_system_File(file).delete(rootFolderPath);
3854
- for (const [file, content] of cleaned)new file_system_File(file).update(content);
3855
- return {
3856
- deleted: files,
3857
- updated: [
3858
- ...cleaned.keys()
3859
- ]
3860
- };
3873
+ writePendingChanges();
3874
+ return true;
3861
3875
  };
3862
- const contractKinds = [
3863
- 'aggregate',
3864
- 'command',
3865
- 'query',
3866
- 'port'
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'
3867
3889
  ];
3868
- const implementations_withWiring = ()=>config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
3869
- const withHandlers = ()=>config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers');
3870
- const contractFile = (unit)=>'aggregate' === unit.kind ? `domain/aggregates/${unit.name}/${unit.name}-repository.ts` : kindLayouts[unit.kind].files(unit, [])[0];
3871
- const findContracts = (ownerPath)=>findBackendUnits(ownerPath).filter((unit)=>contractKinds.includes(unit.kind) && external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, contractFile(unit))));
3872
- const implementationWireName = (label)=>`wire${new UnknownFormatNaming(label).ClassName}Implementation`;
3873
- const contractClassName = (unit)=>kindLayouts[unit.kind].core(new UnknownFormatNaming(unit.name).ClassName);
3874
- const implementationClassName = (unit, label)=>`${new UnknownFormatNaming(label).ClassName}${contractClassName(unit)}`;
3875
- const implementationFile = (unit, label)=>{
3876
- const { implementations } = kindLayouts[unit.kind];
3877
- return kindLayouts[unit.kind].files(unit, [
3878
- label
3879
- ]).find((file)=>file.startsWith(`${implementations}/`));
3880
- };
3881
- const contractWireFile = (unit)=>kindLayouts[unit.kind].files(unit, []).find((file)=>file.startsWith('wiring/'));
3882
- const handlerImplementation = (ContractName, ClassName, contractImport)=>withHandlers() ? `
3883
- import { defineHandler } from '@domain-first/handlers'
3884
- import { ${ContractName} } from '${contractImport}'
3885
-
3886
- export class ${ClassName} extends ${ContractName} {
3887
- constructor() {
3888
- super()
3889
- }
3890
-
3891
- handle = defineHandler({
3892
- inputSchema: ${ContractName}.inputSchema,
3893
- outputSchema: ${ContractName}.outputSchema,
3894
- handler: async (input) => {
3895
- return {}
3896
- }
3897
- })
3898
- }
3899
- `.trim() : `
3900
- import { ${ContractName} } from '${contractImport}'
3901
-
3902
- export class ${ClassName} extends ${ContractName} {
3903
- constructor() {
3904
- super()
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')
3905
3956
  }
3906
- }
3907
- `.trim();
3908
- const createImplementation = (ownerFolder, unit, label)=>{
3909
- const naming = new UnknownFormatNaming(unit.name);
3910
- const ContractName = contractClassName(unit);
3911
- const className = implementationClassName(unit, label);
3912
- const [folder, fileName] = [
3913
- external_node_path_default().dirname(implementationFile(unit, label)),
3914
- external_node_path_default().basename(implementationFile(unit, label))
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
+ ] : [];
3975
+ };
3976
+ const choices = [
3977
+ ...section('New integrations', false),
3978
+ ...section('Already applied (select to reapply)', true)
3915
3979
  ];
3916
- const implementationFolder = ownerFolder.subitem(folder.split('/'));
3917
- const inMemoryDb = !implementations_withWiring() && usesInMemoryDb(label);
3918
- switch(unit.kind){
3919
- case 'aggregate':
3920
- {
3921
- const contractImport = `../../../domain/aggregates/${unit.name}`;
3922
- if (inMemoryDb) {
3923
- const section = addInMemoryDbSection(naming, ownerFolder.subitem([
3924
- 'domain',
3925
- 'aggregates',
3926
- unit.name
3927
- ]).path);
3928
- const file = implementationFolder.createFile(fileName, `
3929
- ${inMemoryDbTypeImport(implementationFolder.subitem([
3930
- fileName
3931
- ]).path)}
3932
- import { ${ContractName} } from '${contractImport}'
3933
-
3934
- export class ${className} implements ${ContractName} {
3935
- ${inMemoryDbSectionMembers(section, false)}
3936
- }
3937
- `.trim());
3938
- return {
3939
- file,
3940
- className
3941
- };
3942
- }
3943
- const file = implementationFolder.createFile(fileName, `
3944
- import { ${ContractName} } from '${contractImport}'
3945
-
3946
- export class ${className} implements ${ContractName} {
3947
- constructor() {}
3948
- }
3949
-
3950
- `.trim());
3951
- return {
3952
- file,
3953
- className
3954
- };
3955
- }
3956
- case 'command':
3957
- case 'query':
3958
- {
3959
- const folderName = 'command' === unit.kind ? 'commands' : 'queries';
3960
- const file = implementationFolder.createFile(fileName, handlerImplementation(ContractName, className, `../../../application/${folderName}/${naming.fileName}-${unit.kind}`));
3961
- if (inMemoryDb) injectInMemoryDb(file, className);
3962
- return {
3963
- file,
3964
- className
3965
- };
3966
- }
3967
- case 'port':
3968
- {
3969
- const file = implementationFolder.createFile(fileName, `
3970
- import { ${ContractName} } from '../../../application/ports/${naming.fileName}'
3971
-
3972
- export class ${className} extends ${ContractName} {
3973
-
3974
- }
3975
- `.trim());
3976
- return {
3977
- file,
3978
- className
3979
- };
3980
- }
3981
- default:
3982
- throw new Error(`${unit.kind} has no implementations`);
3983
- }
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;
3984
3991
  };
3985
- const inMemoryRepositoryWiring = (ownerFolder, unit, wireFile)=>(implementation, dependency)=>{
3986
- if ('aggregate' !== unit.kind || !isInMemoryDb(dependency)) return false;
3987
- keepInMemoryDbSection(new file_system_File(implementation.file), addInMemoryDbSection(new UnknownFormatNaming(unit.name), ownerFolder.subitem([
3988
- 'domain',
3989
- 'aggregates',
3990
- unit.name
3991
- ]).path));
3992
- wireInMemoryDb(wireFile, implementation.className);
3993
- return true;
3994
- };
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()
4010
+ };
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
4196
+ })
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];
3995
4227
  const reactKindLayouts = {
3996
4228
  page: {
3997
4229
  folder: 'pages',
@@ -4585,16 +4817,23 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
4585
4817
  if (!implementation) throw new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
4586
4818
  field: key
4587
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
+ });
4588
4825
  const valid = validateLabel(implementation.type);
4589
4826
  if (true !== valid) throw new RequestError('INVALID_IMPLEMENTATION', valid, {
4590
4827
  field: key
4591
4828
  });
4592
4829
  const label = implementation.type.trim();
4593
4830
  const saveForFutureUse = implementation.save ?? false;
4831
+ const entered = !choices.some((choice)=>choice.value === label);
4594
4832
  if (remember && saveForFutureUse && !system.some((choice)=>choice.value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
4595
4833
  return {
4596
4834
  label,
4597
- saveForFutureUse
4835
+ saveForFutureUse,
4836
+ entered
4598
4837
  };
4599
4838
  }
4600
4839
  const type = await interaction_select({
@@ -4610,7 +4849,8 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
4610
4849
  });
4611
4850
  if ('string' == typeof type) return {
4612
4851
  label: type,
4613
- saveForFutureUse: true
4852
+ saveForFutureUse: true,
4853
+ entered: false
4614
4854
  };
4615
4855
  const saveForFutureUse = type !== enterImplementationTypeOnce;
4616
4856
  const label = (await interaction_input({
@@ -4621,7 +4861,8 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
4621
4861
  if (saveForFutureUse && remember && !choices.some(({ value })=>value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
4622
4862
  return {
4623
4863
  label,
4624
- saveForFutureUse
4864
+ saveForFutureUse,
4865
+ entered: !choices.some(({ value })=>value === label)
4625
4866
  };
4626
4867
  };
4627
4868
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
@@ -4667,7 +4908,12 @@ describe('${aggregateNaming.withSpaces}', () => {
4667
4908
  if (withRepository) {
4668
4909
  aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.ts`, `export abstract class ${aggregateNaming.ClassName}Repository { }`);
4669
4910
  barrelFile.addLine(`export * from './${aggregateNaming.fileName}-repository'`);
4670
- 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
+ });
4671
4917
  let addTestImplementation = false;
4672
4918
  let testImplementationType = '';
4673
4919
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -4707,6 +4953,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
4707
4953
  export const wire${aggregateNaming.ClassName}Repository = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
4708
4954
  `.trim());
4709
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);
4710
4961
  }
4711
4962
  }
4712
4963
  };
@@ -4730,9 +4981,14 @@ export abstract class ${naming.ClassName} {
4730
4981
  }
4731
4982
  `.trim());
4732
4983
  const crossContext = hasNeighboringBoundedContext(boundedContextFolder.path);
4733
- const { label: implementationType } = await promptImplementationType('Adapter implementation type:', 'ports', {
4984
+ const primary = await promptImplementationType('Adapter implementation type:', 'ports', {
4734
4985
  crossContext
4735
4986
  });
4987
+ const implementationType = primary.label;
4988
+ const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
4989
+ entered: primary.entered,
4990
+ save: primary.saveForFutureUse
4991
+ });
4736
4992
  const addTestImplementation = offersTestImplementation() && await interaction_confirm({
4737
4993
  key: 'withTestImplementation',
4738
4994
  message: 'With test implementation'
@@ -4773,6 +5029,11 @@ export const wire${naming.ClassName} = envBranchedWire(${envBranchedWireArgument
4773
5029
 
4774
5030
  `.trim());
4775
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);
4776
5037
  }
4777
5038
  };
4778
5039
  const scaffoldNewApplicationService = async (boundedContextFolder)=>{
@@ -4851,7 +5112,12 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
4851
5112
  message: 'Name: '
4852
5113
  });
4853
5114
  const naming = new UnknownFormatNaming(commandName);
4854
- 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
+ });
4855
5121
  let addTestImplementation = false;
4856
5122
  let testImplementationType = '';
4857
5123
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -4904,6 +5170,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
4904
5170
  export const wire${naming.ClassName}Command = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
4905
5171
  `.trim());
4906
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);
4907
5178
  }
4908
5179
  };
4909
5180
  const scaffold_new_domain_object_noAggregate = 'No aggregate';
@@ -5277,7 +5548,7 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5277
5548
  pageSize: 20
5278
5549
  });
5279
5550
  const kind = 'aggregate' === unit.kind ? 'repositories' : 'command' === unit.kind ? 'commands' : 'query' === unit.kind ? 'queries' : 'ports';
5280
- const { label, saveForFutureUse } = await promptImplementationType('Implementation type:', kind, {
5551
+ const { label, saveForFutureUse, entered } = await promptImplementationType('Implementation type:', kind, {
5281
5552
  existing: unit.labels,
5282
5553
  purpose: 'all',
5283
5554
  remember: false,
@@ -5291,12 +5562,23 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5291
5562
  if (branches.test && environments.includes(branches.test)) rememberImplementation(kind, 'test', label);
5292
5563
  if (environments.some((environment)=>environment !== branches.test)) rememberImplementation(kind, 'primary', label);
5293
5564
  };
5294
- 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
+ }
5295
5573
  const wireFile = new file_system_File(ownerFolder.path).subitem(contractWireFile(unit).split('/'));
5296
5574
  const wireName = `wire${contractClassName(unit)}`;
5297
5575
  const wired = branchesOf(wireFile, wireName);
5298
5576
  if (!wired) {
5299
5577
  rememberFor(branches.primary);
5578
+ await wantsIntegrationTests(label, {
5579
+ entered: false,
5580
+ save: false
5581
+ });
5300
5582
  report(`${wireFile.path} has no ${wireName} = envBranchedWire({...}): wire ${className} there yourself.`);
5301
5583
  return;
5302
5584
  }
@@ -5325,6 +5607,11 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5325
5607
  required: true
5326
5608
  });
5327
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;
5328
5615
  const before = readWiredModule(wireFile.path, ownerFolder.path);
5329
5616
  wireFile.update(addBranchedImplementation(wireFile.data, wireName, {
5330
5617
  importLine: `import { ${className} } from '${relativeImport(wireFile.path, file.path)}'`,
@@ -5333,6 +5620,7 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
5333
5620
  environments: chosenEnvironments
5334
5621
  }));
5335
5622
  const after = readWiredModule(wireFile.path, ownerFolder.path);
5623
+ if (withIntegrationSpec) scaffoldIntegrationSpec(unit, label);
5336
5624
  const unused = (before?.implementations ?? []).filter((x)=>!after?.implementations.some((y)=>y.className === x.className));
5337
5625
  for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
5338
5626
  await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
@@ -5385,6 +5673,7 @@ const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
5385
5673
  message: 'Name: '
5386
5674
  });
5387
5675
  const naming = new UnknownFormatNaming(name);
5676
+ const withIntegrationSpec = await wantsServiceIntegrationSpec();
5388
5677
  const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
5389
5678
  const wiringFolder = boundedContextFolder.subitem([
5390
5679
  'wiring',
@@ -5410,6 +5699,11 @@ export const wire${naming.ClassName}InfrastructureService = wireClass(
5410
5699
  )
5411
5700
  `.trim());
5412
5701
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
5702
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
5703
+ kind: 'infrastructure-service',
5704
+ name: naming.fileName,
5705
+ ownerPath: boundedContextFolder.path
5706
+ });
5413
5707
  }
5414
5708
  };
5415
5709
  const scaffoldNewQuery = async (boundedContextFolder)=>{
@@ -5422,7 +5716,12 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
5422
5716
  message: 'Name: '
5423
5717
  });
5424
5718
  const naming = new UnknownFormatNaming(queryName);
5425
- 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
+ });
5426
5725
  let addTestImplementation = false;
5427
5726
  let testImplementationType = '';
5428
5727
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -5475,6 +5774,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
5475
5774
  export const wire${naming.ClassName}Query = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
5476
5775
  `.trim());
5477
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);
5478
5782
  }
5479
5783
  };
5480
5784
  const scaffoldNewUseCase = async (boundedContextFolder)=>{
@@ -5789,6 +6093,7 @@ const describeAgentCommand = (command)=>{
5789
6093
  const owners = configured ? ownerFolders(root) : [];
5790
6094
  const modules = owners.flatMap((owner)=>findWiredModules(owner.folder.path));
5791
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();
5792
6097
  return {
5793
6098
  schemaVersion: 1,
5794
6099
  command,
@@ -5810,7 +6115,19 @@ const describeAgentCommand = (command)=>{
5810
6115
  contracts: findContracts(owner.folder.path).map((unit)=>({
5811
6116
  id: unitId(unit),
5812
6117
  kind: unit.kind,
5813
- 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
+ } : {}
5814
6131
  })),
5815
6132
  modules: findWiredModules(owner.folder.path).map((module)=>({
5816
6133
  id: moduleId(module),