@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.
package/dist/287.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import node_path from "node:path";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, search, select as prompts_select } from "@inquirer/prompts";
4
- import { styleText } from "node:util";
5
4
  import node_fs from "node:fs";
5
+ import { styleText } from "node:util";
6
6
  import { addImport, availableDependencies, findWiredModules, UnknownFormatNaming, readWiredModule, addClassMember, hasNeighboringBoundedContext, addBranchedImplementation, addWireDependencies, boundedContextLocation, addConstructorParameters, relativeImport, wireBranches, wireDependencies, implementationType as wiring_implementationType, crossContextImportAllowed, crossContextImplementation, isSuggestedFor } from "./947.js";
7
7
  import { implementationLabelSchema, withoutOverwrites, domainFirstPackages as config_file_domainFirstPackages, scaffoldBackendRules, branchNameSchema, discardPendingChanges, ConfigFile, filesToOverwrite, Folder, writePendingChanges, File, ProjectRoot, implementationKinds, compilerOption } from "./780.js";
8
8
  import { missingDomainFirstPackages, walk, projectImports, escapeRegExp, pathParameterAsName, hasLegacyRootEndpoints, stageModuleMove, toPosix, rootStaticSegments, openapiExtractorPath, restControllers, hasDependency, openapiExtractor, missingPackages, codeExtension, isPathParameterName } from "./526.js";
@@ -1500,1038 +1500,1260 @@ const addStorybook = async ()=>{
1500
1500
  })
1501
1501
  ];
1502
1502
  };
1503
- const defaultEnvBranches = {
1504
- names: [
1505
- 'test',
1506
- 'development',
1507
- 'production'
1508
- ],
1509
- test: 'test'
1503
+ const serviceLayout = (layer)=>({
1504
+ title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
1505
+ core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
1506
+ files: ({ name })=>[
1507
+ `${layer}/services/${name}-${layer}-service.ts`,
1508
+ `${layer}/services/${name}-${layer}-service.spec.ts`,
1509
+ `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
1510
+ ],
1511
+ wired: true,
1512
+ sharedKernel: true
1513
+ });
1514
+ const handlerLayout = (kind)=>{
1515
+ const folder = 'command' === kind ? 'commands' : 'queries';
1516
+ const Suffix = 'command' === kind ? 'Command' : 'Query';
1517
+ return {
1518
+ title: 'command' === kind ? 'Commands' : 'Queries',
1519
+ core: (ClassName)=>`${ClassName}${Suffix}`,
1520
+ files: ({ name }, labels)=>[
1521
+ `application/${folder}/${name}-${kind}.ts`,
1522
+ `application/${folder}/${name}-${kind}.spec.ts`,
1523
+ ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
1524
+ `wiring/${folder}/wire-${name}-${kind}.ts`
1525
+ ],
1526
+ implementations: `infrastructure/${folder}`,
1527
+ wired: true,
1528
+ sharedKernel: false
1529
+ };
1510
1530
  };
1511
- const wire_branches_envBranches = ()=>{
1512
- const configured = ConfigFile.exists ? ConfigFile.Instance.data.backend?.envBranches : void 0;
1513
- const { names, test } = configured ?? defaultEnvBranches;
1531
+ const domainModelLayout = (kind)=>{
1532
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
1514
1533
  return {
1515
- names,
1516
- test,
1517
- primary: names.filter((name)=>name !== test),
1518
- custom: Boolean(configured)
1534
+ title: 'entity' === kind ? 'Entities' : 'Value objects',
1535
+ core: (ClassName)=>ClassName,
1536
+ files: ({ name, aggregate })=>{
1537
+ const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
1538
+ return [
1539
+ `${base}/${name}.${kind}.ts`,
1540
+ `${base}/${name}.${kind}.spec.ts`
1541
+ ];
1542
+ },
1543
+ wired: false,
1544
+ sharedKernel: true
1519
1545
  };
1520
1546
  };
1521
- const offersTestImplementation = ()=>{
1522
- const backend = ConfigFile.exists ? ConfigFile.Instance.data.backend : void 0;
1523
- return !(backend?.domainFirstPackages.includes('@domain-first/wire') && backend.envBranches && void 0 === backend.envBranches.test);
1547
+ const aggregateOwnFiles = (name)=>[
1548
+ `${name}.aggregate-root.ts`,
1549
+ `${name}.aggregate-root.spec.ts`,
1550
+ `${name}-repository.ts`,
1551
+ `${name}-repository.spec.ts`,
1552
+ 'index.ts'
1553
+ ];
1554
+ const kindLayouts = {
1555
+ aggregate: {
1556
+ title: 'Aggregates',
1557
+ core: (ClassName)=>`${ClassName}Repository`,
1558
+ files: ({ name }, labels)=>[
1559
+ ...aggregateOwnFiles(name).map((file)=>`domain/aggregates/${name}/${file}`),
1560
+ ...labels.map((label)=>`infrastructure/repositories/${label}/${label}-${name}-repository.ts`),
1561
+ `wiring/repositories/wire-${name}-repository.ts`
1562
+ ],
1563
+ implementations: 'infrastructure/repositories',
1564
+ wired: true,
1565
+ sharedKernel: false
1566
+ },
1567
+ entity: domainModelLayout('entity'),
1568
+ 'value-object': domainModelLayout('value-object'),
1569
+ 'domain-service': serviceLayout('domain'),
1570
+ 'application-service': serviceLayout('application'),
1571
+ 'infrastructure-service': serviceLayout('infrastructure'),
1572
+ 'presentation-service': serviceLayout('presentation'),
1573
+ 'use-case': {
1574
+ title: 'Use cases',
1575
+ core: (ClassName)=>`${ClassName}UseCase`,
1576
+ files: ({ name })=>[
1577
+ `application/use-cases/${name}-use-case.ts`,
1578
+ `application/use-cases/${name}-use-case.spec.ts`,
1579
+ `wiring/use-cases/wire-${name}-use-case.ts`
1580
+ ],
1581
+ wired: true,
1582
+ sharedKernel: false
1583
+ },
1584
+ command: handlerLayout('command'),
1585
+ query: handlerLayout('query'),
1586
+ port: {
1587
+ title: 'Ports',
1588
+ core: (ClassName)=>ClassName,
1589
+ files: ({ name }, labels)=>[
1590
+ `application/ports/${name}.ts`,
1591
+ `application/ports/${name}.spec.ts`,
1592
+ ...labels.map((label)=>`infrastructure/application-adapters/${label}/${label}-${name}.ts`),
1593
+ `wiring/application-ports/wire-${name}.ts`
1594
+ ],
1595
+ implementations: 'infrastructure/application-adapters',
1596
+ wired: true,
1597
+ sharedKernel: true
1598
+ }
1524
1599
  };
1525
- const envBranchedWireArgument = (testWire, primaryWire)=>{
1526
- const { test, primary } = wire_branches_envBranches();
1527
- return `{\n${[
1528
- ...test ? [
1529
- ` ${test}: ${testWire}`
1530
- ] : [],
1531
- ...primary.map((name)=>` ${name}: ${primaryWire}`)
1532
- ].join(',\n')}\n}`;
1600
+ const integrationSpecsFolder = 'specs/integration';
1601
+ const projectRootOf = (folder)=>{
1602
+ let current = folder;
1603
+ while(true){
1604
+ if (node_fs.existsSync(node_path.join(current, 'package.json'))) return current;
1605
+ const parent = node_path.dirname(current);
1606
+ if (parent === current) return;
1607
+ current = parent;
1608
+ }
1533
1609
  };
1534
- const envBranchedWireSource = ()=>{
1535
- const { names, custom } = wire_branches_envBranches();
1536
- if (!custom) return `import { branchedWire } from '@domain-first/wire'
1537
-
1538
- export const envBranchedWire = branchedWire(() => {
1539
- return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1540
- });`;
1541
- return `import { branchedWire } from '@domain-first/wire'
1542
-
1543
- export type EnvBranch = ${names.map((name)=>`'${name}'`).join(' | ')}
1544
-
1545
- /**
1546
- * The branch this process runs in. Write how it is selected:
1547
- * until then, this function doesn't compile.
1548
- */
1549
- const currentBranch = (): EnvBranch => {
1550
- }
1551
-
1552
- export const envBranchedWire = branchedWire(currentBranch)`;
1610
+ const integrationSpecFile = (unit, label)=>{
1611
+ const layout = kindLayouts[unit.kind];
1612
+ const place = {
1613
+ ownerPath: unit.ownerPath,
1614
+ name: unit.name
1615
+ };
1616
+ const source = void 0 === label ? 'infrastructure-service' === unit.kind ? layout.files(place, [])[0] : void 0 : layout.implementations ? layout.files(place, [
1617
+ label
1618
+ ]).find((file)=>file.startsWith(`${layout.implementations}/${label}/`)) : void 0;
1619
+ const projectRoot = projectRootOf(unit.ownerPath);
1620
+ if (!source || !projectRoot) return;
1621
+ return node_path.join(projectRoot, integrationSpecsFolder, node_path.basename(unit.ownerPath), source.slice(15).replace(/\.ts$/, '.spec.ts'));
1622
+ };
1623
+ const integrationSpecSubjects = (unit)=>'infrastructure-service' === unit.kind ? [
1624
+ void 0
1625
+ ] : unit.labels;
1626
+ const integrationSpecsStop = (file)=>{
1627
+ const projectRoot = projectRootOf(node_path.dirname(file));
1628
+ if (!projectRoot) return;
1629
+ const folder = node_path.join(projectRoot, integrationSpecsFolder);
1630
+ return file.startsWith(`${folder}${node_path.sep}`) ? folder : void 0;
1553
1631
  };
1554
- const integrationFolder = 'specs/integration';
1555
- const testcontainersScripts = {
1556
- 'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
1632
+ const subfolders = (folder)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder, {
1633
+ withFileTypes: true
1634
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
1635
+ const namesBySuffix = (folder, suffix)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder).filter((file)=>file.endsWith(suffix) && !file.endsWith('.spec.ts')).map((file)=>file.slice(0, -suffix.length)).sort() : [];
1636
+ const labelsOf = (ownerPath, kind, name)=>{
1637
+ const { implementations } = kindLayouts[kind];
1638
+ if (!implementations) return [];
1639
+ return subfolders(node_path.join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
1640
+ ownerPath,
1641
+ name
1642
+ }, [
1643
+ label
1644
+ ]).some((file)=>file.startsWith(`${implementations}/`) && node_fs.existsSync(node_path.join(ownerPath, file))));
1557
1645
  };
1558
- const testcontainersVitestConfig = (inlineHandlersNext)=>{
1559
- const server = inlineHandlersNext ? `,
1560
- server: {
1561
- deps: {
1562
- // Imports \`next/headers\` without an extension, which only a bundler can resolve
1563
- inline: ['@domain-first/handlers-next']
1564
- }
1565
- }` : '';
1566
- return `import { fileURLToPath } from 'node:url';
1567
- import { defineConfig } from 'vitest/config';
1568
-
1569
- // Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
1570
- export default defineConfig({
1571
- // Paths below are relative to the project root, not this folder
1572
- root: fileURLToPath(new URL('../..', import.meta.url)),
1573
- resolve: {
1574
- tsconfigPaths: true
1575
- },
1576
- test: {
1577
- include: ['${integrationFolder}/**/*.spec.ts'],
1578
- // Development implementations work with the real database
1579
- env: { NODE_ENV: 'development' },
1580
- globalSetup: ['${integrationFolder}/global-setup.ts'],
1581
- setupFiles: ['${integrationFolder}/setup-env.ts'],
1582
- // Pulling the image on the first run takes a while
1583
- hookTimeout: 120_000${server}
1584
- }
1585
- });
1586
- `;
1646
+ const aggregatesOf = (ownerPath)=>subfolders(node_path.join(ownerPath, 'domain/aggregates')).filter((name)=>node_fs.existsSync(node_path.join(ownerPath, 'domain/aggregates', name, `${name}.aggregate-root.ts`)));
1647
+ const findBackendUnits = (ownerPath)=>{
1648
+ const unit = (kind, name, aggregate)=>({
1649
+ kind,
1650
+ name,
1651
+ ownerPath,
1652
+ aggregate,
1653
+ labels: labelsOf(ownerPath, kind, name)
1654
+ });
1655
+ const aggregates = aggregatesOf(ownerPath);
1656
+ const inAggregates = (kind)=>aggregates.flatMap((aggregate)=>namesBySuffix(node_path.join(ownerPath, 'domain/aggregates', aggregate, 'entity' === kind ? 'entities' : 'value-objects'), `.${kind}.ts`).map((name)=>unit(kind, name, aggregate)));
1657
+ const at = (folder, suffix, kind)=>namesBySuffix(node_path.join(ownerPath, folder), suffix).map((name)=>unit(kind, name));
1658
+ return [
1659
+ ...aggregates.map((name)=>unit('aggregate', name)),
1660
+ ...inAggregates('entity'),
1661
+ ...at('domain/entities', '.entity.ts', 'entity'),
1662
+ ...inAggregates('value-object'),
1663
+ ...at('domain/value-objects', '.value-object.ts', 'value-object'),
1664
+ ...at('domain/services', '-domain-service.ts', 'domain-service'),
1665
+ ...at('application/ports', '.ts', 'port'),
1666
+ ...at('application/queries', '-query.ts', 'query'),
1667
+ ...at('application/commands', '-command.ts', 'command'),
1668
+ ...at('application/use-cases', '-use-case.ts', 'use-case'),
1669
+ ...at('application/services', '-application-service.ts', 'application-service'),
1670
+ ...at('infrastructure/services', '-infrastructure-service.ts', 'infrastructure-service'),
1671
+ ...at('presentation/services', '-presentation-service.ts', 'presentation-service')
1672
+ ];
1587
1673
  };
1588
- const testcontainersGlobalSetup = (migrationCommand)=>{
1589
- const migrations = migrationCommand ? `
1590
- // dotenv in the Prisma config does not override an already set variable
1591
- execSync(${JSON.stringify(migrationCommand)}, {
1592
- cwd: project.config.root,
1593
- env: { ...process.env, DATABASE_URL: databaseUrl },
1594
- // On failure the error carries the command's output
1595
- stdio: 'pipe'
1674
+ const kebabName = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
1675
+ const lowerFirst = (value)=>value[0].toLowerCase() + value.slice(1);
1676
+ const unitMoves = (unit, target)=>{
1677
+ const layout = kindLayouts[unit.kind];
1678
+ const from = layout.files(unit, unit.labels);
1679
+ const to = layout.files(target, unit.labels);
1680
+ const moves = new Map();
1681
+ from.forEach((file, index)=>{
1682
+ const oldPath = node_path.join(unit.ownerPath, file);
1683
+ if (node_fs.existsSync(oldPath)) moves.set(oldPath, node_path.join(target.ownerPath, to[index]));
1596
1684
  });
1597
- ` : `
1598
- // Apply your migrations to databaseUrl here.
1599
- `;
1600
- return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
1601
- import type { TestProject } from 'vitest/node';
1602
-
1603
- declare module 'vitest' {
1604
- export interface ProvidedContext {
1605
- databaseUrl: string;
1685
+ for (const label of integrationSpecSubjects(unit)){
1686
+ const oldSpec = integrationSpecFile(unit, label);
1687
+ const newSpec = integrationSpecFile({
1688
+ kind: unit.kind,
1689
+ name: target.name,
1690
+ ownerPath: target.ownerPath
1691
+ }, label);
1692
+ if (oldSpec && newSpec && node_fs.existsSync(oldSpec)) moves.set(oldSpec, newSpec);
1606
1693
  }
1607
- }
1608
-
1609
- const POSTGRES_IMAGE = 'postgres:15';
1610
- const POSTGRES_PORT = 5432;
1611
- const POSTGRES_USER = 'test';
1612
- const POSTGRES_PASSWORD = 'test';
1613
- const POSTGRES_DB = 'test';
1614
-
1615
- export default async function setup(project: TestProject) {
1616
- const container = await new GenericContainer(POSTGRES_IMAGE)
1617
- .withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
1618
- .withExposedPorts(POSTGRES_PORT)
1619
- // During init PostgreSQL listens on a unix socket only and restarts,
1620
- // so checking over TCP passes once the final server is up
1621
- .withHealthCheck({
1622
- test: [
1623
- 'CMD-SHELL',
1624
- \`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
1625
- ],
1626
- interval: 250,
1627
- timeout: 1000,
1628
- retries: 1000
1629
- })
1630
- .withWaitStrategy(Wait.forHealthCheck())
1631
- .withStartupTimeout(120_000)
1632
- .start();
1633
-
1634
- const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
1635
- ${migrations}
1636
- project.provide('databaseUrl', databaseUrl);
1637
-
1638
- return async () => {
1639
- await container.stop();
1640
- };
1641
- }
1642
- `;
1643
- };
1644
- const testcontainersSetupEnv = `import 'dotenv/config';
1645
- import { inject } from 'vitest';
1646
-
1647
- // Runs before each spec's imports: development implementations get the .env
1648
- // config, and DATABASE_URL points to the container instead of the one from .env.
1649
- if (process.env.NODE_ENV !== 'development') {
1650
- throw new Error(
1651
- \`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
1652
- );
1653
- }
1654
-
1655
- process.env.DATABASE_URL = inject('databaseUrl');
1656
- `;
1657
- const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
1658
-
1659
- test('connects to the database in the container', () => {
1660
- expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
1661
- });
1662
- `;
1663
- const excludeFromUnitTests = (content)=>{
1664
- const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
1665
- if (!exclude.test(content)) return;
1666
- const entry = `'${integrationFolder}/**'`;
1667
- return content.replace(exclude, (_, items, comma, whitespace)=>{
1668
- const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
1669
- const separator = void 0 === indent ? ', ' : `,\n${indent}`;
1670
- return `${items}${separator}${entry}${comma}${whitespace}]`;
1671
- }).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
1694
+ if ('aggregate' === unit.kind) {
1695
+ const oldFolder = node_path.join(unit.ownerPath, 'domain/aggregates', unit.name);
1696
+ const newFolder = node_path.join(target.ownerPath, 'domain/aggregates', target.name);
1697
+ const own = new Set(aggregateOwnFiles(unit.name).map((file)=>node_path.join(oldFolder, file)));
1698
+ for (const file of walk(oldFolder))if (!own.has(file)) moves.set(file, node_path.join(newFolder, node_path.relative(oldFolder, file)));
1699
+ }
1700
+ return moves;
1672
1701
  };
1673
- const testcontainers_stageFile = (filePath, content)=>{
1674
- const file = new File(filePath);
1675
- if (!file.exists || file.data !== content) file.data = content;
1702
+ const validateBackendMove = (unit, target, sharedKernelPath)=>{
1703
+ if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
1704
+ if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
1705
+ 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';
1706
+ for (const [from, to] of unitMoves(unit, target))if (to !== from && node_fs.existsSync(to)) return `${node_path.relative(target.ownerPath, to)} already exists`;
1707
+ return true;
1676
1708
  };
1677
- const addTestcontainers = async ()=>{
1678
- const config = ConfigFile.Instance.data;
1679
- const root = new ProjectRoot().path;
1680
- const manifestFile = new File(node_path.join(root, 'package.json'));
1681
- const manifest = JSON.parse(manifestFile.data);
1682
- const dependencies = {
1683
- ...manifest.dependencies,
1684
- ...manifest.devDependencies
1709
+ const ownerOf = (rootFolderPath, file)=>{
1710
+ const [area, context] = node_path.relative(rootFolderPath, file).split(node_path.sep);
1711
+ if ('bounded-contexts' === area && context) return {
1712
+ context,
1713
+ path: node_path.join(rootFolderPath, area, context)
1714
+ };
1715
+ if ('shared-kernel' === area) return {
1716
+ context: void 0,
1717
+ path: node_path.join(rootFolderPath, area)
1685
1718
  };
1686
- const selected = await addPackageScripts(manifestFile, testcontainersScripts);
1687
- const withPrisma = new File(node_path.resolve(root, config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
1688
- const migrationCommand = withPrisma ? `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
1689
- const folder = node_path.join(root, integrationFolder);
1690
- testcontainers_stageFile(node_path.join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
1691
- testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
1692
- testcontainers_stageFile(node_path.join(folder, 'setup-env.ts'), testcontainersSetupEnv);
1693
- const example = new File(node_path.join(folder, 'database/database.spec.ts'));
1694
- if (!example.exists) example.data = testcontainers_exampleSpec;
1695
- const unitConfig = new File(node_path.join(root, 'vitest.config.ts'));
1696
- let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
1697
- if (!excludedFromUnitTests) {
1698
- const excluded = excludeFromUnitTests(unitConfig.data);
1699
- if (excluded) {
1700
- unitConfig.update(excluded);
1701
- excludedFromUnitTests = true;
1702
- }
1703
- }
1704
- const missing = [
1705
- 'vitest',
1706
- 'testcontainers',
1707
- 'dotenv'
1708
- ].filter((name)=>!dependencies[name]);
1709
- return [
1710
- ...missing.length ? [
1711
- `npm install --save-dev ${missing.join(' ')}`
1712
- ] : [],
1713
- `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.`,
1714
- ...migrationCommand ? [] : [
1715
- `Apply your migrations in ${integrationFolder}/global-setup.ts.`
1716
- ],
1717
- ...excludedFromUnitTests ? [] : [
1718
- `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
1719
- ],
1720
- ...wire_branches_envBranches().custom ? [
1721
- `${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.`
1722
- ] : [],
1723
- 'Docker must be running for integration specs.',
1724
- ...describeScripts(selected, {
1725
- 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
1726
- })
1727
- ];
1728
1719
  };
1729
- const vitestScripts = {
1730
- test: 'vitest run --reporter=dot --silent=passed-only',
1731
- 'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
1720
+ const inMemoryDbFile = (rootFolderPath)=>node_path.join(rootFolderPath, 'shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts');
1721
+ const isolationAllows = (rootFolderPath, from, to)=>{
1722
+ const fromOwner = ownerOf(rootFolderPath, from);
1723
+ const toOwner = ownerOf(rootFolderPath, to);
1724
+ if (!fromOwner || !toOwner?.context) return true;
1725
+ if (fromOwner.context) return fromOwner.context === toOwner.context || true === crossContextImportAllowed(from, to);
1726
+ const inside = (folder)=>to === node_path.join(toOwner.path, folder) || to.startsWith(node_path.join(toOwner.path, folder) + node_path.sep);
1727
+ return inside('domain/errors') || from.replace(codeExtension, '') === inMemoryDbFile(rootFolderPath).replace(codeExtension, '') && inside('domain');
1732
1728
  };
1733
- const vitestConfig = (rootFolder, inlineHandlersNext)=>{
1734
- const folder = (subpath)=>JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), subpath));
1735
- const server = inlineHandlersNext ? `,
1736
- server: {
1737
- deps: {
1738
- // Imports \`next/headers\` without an extension, which only a bundler can resolve
1739
- inline: ['@domain-first/handlers-next']
1729
+ const moveBackendUnit = (projectRoot, rootFolderPath, unit, target)=>{
1730
+ const layout = kindLayouts[unit.kind];
1731
+ const moves = unitMoves(unit, target);
1732
+ const withoutExtension = new Map([
1733
+ ...moves
1734
+ ].map(([from, to])=>[
1735
+ from.replace(codeExtension, ''),
1736
+ to.replace(codeExtension, '')
1737
+ ]));
1738
+ const folders = 'aggregate' === unit.kind ? [
1739
+ [
1740
+ node_path.join(unit.ownerPath, 'domain/aggregates', unit.name),
1741
+ node_path.join(target.ownerPath, 'domain/aggregates', target.name)
1742
+ ]
1743
+ ] : [];
1744
+ const movedPath = (candidate)=>{
1745
+ const extension = candidate.match(codeExtension)?.[0];
1746
+ if (extension) return moves.get(candidate);
1747
+ return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
1748
+ };
1749
+ const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
1750
+ const oldNaming = new UnknownFormatNaming(unit.name);
1751
+ const newNaming = new UnknownFormatNaming(target.name);
1752
+ const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
1753
+ const oldAggregateFolder = unit.aggregate && node_path.join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
1754
+ const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === node_path.join(oldAggregateFolder, 'index'));
1755
+ const mainFile = [
1756
+ ...moves.keys()
1757
+ ][0];
1758
+ const newMainFile = moves.get(mainFile);
1759
+ const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
1760
+ const barrelImporters = leavesAggregate ? [
1761
+ ...codeFiles
1762
+ ].filter(([file, content])=>!moves.has(file) && [
1763
+ ...content.matchAll(namedImports)
1764
+ ].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
1765
+ const violations = [];
1766
+ const relative = (file)=>toPosix(node_path.relative(projectRoot, file));
1767
+ for (const file of codeFiles.keys()){
1768
+ const from = moves.get(file) ?? file;
1769
+ for (const imported of importsOf(file)){
1770
+ const to = movedPath(imported);
1771
+ if (moves.has(file) || to) {
1772
+ if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
1773
+ relative(from),
1774
+ relative(to ?? imported)
1775
+ ]);
1740
1776
  }
1741
- }` : '';
1742
- return `import { configDefaults, defineConfig } from 'vitest/config';
1743
-
1744
- export default defineConfig({
1745
- resolve: {
1746
- tsconfigPaths: true
1747
- },
1748
- test: {
1749
- // Playwright runs end-to-end specs, test:integration runs integration ones
1750
- exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
1751
- coverage: {
1752
- provider: 'v8',
1753
- include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
1754
- exclude: [
1755
- '**/*.spec.ts',
1756
- ${folder('shared-kernel/infrastructure/**')},
1757
- ${folder('bounded-contexts/*/infrastructure/**')},
1758
- ${folder('bounded-contexts/*/presentation/rest/**')},
1759
- ${folder('shared-kernel/wiring/**')},
1760
- ${folder('bounded-contexts/*/wiring/**')}
1761
- ],
1762
- reporter: [['text', { skipFull: true }], 'html']
1763
- }${server}
1777
+ }
1764
1778
  }
1765
- });
1766
- `;
1767
- };
1768
- const addVitest = async ()=>{
1769
- const config = ConfigFile.Instance.data;
1770
- if (ConfigFile.backend.testingLibrary && 'vitest' !== ConfigFile.backend.testingLibrary && !await interaction_confirm({
1771
- key: 'replaceTestingLibrary',
1772
- requestRequired: true,
1773
- message: `Replace testing library "${ConfigFile.backend.testingLibrary}" with vitest for generated tests?`,
1774
- default: false
1775
- })) return [];
1776
- const root = new ProjectRoot().path;
1777
- const manifestFile = new File(node_path.join(root, 'package.json'));
1778
- const manifest = JSON.parse(manifestFile.data);
1779
- const dependencies = {
1780
- ...manifest.dependencies,
1781
- ...manifest.devDependencies
1779
+ for (const [file] of barrelImporters)if (!isolationAllows(rootFolderPath, file, newMainFile)) violations.push([
1780
+ relative(file),
1781
+ relative(newMainFile)
1782
+ ]);
1783
+ if (violations.length) return {
1784
+ violations
1782
1785
  };
1783
- const selected = await addPackageScripts(manifestFile, vitestScripts);
1784
- const configFile = new File(node_path.join(root, 'vitest.config.ts'));
1785
- const content = vitestConfig(config.project.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
1786
- if (!configFile.exists || configFile.data !== content) configFile.data = content;
1787
- if ('vitest' !== ConfigFile.backend.testingLibrary) ConfigFile.update({
1788
- backend: {
1789
- ...ConfigFile.backend,
1790
- testingLibrary: 'vitest'
1791
- }
1792
- });
1793
- addGitignoreEntry(root, '/coverage/');
1794
- const missing = [
1795
- 'vitest',
1796
- '@vitest/coverage-v8'
1797
- ].filter((name)=>!dependencies[name]);
1798
- return [
1799
- ...missing.length ? [
1800
- `npm install --save-dev ${missing.join(' ')}`
1801
- ] : [],
1802
- ...describeScripts(selected, {
1803
- test: 'run unit tests',
1804
- 'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
1805
- })
1786
+ const word = (form)=>`(?<![\\w$])${escapeRegExp(form)}(?![\\w$])`;
1787
+ const oldCore = layout.core(oldNaming.ClassName);
1788
+ const newCore = layout.core(newNaming.ClassName);
1789
+ const labelNames = unit.labels.map((label)=>new UnknownFormatNaming(label).ClassName);
1790
+ const prefixes = [
1791
+ ...labelNames,
1792
+ ...layout.wired ? [
1793
+ 'wire',
1794
+ ...labelNames.map((label)=>`wire${label}`)
1795
+ ] : []
1806
1796
  ];
1807
- };
1808
- const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
1809
- const mergeInstallCommands = (commands)=>{
1810
- const runtime = new Set();
1811
- const development = new Set();
1812
- const rest = [];
1813
- for (const command of commands){
1814
- const match = installCommand.exec(command);
1815
- if (!match) {
1816
- rest.push(command);
1817
- continue;
1797
+ const renames = [
1798
+ {
1799
+ pattern: new RegExp(`(?<![\\w$])(${prefixes.map(escapeRegExp).join('|')})?${escapeRegExp(oldCore)}(?![\\w$])`, 'g'),
1800
+ to: `$1${newCore}`
1801
+ },
1802
+ {
1803
+ pattern: new RegExp(word(lowerFirst(oldCore)), 'g'),
1804
+ to: lowerFirst(newCore)
1805
+ },
1806
+ {
1807
+ pattern: new RegExp(`(describe\\(\\s*['"\`])${escapeRegExp(oldNaming.withSpaces)}(?=[ '"\`])`, 'g'),
1808
+ to: `$1${newNaming.withSpaces}`,
1809
+ movedOnly: true
1818
1810
  }
1819
- for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
1820
- }
1821
- const devOnly = [
1822
- ...development
1823
- ].filter((name)=>!runtime.has(name));
1824
- return [
1825
- ...runtime.size ? [
1826
- `npm install ${[
1827
- ...runtime
1828
- ].join(' ')}`
1829
- ] : [],
1830
- ...devOnly.length ? [
1831
- `npm install --save-dev ${devOnly.join(' ')}`
1832
- ] : [],
1833
- ...rest
1834
1811
  ];
1835
- };
1836
- const printNextSteps = (nextSteps)=>{
1837
- const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
1838
- const commands = mergeInstallCommands(nextSteps.filter(isCommand));
1839
- const notes = nextSteps.filter((line)=>!isCommand(line));
1840
- const sections = [];
1841
- if (commands.length) sections.push([
1842
- 'Run this command to install the required dependencies:',
1843
- styleText([
1844
- 'bold',
1845
- 'cyan'
1846
- ], commands.join(' && '))
1847
- ].join('\n'));
1848
- if (notes.length) sections.push([
1849
- 'Additional information:',
1850
- ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
1851
- 'bold',
1852
- 'cyan'
1853
- ], path)))
1854
- ].join('\n'));
1855
- if (sections.length) console.log(sections.join('\n\n'));
1856
- };
1857
- const savePendingChanges = async ()=>{
1858
- assertAnswersConsumed();
1859
- const overwrittenFiles = filesToOverwrite({
1860
- changedOnly: isNonInteractive()
1812
+ if ('aggregate' === unit.kind) renames.push({
1813
+ pattern: new RegExp(word(oldNaming.ClassName), 'g'),
1814
+ to: newNaming.ClassName
1815
+ }, {
1816
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
1817
+ to: newNaming.variableName,
1818
+ movedOnly: true
1861
1819
  });
1862
- if (isNonInteractive() && overwrittenFiles.length && !answerFor('overwrite', false)) throw new RequestError('OVERWRITE_REQUIRED', 'Set overwrite to true to replace existing files.', {
1863
- files: overwrittenFiles.map((file)=>node_path.relative(new ProjectRoot().path, file).split(node_path.sep).join('/'))
1820
+ if ('entity' === unit.kind || 'value-object' === unit.kind) renames.push({
1821
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
1822
+ to: newNaming.variableName,
1823
+ movedOnly: true
1864
1824
  });
1865
- if (overwrittenFiles.length) {
1866
- const root = new ProjectRoot().path;
1867
- report('These files already exist and will be overwritten:');
1868
- for (const filePath of overwrittenFiles)report(` ${node_path.relative(root, filePath)}`);
1869
- const overwrite = await interaction_confirm({
1870
- key: 'overwrite',
1871
- message: 'Overwrite them?',
1872
- default: false
1873
- });
1874
- if (!overwrite) {
1875
- discardPendingChanges();
1876
- report('Cancelled: nothing was written.');
1877
- return false;
1825
+ const oldSection = new UnknownFormatNaming(plural(unit.name));
1826
+ const newSection = new UnknownFormatNaming(plural(target.name));
1827
+ const renamesSection = 'aggregate' === unit.kind && unit.name !== target.name;
1828
+ 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;
1829
+ const plan = stageModuleMove({
1830
+ projectRoot,
1831
+ stopAt: rootFolderPath,
1832
+ stopAtFor: integrationSpecsStop,
1833
+ moves,
1834
+ movedPath,
1835
+ rename: (content, { moved })=>renames.reduce((result, { pattern, to, movedOnly })=>movedOnly && !moved ? result : result.replace(pattern, to), content),
1836
+ everyFile
1837
+ });
1838
+ if (leavesAggregate && oldAggregateFolder) {
1839
+ const indexFile = new File(node_path.join(oldAggregateFolder, 'index.ts'));
1840
+ const exportLine = /^export\s+\*\s+from\s+(['"])([^'"\n]+)\1;?\s*$/;
1841
+ indexFile.update(indexFile.data.split('\n').filter((line)=>{
1842
+ const specifier = line.match(exportLine)?.[2];
1843
+ return !specifier || node_path.resolve(node_path.dirname(indexFile.path), specifier) !== newMainFile.replace(codeExtension, '');
1844
+ }).join('\n'));
1845
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
1846
+ for (const [file] of barrelImporters){
1847
+ const importer = new File(file);
1848
+ let content = importer.data;
1849
+ for (const match of content.matchAll(namedImports)){
1850
+ const [statement, typeOnly = '', names, quote, specifier] = match;
1851
+ if (!isOldBarrel(resolve(specifier, file)?.resolved)) continue;
1852
+ const items = names.split(',').map((item)=>item.trim()).filter((item)=>!!item);
1853
+ const own = new RegExp(`^(?:type\\s+)?${newNaming.ClassName}(?:\\s+as\\s+[\\w$]+)?$`);
1854
+ const moved = items.filter((item)=>own.test(item));
1855
+ if (!moved.length) continue;
1856
+ const rest = items.filter((item)=>!own.test(item));
1857
+ const direct = `import ${typeOnly}{ ${moved.join(', ')} } from ${quote}${projectRelative(file, newMainFile)}${quote}`;
1858
+ content = content.replace(statement, rest.length ? `import ${typeOnly}{ ${rest.join(', ')} } from ${quote}${specifier}${quote}\n${direct}` : direct);
1859
+ }
1860
+ importer.update(content);
1878
1861
  }
1879
1862
  }
1880
- writePendingChanges();
1881
- return true;
1863
+ if (target.aggregate && (target.aggregate !== unit.aggregate || target.ownerPath !== unit.ownerPath)) {
1864
+ const kindFolder = 'entity' === unit.kind ? 'entities' : 'value-objects';
1865
+ const indexFile = new File(node_path.join(target.ownerPath, 'domain/aggregates', target.aggregate, 'index.ts'));
1866
+ indexFile.addLineIfMissing(`export * from './${kindFolder}/${target.name}.${unit.kind}'`);
1867
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
1868
+ }
1869
+ return plan;
1882
1870
  };
1883
- const withHandlersRest = ()=>ConfigFile.Instance.data.backend?.domainFirstPackages.includes('@domain-first/handlers-rest') ?? false;
1884
- const created = (...segments)=>new File(node_path.join(new ProjectRoot().path, ...segments)).exists;
1885
- const createdInRoot = (...segments)=>created(ConfigFile.Instance.data.project.rootFolder, ...segments);
1886
- const integrationIds = [
1887
- 'storybook',
1888
- 'rest-endpoint-generator',
1889
- 'in-memory-db',
1890
- 'prisma',
1891
- 'vitest',
1892
- 'playwright',
1893
- 'testcontainers',
1894
- 'openapi',
1895
- 'orval'
1896
- ];
1897
- const integrations = [
1898
- {
1899
- id: 'storybook',
1900
- name: 'Storybook (React + Vite)',
1901
- group: 'frontend',
1902
- run: addStorybook,
1903
- applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
1904
- },
1905
- {
1906
- id: 'rest-endpoint-generator',
1907
- name: 'REST endpoint generator',
1908
- group: 'backend',
1909
- run: addRestEndpointGenerator,
1910
- available: ()=>withHandlersRest(),
1911
- applied: restEndpointGeneratorApplied
1912
- },
1913
- {
1914
- id: 'in-memory-db',
1915
- name: 'In-memory DB',
1916
- group: 'backend',
1917
- run: addInMemoryDb,
1918
- applied: inMemoryDbApplied
1919
- },
1920
- {
1921
- id: 'prisma',
1922
- name: 'Prisma 8 (PostgreSQL, RC)',
1923
- group: 'backend',
1924
- run: addPrisma,
1925
- applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
1926
- },
1927
- {
1928
- id: 'vitest',
1929
- name: 'Vitest',
1930
- group: 'backend',
1931
- run: addVitest,
1932
- applied: ()=>created('vitest.config.ts')
1933
- },
1934
- {
1935
- id: 'playwright',
1936
- name: 'Playwright',
1937
- group: 'frontend',
1938
- run: addPlaywright,
1939
- applied: ()=>created('playwright.config.ts')
1940
- },
1941
- {
1942
- id: 'testcontainers',
1943
- name: 'Integration tests (Testcontainers, PostgreSQL)',
1944
- group: 'backend',
1945
- run: addTestcontainers,
1946
- applied: ()=>created('specs/integration/vitest.config.ts')
1947
- },
1948
- {
1949
- id: 'openapi',
1950
- name: 'OpenAPI',
1951
- group: 'backend',
1952
- run: addOpenapi,
1953
- available: ()=>withHandlersRest(),
1954
- applied: ()=>created(openapiScriptPath)
1955
- },
1956
- {
1957
- id: 'orval',
1958
- name: 'Orval (API client)',
1959
- group: 'frontend',
1960
- run: addOrval,
1961
- available: ()=>withHandlersRest(),
1962
- applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
1871
+ const projectRelative = (fromFile, toFile)=>{
1872
+ const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toFile.replace(codeExtension, '')));
1873
+ return relative.startsWith('.') ? relative : `./${relative}`;
1874
+ };
1875
+ const importSpecifier = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"\n]+)\1/g;
1876
+ const importLine = /^\s*(?:import|export)\b[^'"\n]*\bfrom\s*(['"])([^'"\n]+)\1;?\s*$/;
1877
+ const deleteBackendUnit = (projectRoot, rootFolderPath, unit)=>{
1878
+ const files = [
1879
+ ...unitMoves(unit, unit).keys()
1880
+ ];
1881
+ const fileSet = new Set(files);
1882
+ const stems = new Set(files.map((file)=>file.replace(codeExtension, '')));
1883
+ const aggregateFolder = 'aggregate' === unit.kind ? node_path.join(unit.ownerPath, 'domain/aggregates', unit.name) : void 0;
1884
+ const parentAggregate = unit.aggregate ? node_path.join(unit.ownerPath, 'domain/aggregates', unit.aggregate) : void 0;
1885
+ const isUnit = (resolved)=>stems.has(resolved) || !!aggregateFolder && (resolved === aggregateFolder || resolved.startsWith(`${aggregateFolder}${node_path.sep}`));
1886
+ const isParentBarrel = (resolved)=>!!parentAggregate && (resolved === parentAggregate || resolved === node_path.join(parentAggregate, 'index'));
1887
+ const { codeFiles, resolve } = projectImports(projectRoot);
1888
+ const resolved = (specifier, file)=>resolve(specifier, file)?.resolved;
1889
+ const withoutUnitImports = (content, file)=>content.split('\n').filter((line)=>{
1890
+ const specifier = line.match(importLine)?.[2];
1891
+ const target = specifier && resolved(specifier, file);
1892
+ return !(target && isUnit(target));
1893
+ }).join('\n');
1894
+ const cleaned = new Map();
1895
+ const inMemoryDb = inMemoryDbFile(rootFolderPath);
1896
+ if ('aggregate' === unit.kind && codeFiles.has(inMemoryDb)) {
1897
+ const section = new UnknownFormatNaming(plural(unit.name));
1898
+ const original = codeFiles.get(inMemoryDb);
1899
+ const content = withoutUnitImports(original.replace(new RegExp(`^[ \\t]*${escapeRegExp(section.variableName)}\\s*=\\s*this\\.section<[^\\n]*\\n?`, 'm'), ''), inMemoryDb);
1900
+ if (content !== original) cleaned.set(inMemoryDb, content);
1963
1901
  }
1964
- ];
1965
- const addIntegration = async ({ save = true } = {})=>{
1966
- const available = integrations.filter(({ group, available })=>('backend' !== group || Boolean(ConfigFile.Instance.data.backend)) && (available?.() ?? true)).map((value)=>({
1967
- value,
1968
- applied: value.applied()
1969
- }));
1970
- const section = (title, applied)=>{
1971
- const items = [
1972
- 'backend',
1973
- 'frontend'
1974
- ].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
1975
- return items.length ? [
1976
- new Separator(title),
1977
- ...items.map(({ value })=>({
1978
- name: `${value.name} · ${value.group}`,
1979
- value
1980
- }))
1981
- ] : [];
1902
+ if (parentAggregate) {
1903
+ const index = node_path.join(parentAggregate, 'index.ts');
1904
+ const original = codeFiles.get(index);
1905
+ if (void 0 !== original) {
1906
+ const content = withoutUnitImports(original, index);
1907
+ if (content !== original) cleaned.set(index, content);
1908
+ }
1909
+ }
1910
+ const ClassName = new UnknownFormatNaming(unit.name).ClassName;
1911
+ const namedImports = /import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\2/g;
1912
+ const usedBy = [];
1913
+ const relative = (file)=>toPosix(node_path.relative(projectRoot, file));
1914
+ for (const [file, original] of codeFiles){
1915
+ if (fileSet.has(file)) continue;
1916
+ const content = cleaned.get(file) ?? original;
1917
+ for (const [, , specifier] of content.matchAll(importSpecifier)){
1918
+ const target = resolved(specifier, file);
1919
+ if (target && isUnit(target)) usedBy.push([
1920
+ relative(file),
1921
+ relative(target)
1922
+ ]);
1923
+ }
1924
+ for (const [, names, , specifier] of content.matchAll(namedImports)){
1925
+ const target = resolved(specifier, file);
1926
+ if (target && isParentBarrel(target) && new RegExp(`(?<![\\w$])${ClassName}(?![\\w$])`).test(names)) usedBy.push([
1927
+ relative(file),
1928
+ `${relative(target)} (${ClassName})`
1929
+ ]);
1930
+ }
1931
+ }
1932
+ if (usedBy.length) return {
1933
+ usedBy
1982
1934
  };
1983
- const choices = [
1984
- ...section('New integrations', false),
1985
- ...section('Already applied (select to reapply)', true)
1986
- ];
1987
- const selected = await interaction_checkbox({
1988
- key: 'integrations',
1989
- id: (integration)=>integration.id,
1990
- message: 'Integrations:',
1991
- choices,
1992
- pageSize: choices.length
1993
- });
1994
- const nextSteps = [];
1995
- for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
1996
- if (save && await savePendingChanges()) printNextSteps(nextSteps);
1997
- return nextSteps;
1998
- };
1999
- const integrationDescriptions = ()=>integrations.map((integration)=>({
2000
- id: integration.id,
2001
- name: integration.name,
2002
- group: integration.group,
2003
- available: ('backend' !== integration.group || Boolean(ConfigFile.Instance.data.backend)) && (integration.available?.() ?? true)
2004
- }));
2005
- const serviceLayout = (layer)=>({
2006
- title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
2007
- core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
2008
- files: ({ name })=>[
2009
- `${layer}/services/${name}-${layer}-service.ts`,
2010
- `${layer}/services/${name}-${layer}-service.spec.ts`,
2011
- `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
2012
- ],
2013
- wired: true,
2014
- sharedKernel: true
2015
- });
2016
- const handlerLayout = (kind)=>{
2017
- const folder = 'command' === kind ? 'commands' : 'queries';
2018
- const Suffix = 'command' === kind ? 'Command' : 'Query';
1935
+ for (const file of files)new File(file).delete(integrationSpecsStop(file) ?? rootFolderPath);
1936
+ for (const [file, content] of cleaned)new File(file).update(content);
2019
1937
  return {
2020
- title: 'command' === kind ? 'Commands' : 'Queries',
2021
- core: (ClassName)=>`${ClassName}${Suffix}`,
2022
- files: ({ name }, labels)=>[
2023
- `application/${folder}/${name}-${kind}.ts`,
2024
- `application/${folder}/${name}-${kind}.spec.ts`,
2025
- ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
2026
- `wiring/${folder}/wire-${name}-${kind}.ts`
2027
- ],
2028
- implementations: `infrastructure/${folder}`,
2029
- wired: true,
2030
- sharedKernel: false
1938
+ deleted: files,
1939
+ updated: [
1940
+ ...cleaned.keys()
1941
+ ]
2031
1942
  };
2032
1943
  };
2033
- const domainModelLayout = (kind)=>{
2034
- const folder = 'entity' === kind ? 'entities' : 'value-objects';
2035
- return {
2036
- title: 'entity' === kind ? 'Entities' : 'Value objects',
2037
- core: (ClassName)=>ClassName,
2038
- files: ({ name, aggregate })=>{
2039
- const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
2040
- return [
2041
- `${base}/${name}.${kind}.ts`,
2042
- `${base}/${name}.${kind}.spec.ts`
2043
- ];
2044
- },
2045
- wired: false,
2046
- sharedKernel: true
2047
- };
1944
+ const contractKinds = [
1945
+ 'aggregate',
1946
+ 'command',
1947
+ 'query',
1948
+ 'port'
1949
+ ];
1950
+ const implementations_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
1951
+ const withHandlers = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers');
1952
+ const contractFile = (unit)=>'aggregate' === unit.kind ? `domain/aggregates/${unit.name}/${unit.name}-repository.ts` : kindLayouts[unit.kind].files(unit, [])[0];
1953
+ const findContracts = (ownerPath)=>findBackendUnits(ownerPath).filter((unit)=>contractKinds.includes(unit.kind) && node_fs.existsSync(node_path.join(ownerPath, contractFile(unit))));
1954
+ const implementationWireName = (label)=>`wire${new UnknownFormatNaming(label).ClassName}Implementation`;
1955
+ const contractClassName = (unit)=>kindLayouts[unit.kind].core(new UnknownFormatNaming(unit.name).ClassName);
1956
+ const implementationClassName = (unit, label)=>`${new UnknownFormatNaming(label).ClassName}${contractClassName(unit)}`;
1957
+ const implementationFile = (unit, label)=>{
1958
+ const { implementations } = kindLayouts[unit.kind];
1959
+ return kindLayouts[unit.kind].files(unit, [
1960
+ label
1961
+ ]).find((file)=>file.startsWith(`${implementations}/`));
2048
1962
  };
2049
- const aggregateOwnFiles = (name)=>[
2050
- `${name}.aggregate-root.ts`,
2051
- `${name}.aggregate-root.spec.ts`,
2052
- `${name}-repository.ts`,
2053
- `${name}-repository.spec.ts`,
2054
- 'index.ts'
2055
- ];
2056
- const kindLayouts = {
2057
- aggregate: {
2058
- title: 'Aggregates',
2059
- core: (ClassName)=>`${ClassName}Repository`,
2060
- files: ({ name }, labels)=>[
2061
- ...aggregateOwnFiles(name).map((file)=>`domain/aggregates/${name}/${file}`),
2062
- ...labels.map((label)=>`infrastructure/repositories/${label}/${label}-${name}-repository.ts`),
2063
- `wiring/repositories/wire-${name}-repository.ts`
2064
- ],
2065
- implementations: 'infrastructure/repositories',
2066
- wired: true,
2067
- sharedKernel: false
2068
- },
2069
- entity: domainModelLayout('entity'),
2070
- 'value-object': domainModelLayout('value-object'),
2071
- 'domain-service': serviceLayout('domain'),
2072
- 'application-service': serviceLayout('application'),
2073
- 'infrastructure-service': serviceLayout('infrastructure'),
2074
- 'presentation-service': serviceLayout('presentation'),
2075
- 'use-case': {
2076
- title: 'Use cases',
2077
- core: (ClassName)=>`${ClassName}UseCase`,
2078
- files: ({ name })=>[
2079
- `application/use-cases/${name}-use-case.ts`,
2080
- `application/use-cases/${name}-use-case.spec.ts`,
2081
- `wiring/use-cases/wire-${name}-use-case.ts`
2082
- ],
2083
- wired: true,
2084
- sharedKernel: false
2085
- },
2086
- command: handlerLayout('command'),
2087
- query: handlerLayout('query'),
2088
- port: {
2089
- title: 'Ports',
2090
- core: (ClassName)=>ClassName,
2091
- files: ({ name }, labels)=>[
2092
- `application/ports/${name}.ts`,
2093
- `application/ports/${name}.spec.ts`,
2094
- ...labels.map((label)=>`infrastructure/application-adapters/${label}/${label}-${name}.ts`),
2095
- `wiring/application-ports/wire-${name}.ts`
2096
- ],
2097
- implementations: 'infrastructure/application-adapters',
2098
- wired: true,
2099
- sharedKernel: true
1963
+ const contractWireFile = (unit)=>kindLayouts[unit.kind].files(unit, []).find((file)=>file.startsWith('wiring/'));
1964
+ const handlerImplementation = (ContractName, ClassName, contractImport)=>withHandlers() ? `
1965
+ import { defineHandler } from '@domain-first/handlers'
1966
+ import { ${ContractName} } from '${contractImport}'
1967
+
1968
+ export class ${ClassName} extends ${ContractName} {
1969
+ constructor() {
1970
+ super()
2100
1971
  }
2101
- };
2102
- const subfolders = (folder)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder, {
2103
- withFileTypes: true
2104
- }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
2105
- const namesBySuffix = (folder, suffix)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder).filter((file)=>file.endsWith(suffix) && !file.endsWith('.spec.ts')).map((file)=>file.slice(0, -suffix.length)).sort() : [];
2106
- const labelsOf = (ownerPath, kind, name)=>{
2107
- const { implementations } = kindLayouts[kind];
2108
- if (!implementations) return [];
2109
- return subfolders(node_path.join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
2110
- ownerPath,
2111
- name
2112
- }, [
2113
- label
2114
- ]).some((file)=>file.startsWith(`${implementations}/`) && node_fs.existsSync(node_path.join(ownerPath, file))));
2115
- };
2116
- const aggregatesOf = (ownerPath)=>subfolders(node_path.join(ownerPath, 'domain/aggregates')).filter((name)=>node_fs.existsSync(node_path.join(ownerPath, 'domain/aggregates', name, `${name}.aggregate-root.ts`)));
2117
- const findBackendUnits = (ownerPath)=>{
2118
- const unit = (kind, name, aggregate)=>({
2119
- kind,
2120
- name,
2121
- ownerPath,
2122
- aggregate,
2123
- labels: labelsOf(ownerPath, kind, name)
2124
- });
2125
- const aggregates = aggregatesOf(ownerPath);
2126
- const inAggregates = (kind)=>aggregates.flatMap((aggregate)=>namesBySuffix(node_path.join(ownerPath, 'domain/aggregates', aggregate, 'entity' === kind ? 'entities' : 'value-objects'), `.${kind}.ts`).map((name)=>unit(kind, name, aggregate)));
2127
- const at = (folder, suffix, kind)=>namesBySuffix(node_path.join(ownerPath, folder), suffix).map((name)=>unit(kind, name));
2128
- return [
2129
- ...aggregates.map((name)=>unit('aggregate', name)),
2130
- ...inAggregates('entity'),
2131
- ...at('domain/entities', '.entity.ts', 'entity'),
2132
- ...inAggregates('value-object'),
2133
- ...at('domain/value-objects', '.value-object.ts', 'value-object'),
2134
- ...at('domain/services', '-domain-service.ts', 'domain-service'),
2135
- ...at('application/ports', '.ts', 'port'),
2136
- ...at('application/queries', '-query.ts', 'query'),
2137
- ...at('application/commands', '-command.ts', 'command'),
2138
- ...at('application/use-cases', '-use-case.ts', 'use-case'),
2139
- ...at('application/services', '-application-service.ts', 'application-service'),
2140
- ...at('infrastructure/services', '-infrastructure-service.ts', 'infrastructure-service'),
2141
- ...at('presentation/services', '-presentation-service.ts', 'presentation-service')
1972
+
1973
+ handle = defineHandler({
1974
+ inputSchema: ${ContractName}.inputSchema,
1975
+ outputSchema: ${ContractName}.outputSchema,
1976
+ handler: async (input) => {
1977
+ return {}
1978
+ }
1979
+ })
1980
+ }
1981
+ `.trim() : `
1982
+ import { ${ContractName} } from '${contractImport}'
1983
+
1984
+ export class ${ClassName} extends ${ContractName} {
1985
+ constructor() {
1986
+ super()
1987
+ }
1988
+ }
1989
+ `.trim();
1990
+ const createImplementation = (ownerFolder, unit, label)=>{
1991
+ const naming = new UnknownFormatNaming(unit.name);
1992
+ const ContractName = contractClassName(unit);
1993
+ const className = implementationClassName(unit, label);
1994
+ const [folder, fileName] = [
1995
+ node_path.dirname(implementationFile(unit, label)),
1996
+ node_path.basename(implementationFile(unit, label))
2142
1997
  ];
2143
- };
2144
- const kebabName = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
2145
- const lowerFirst = (value)=>value[0].toLowerCase() + value.slice(1);
2146
- const unitMoves = (unit, target)=>{
2147
- const layout = kindLayouts[unit.kind];
2148
- const from = layout.files(unit, unit.labels);
2149
- const to = layout.files(target, unit.labels);
2150
- const moves = new Map();
2151
- from.forEach((file, index)=>{
2152
- const oldPath = node_path.join(unit.ownerPath, file);
2153
- if (node_fs.existsSync(oldPath)) moves.set(oldPath, node_path.join(target.ownerPath, to[index]));
2154
- });
2155
- if ('aggregate' === unit.kind) {
2156
- const oldFolder = node_path.join(unit.ownerPath, 'domain/aggregates', unit.name);
2157
- const newFolder = node_path.join(target.ownerPath, 'domain/aggregates', target.name);
2158
- const own = new Set(aggregateOwnFiles(unit.name).map((file)=>node_path.join(oldFolder, file)));
2159
- for (const file of walk(oldFolder))if (!own.has(file)) moves.set(file, node_path.join(newFolder, node_path.relative(oldFolder, file)));
1998
+ const implementationFolder = ownerFolder.subitem(folder.split('/'));
1999
+ const inMemoryDb = !implementations_withWiring() && usesInMemoryDb(label);
2000
+ switch(unit.kind){
2001
+ case 'aggregate':
2002
+ {
2003
+ const contractImport = `../../../domain/aggregates/${unit.name}`;
2004
+ if (inMemoryDb) {
2005
+ const section = addInMemoryDbSection(naming, ownerFolder.subitem([
2006
+ 'domain',
2007
+ 'aggregates',
2008
+ unit.name
2009
+ ]).path);
2010
+ const file = implementationFolder.createFile(fileName, `
2011
+ ${inMemoryDbTypeImport(implementationFolder.subitem([
2012
+ fileName
2013
+ ]).path)}
2014
+ import { ${ContractName} } from '${contractImport}'
2015
+
2016
+ export class ${className} implements ${ContractName} {
2017
+ ${inMemoryDbSectionMembers(section, false)}
2018
+ }
2019
+ `.trim());
2020
+ return {
2021
+ file,
2022
+ className
2023
+ };
2024
+ }
2025
+ const file = implementationFolder.createFile(fileName, `
2026
+ import { ${ContractName} } from '${contractImport}'
2027
+
2028
+ export class ${className} implements ${ContractName} {
2029
+ constructor() {}
2030
+ }
2031
+
2032
+ `.trim());
2033
+ return {
2034
+ file,
2035
+ className
2036
+ };
2037
+ }
2038
+ case 'command':
2039
+ case 'query':
2040
+ {
2041
+ const folderName = 'command' === unit.kind ? 'commands' : 'queries';
2042
+ const file = implementationFolder.createFile(fileName, handlerImplementation(ContractName, className, `../../../application/${folderName}/${naming.fileName}-${unit.kind}`));
2043
+ if (inMemoryDb) injectInMemoryDb(file, className);
2044
+ return {
2045
+ file,
2046
+ className
2047
+ };
2048
+ }
2049
+ case 'port':
2050
+ {
2051
+ const file = implementationFolder.createFile(fileName, `
2052
+ import { ${ContractName} } from '../../../application/ports/${naming.fileName}'
2053
+
2054
+ export class ${className} extends ${ContractName} {
2055
+
2056
+ }
2057
+ `.trim());
2058
+ return {
2059
+ file,
2060
+ className
2061
+ };
2062
+ }
2063
+ default:
2064
+ throw new Error(`${unit.kind} has no implementations`);
2160
2065
  }
2161
- return moves;
2162
- };
2163
- const validateBackendMove = (unit, target, sharedKernelPath)=>{
2164
- if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
2165
- if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
2166
- 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';
2167
- for (const [from, to] of unitMoves(unit, target))if (to !== from && node_fs.existsSync(to)) return `${node_path.relative(target.ownerPath, to)} already exists`;
2168
- return true;
2169
2066
  };
2170
- const ownerOf = (rootFolderPath, file)=>{
2171
- const [area, context] = node_path.relative(rootFolderPath, file).split(node_path.sep);
2172
- if ('bounded-contexts' === area && context) return {
2173
- context,
2174
- path: node_path.join(rootFolderPath, area, context)
2175
- };
2176
- if ('shared-kernel' === area) return {
2177
- context: void 0,
2178
- path: node_path.join(rootFolderPath, area)
2179
- };
2180
- };
2181
- const inMemoryDbFile = (rootFolderPath)=>node_path.join(rootFolderPath, 'shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts');
2182
- const isolationAllows = (rootFolderPath, from, to)=>{
2183
- const fromOwner = ownerOf(rootFolderPath, from);
2184
- const toOwner = ownerOf(rootFolderPath, to);
2185
- if (!fromOwner || !toOwner?.context) return true;
2186
- if (fromOwner.context) return fromOwner.context === toOwner.context || true === crossContextImportAllowed(from, to);
2187
- const inside = (folder)=>to === node_path.join(toOwner.path, folder) || to.startsWith(node_path.join(toOwner.path, folder) + node_path.sep);
2188
- return inside('domain/errors') || from.replace(codeExtension, '') === inMemoryDbFile(rootFolderPath).replace(codeExtension, '') && inside('domain');
2189
- };
2190
- const moveBackendUnit = (projectRoot, rootFolderPath, unit, target)=>{
2191
- const layout = kindLayouts[unit.kind];
2192
- const moves = unitMoves(unit, target);
2193
- const withoutExtension = new Map([
2194
- ...moves
2195
- ].map(([from, to])=>[
2196
- from.replace(codeExtension, ''),
2197
- to.replace(codeExtension, '')
2198
- ]));
2199
- const folders = 'aggregate' === unit.kind ? [
2200
- [
2201
- node_path.join(unit.ownerPath, 'domain/aggregates', unit.name),
2202
- node_path.join(target.ownerPath, 'domain/aggregates', target.name)
2203
- ]
2204
- ] : [];
2205
- const movedPath = (candidate)=>{
2206
- const extension = candidate.match(codeExtension)?.[0];
2207
- if (extension) return moves.get(candidate);
2208
- return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
2067
+ const inMemoryRepositoryWiring = (ownerFolder, unit, wireFile)=>(implementation, dependency)=>{
2068
+ if ('aggregate' !== unit.kind || !isInMemoryDb(dependency)) return false;
2069
+ keepInMemoryDbSection(new File(implementation.file), addInMemoryDbSection(new UnknownFormatNaming(unit.name), ownerFolder.subitem([
2070
+ 'domain',
2071
+ 'aggregates',
2072
+ unit.name
2073
+ ]).path));
2074
+ wireInMemoryDb(wireFile, implementation.className);
2075
+ return true;
2209
2076
  };
2210
- const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
2211
- const oldNaming = new UnknownFormatNaming(unit.name);
2212
- const newNaming = new UnknownFormatNaming(target.name);
2213
- const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
2214
- const oldAggregateFolder = unit.aggregate && node_path.join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
2215
- const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === node_path.join(oldAggregateFolder, 'index'));
2216
- const mainFile = [
2217
- ...moves.keys()
2218
- ][0];
2219
- const newMainFile = moves.get(mainFile);
2220
- const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
2221
- const barrelImporters = leavesAggregate ? [
2222
- ...codeFiles
2223
- ].filter(([file, content])=>!moves.has(file) && [
2224
- ...content.matchAll(namedImports)
2225
- ].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
2226
- const violations = [];
2227
- const relative = (file)=>toPosix(node_path.relative(projectRoot, file));
2228
- for (const file of codeFiles.keys()){
2229
- const from = moves.get(file) ?? file;
2230
- for (const imported of importsOf(file)){
2231
- const to = movedPath(imported);
2232
- if (moves.has(file) || to) {
2233
- if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
2234
- relative(from),
2235
- relative(to ?? imported)
2236
- ]);
2077
+ const integration_tests_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
2078
+ const integrationSpecsAvailable = ()=>integration_tests_withWiring() && new File(node_path.join(new ProjectRoot().path, integrationSpecsFolder, 'vitest.config.ts')).exists;
2079
+ const systemImplementationTypes = new Set([
2080
+ inMemoryImplementationType,
2081
+ crossContextImplementation
2082
+ ]);
2083
+ const integrationTestTypes = ()=>ConfigFile.backend.implementations?.integrationTests ?? [];
2084
+ const setIntegrationTestTypes = (types)=>{
2085
+ const backend = ConfigFile.backend;
2086
+ ConfigFile.update({
2087
+ backend: {
2088
+ ...backend,
2089
+ implementations: {
2090
+ ...backend.implementations,
2091
+ integrationTests: [
2092
+ ...new Set(types)
2093
+ ]
2237
2094
  }
2238
2095
  }
2239
- }
2240
- for (const [file] of barrelImporters)if (!isolationAllows(rootFolderPath, file, newMainFile)) violations.push([
2241
- relative(file),
2242
- relative(newMainFile)
2243
- ]);
2244
- if (violations.length) return {
2245
- violations
2246
- };
2247
- const word = (form)=>`(?<![\\w$])${escapeRegExp(form)}(?![\\w$])`;
2248
- const oldCore = layout.core(oldNaming.ClassName);
2249
- const newCore = layout.core(newNaming.ClassName);
2250
- const prefixes = [
2251
- ...unit.labels.map((label)=>new UnknownFormatNaming(label).ClassName),
2252
- ...layout.wired ? [
2253
- 'wire'
2254
- ] : []
2255
- ];
2256
- const renames = [
2257
- {
2258
- pattern: new RegExp(`(?<![\\w$])(${prefixes.map(escapeRegExp).join('|')})?${escapeRegExp(oldCore)}(?![\\w$])`, 'g'),
2259
- to: `$1${newCore}`
2260
- },
2261
- {
2262
- pattern: new RegExp(word(lowerFirst(oldCore)), 'g'),
2263
- to: lowerFirst(newCore)
2264
- },
2265
- {
2266
- pattern: new RegExp(`(describe\\(\\s*['"\`])${escapeRegExp(oldNaming.withSpaces)}(?=[ '"\`])`, 'g'),
2267
- to: `$1${newNaming.withSpaces}`,
2268
- movedOnly: true
2269
- }
2270
- ];
2271
- if ('aggregate' === unit.kind) renames.push({
2272
- pattern: new RegExp(word(oldNaming.ClassName), 'g'),
2273
- to: newNaming.ClassName
2274
- }, {
2275
- pattern: new RegExp(word(oldNaming.variableName), 'g'),
2276
- to: newNaming.variableName,
2277
- movedOnly: true
2278
2096
  });
2279
- if ('entity' === unit.kind || 'value-object' === unit.kind) renames.push({
2280
- pattern: new RegExp(word(oldNaming.variableName), 'g'),
2281
- to: newNaming.variableName,
2282
- movedOnly: true
2097
+ };
2098
+ const importPath = (fromFile, toFile)=>{
2099
+ const relative = node_path.relative(node_path.dirname(fromFile), toFile).replace(/\.ts$/, '').split(node_path.sep).join('/');
2100
+ return relative.startsWith('.') ? relative : `./${relative}`;
2101
+ };
2102
+ const exportImplementationWire = (wireFile, label)=>{
2103
+ if (!wireFile.exists) return false;
2104
+ const name = implementationWireName(label);
2105
+ const declaration = new RegExp(`^(export\\s+)?const\\s+${name}\\b`, 'm');
2106
+ const match = wireFile.data.match(declaration);
2107
+ if (!match) return false;
2108
+ if (!match[1]) wireFile.update(wireFile.data.replace(declaration, `export const ${name}`));
2109
+ return true;
2110
+ };
2111
+ const renderSpec = ({ title, className, classFile, wireImport, wireFile, factory, specPath })=>`
2112
+ import { describe, test, expect } from 'vitest'
2113
+ import { ${className} } from '${importPath(specPath, classFile)}'
2114
+ import { ${wireImport} } from '${importPath(specPath, wireFile)}'
2115
+
2116
+ describe('${title}', () => {
2117
+ test('can be wired', () => {
2118
+ expect(${factory}()).toBeInstanceOf(${className})
2119
+ })
2120
+
2121
+ test.todo('works against the infrastructure')
2122
+ })
2123
+ `.trimStart();
2124
+ const scaffoldIntegrationSpec = (unit, label)=>{
2125
+ const specPath = integrationSpecFile(unit, label);
2126
+ if (!specPath) return;
2127
+ const spec = new File(specPath);
2128
+ if (spec.exists) return;
2129
+ const layout = kindLayouts[unit.kind];
2130
+ const naming = new UnknownFormatNaming(unit.name);
2131
+ const core = layout.core(naming.ClassName);
2132
+ const files = layout.files({
2133
+ ownerPath: unit.ownerPath,
2134
+ name: unit.name
2135
+ }, void 0 === label ? [] : [
2136
+ label
2137
+ ]);
2138
+ const wireFile = new File(node_path.join(unit.ownerPath, files.find((file)=>file.startsWith('wiring/'))));
2139
+ if (void 0 === label) {
2140
+ const factory = `wire${core}`;
2141
+ spec.data = renderSpec({
2142
+ title: naming.withSpaces,
2143
+ className: core,
2144
+ classFile: node_path.join(unit.ownerPath, files[0]),
2145
+ wireImport: factory,
2146
+ wireFile: wireFile.path,
2147
+ factory,
2148
+ specPath
2149
+ });
2150
+ return spec;
2151
+ }
2152
+ const className = `${new UnknownFormatNaming(label).ClassName}${core}`;
2153
+ if (!exportImplementationWire(wireFile, label)) return void report(`No integration spec for ${className}: ${wireFile.path} has no ${implementationWireName(label)} factory.`);
2154
+ const factory = `wire${className}`;
2155
+ const wireImport = `${implementationWireName(label)} as ${factory}`;
2156
+ const title = 'aggregate' === unit.kind ? `${naming.withSpaces} repository` : 'port' === unit.kind ? naming.withSpaces : `${naming.withSpaces} ${unit.kind}`;
2157
+ spec.data = renderSpec({
2158
+ title: `${title} (${label})`,
2159
+ className,
2160
+ classFile: node_path.join(unit.ownerPath, files.find((file)=>file.startsWith(`${layout.implementations}/${label}/`))),
2161
+ wireImport,
2162
+ wireFile: wireFile.path,
2163
+ factory,
2164
+ specPath
2165
+ });
2166
+ return spec;
2167
+ };
2168
+ const unusedAnswer = ()=>new RequestError('UNUSED_PARAMETERS', 'implementation.integrationTests applies only to a newly entered primary implementation type, with the Testcontainers integration and wiring.', {
2169
+ fields: [
2170
+ 'implementation.integrationTests'
2171
+ ]
2283
2172
  });
2284
- const oldSection = new UnknownFormatNaming(plural(unit.name));
2285
- const newSection = new UnknownFormatNaming(plural(target.name));
2286
- const renamesSection = 'aggregate' === unit.kind && unit.name !== target.name;
2287
- 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;
2288
- const plan = stageModuleMove({
2289
- projectRoot,
2290
- stopAt: rootFolderPath,
2291
- moves,
2292
- movedPath,
2293
- rename: (content, { moved })=>renames.reduce((result, { pattern, to, movedOnly })=>movedOnly && !moved ? result : result.replace(pattern, to), content),
2294
- everyFile
2173
+ const wantsIntegrationTests = async (label, { entered, save })=>{
2174
+ const answer = isNonInteractive() ? answerFor('implementation')?.integrationTests : void 0;
2175
+ const applies = integrationSpecsAvailable() && entered && !systemImplementationTypes.has(label) && !integrationTestTypes().includes(label);
2176
+ if (!applies) {
2177
+ if (void 0 !== answer) throw unusedAnswer();
2178
+ return integrationSpecsAvailable() && integrationTestTypes().includes(label);
2179
+ }
2180
+ const wanted = isNonInteractive() ? answer ?? true : await interaction_confirm({
2181
+ message: `Generate integration tests for ${label} implementations?`,
2182
+ default: true
2295
2183
  });
2296
- if (leavesAggregate && oldAggregateFolder) {
2297
- const indexFile = new File(node_path.join(oldAggregateFolder, 'index.ts'));
2298
- const exportLine = /^export\s+\*\s+from\s+(['"])([^'"\n]+)\1;?\s*$/;
2299
- indexFile.update(indexFile.data.split('\n').filter((line)=>{
2300
- const specifier = line.match(exportLine)?.[2];
2301
- return !specifier || node_path.resolve(node_path.dirname(indexFile.path), specifier) !== newMainFile.replace(codeExtension, '');
2302
- }).join('\n'));
2303
- if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
2304
- for (const [file] of barrelImporters){
2305
- const importer = new File(file);
2306
- let content = importer.data;
2307
- for (const match of content.matchAll(namedImports)){
2308
- const [statement, typeOnly = '', names, quote, specifier] = match;
2309
- if (!isOldBarrel(resolve(specifier, file)?.resolved)) continue;
2310
- const items = names.split(',').map((item)=>item.trim()).filter((item)=>!!item);
2311
- const own = new RegExp(`^(?:type\\s+)?${newNaming.ClassName}(?:\\s+as\\s+[\\w$]+)?$`);
2312
- const moved = items.filter((item)=>own.test(item));
2313
- if (!moved.length) continue;
2314
- const rest = items.filter((item)=>!own.test(item));
2315
- const direct = `import ${typeOnly}{ ${moved.join(', ')} } from ${quote}${projectRelative(file, newMainFile)}${quote}`;
2316
- content = content.replace(statement, rest.length ? `import ${typeOnly}{ ${rest.join(', ')} } from ${quote}${specifier}${quote}\n${direct}` : direct);
2184
+ if (wanted && save) setIntegrationTestTypes([
2185
+ ...integrationTestTypes(),
2186
+ label
2187
+ ]);
2188
+ return wanted;
2189
+ };
2190
+ const wantsServiceIntegrationSpec = async ()=>integrationSpecsAvailable() && await interaction_confirm({
2191
+ key: 'integrationSpec',
2192
+ message: 'Generate an integration spec?',
2193
+ default: false
2194
+ });
2195
+ const defaultEnvBranches = {
2196
+ names: [
2197
+ 'test',
2198
+ 'development',
2199
+ 'production'
2200
+ ],
2201
+ test: 'test'
2202
+ };
2203
+ const wire_branches_envBranches = ()=>{
2204
+ const configured = ConfigFile.exists ? ConfigFile.Instance.data.backend?.envBranches : void 0;
2205
+ const { names, test } = configured ?? defaultEnvBranches;
2206
+ return {
2207
+ names,
2208
+ test,
2209
+ primary: names.filter((name)=>name !== test),
2210
+ custom: Boolean(configured)
2211
+ };
2212
+ };
2213
+ const offersTestImplementation = ()=>{
2214
+ const backend = ConfigFile.exists ? ConfigFile.Instance.data.backend : void 0;
2215
+ return !(backend?.domainFirstPackages.includes('@domain-first/wire') && backend.envBranches && void 0 === backend.envBranches.test);
2216
+ };
2217
+ const envBranchedWireArgument = (testWire, primaryWire)=>{
2218
+ const { test, primary } = wire_branches_envBranches();
2219
+ return `{\n${[
2220
+ ...test ? [
2221
+ ` ${test}: ${testWire}`
2222
+ ] : [],
2223
+ ...primary.map((name)=>` ${name}: ${primaryWire}`)
2224
+ ].join(',\n')}\n}`;
2225
+ };
2226
+ const envBranchedWireSource = ()=>{
2227
+ const { names, custom } = wire_branches_envBranches();
2228
+ if (!custom) return `import { branchedWire } from '@domain-first/wire'
2229
+
2230
+ export const envBranchedWire = branchedWire(() => {
2231
+ return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
2232
+ });`;
2233
+ return `import { branchedWire } from '@domain-first/wire'
2234
+
2235
+ export type EnvBranch = ${names.map((name)=>`'${name}'`).join(' | ')}
2236
+
2237
+ /**
2238
+ * The branch this process runs in. Write how it is selected:
2239
+ * until then, this function doesn't compile.
2240
+ */
2241
+ const currentBranch = (): EnvBranch => {
2242
+ }
2243
+
2244
+ export const envBranchedWire = branchedWire(currentBranch)`;
2245
+ };
2246
+ const integrationFolder = 'specs/integration';
2247
+ const testcontainersScripts = {
2248
+ 'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
2249
+ };
2250
+ const testcontainersVitestConfig = (inlineHandlersNext)=>{
2251
+ const server = inlineHandlersNext ? `,
2252
+ server: {
2253
+ deps: {
2254
+ // Imports \`next/headers\` without an extension, which only a bundler can resolve
2255
+ inline: ['@domain-first/handlers-next']
2317
2256
  }
2318
- importer.update(content);
2319
- }
2320
- }
2321
- if (target.aggregate && (target.aggregate !== unit.aggregate || target.ownerPath !== unit.ownerPath)) {
2322
- const kindFolder = 'entity' === unit.kind ? 'entities' : 'value-objects';
2323
- const indexFile = new File(node_path.join(target.ownerPath, 'domain/aggregates', target.aggregate, 'index.ts'));
2324
- indexFile.addLineIfMissing(`export * from './${kindFolder}/${target.name}.${unit.kind}'`);
2325
- if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
2257
+ }` : '';
2258
+ return `import { fileURLToPath } from 'node:url';
2259
+ import { defineConfig } from 'vitest/config';
2260
+
2261
+ // Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
2262
+ export default defineConfig({
2263
+ // Paths below are relative to the project root, not this folder
2264
+ root: fileURLToPath(new URL('../..', import.meta.url)),
2265
+ resolve: {
2266
+ tsconfigPaths: true
2267
+ },
2268
+ test: {
2269
+ include: ['${integrationFolder}/**/*.spec.ts'],
2270
+ // Development implementations work with the real database
2271
+ env: { NODE_ENV: 'development' },
2272
+ globalSetup: ['${integrationFolder}/global-setup.ts'],
2273
+ setupFiles: ['${integrationFolder}/setup-env.ts'],
2274
+ // Pulling the image on the first run takes a while
2275
+ hookTimeout: 120_000${server}
2326
2276
  }
2327
- return plan;
2277
+ });
2278
+ `;
2328
2279
  };
2329
- const projectRelative = (fromFile, toFile)=>{
2330
- const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toFile.replace(codeExtension, '')));
2331
- return relative.startsWith('.') ? relative : `./${relative}`;
2280
+ const testcontainersGlobalSetup = (migrationCommand)=>{
2281
+ const migrations = migrationCommand ? `
2282
+ // dotenv in the Prisma config does not override an already set variable
2283
+ execSync(${JSON.stringify(migrationCommand)}, {
2284
+ cwd: project.config.root,
2285
+ env: { ...process.env, DATABASE_URL: databaseUrl },
2286
+ // On failure the error carries the command's output
2287
+ stdio: 'pipe'
2288
+ });
2289
+ ` : `
2290
+ // Apply your migrations to databaseUrl here.
2291
+ `;
2292
+ return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
2293
+ import type { TestProject } from 'vitest/node';
2294
+
2295
+ declare module 'vitest' {
2296
+ export interface ProvidedContext {
2297
+ databaseUrl: string;
2298
+ }
2299
+ }
2300
+
2301
+ const POSTGRES_IMAGE = 'postgres:15';
2302
+ const POSTGRES_PORT = 5432;
2303
+ const POSTGRES_USER = 'test';
2304
+ const POSTGRES_PASSWORD = 'test';
2305
+ const POSTGRES_DB = 'test';
2306
+
2307
+ export default async function setup(project: TestProject) {
2308
+ const container = await new GenericContainer(POSTGRES_IMAGE)
2309
+ .withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
2310
+ .withExposedPorts(POSTGRES_PORT)
2311
+ // During init PostgreSQL listens on a unix socket only and restarts,
2312
+ // so checking over TCP passes once the final server is up
2313
+ .withHealthCheck({
2314
+ test: [
2315
+ 'CMD-SHELL',
2316
+ \`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
2317
+ ],
2318
+ interval: 250,
2319
+ timeout: 1000,
2320
+ retries: 1000
2321
+ })
2322
+ .withWaitStrategy(Wait.forHealthCheck())
2323
+ .withStartupTimeout(120_000)
2324
+ .start();
2325
+
2326
+ const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
2327
+ ${migrations}
2328
+ project.provide('databaseUrl', databaseUrl);
2329
+
2330
+ return async () => {
2331
+ await container.stop();
2332
+ };
2333
+ }
2334
+ `;
2332
2335
  };
2333
- const importSpecifier = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"\n]+)\1/g;
2334
- const importLine = /^\s*(?:import|export)\b[^'"\n]*\bfrom\s*(['"])([^'"\n]+)\1;?\s*$/;
2335
- const deleteBackendUnit = (projectRoot, rootFolderPath, unit)=>{
2336
- const files = [
2337
- ...unitMoves(unit, unit).keys()
2338
- ];
2339
- const fileSet = new Set(files);
2340
- const stems = new Set(files.map((file)=>file.replace(codeExtension, '')));
2341
- const aggregateFolder = 'aggregate' === unit.kind ? node_path.join(unit.ownerPath, 'domain/aggregates', unit.name) : void 0;
2342
- const parentAggregate = unit.aggregate ? node_path.join(unit.ownerPath, 'domain/aggregates', unit.aggregate) : void 0;
2343
- const isUnit = (resolved)=>stems.has(resolved) || !!aggregateFolder && (resolved === aggregateFolder || resolved.startsWith(`${aggregateFolder}${node_path.sep}`));
2344
- const isParentBarrel = (resolved)=>!!parentAggregate && (resolved === parentAggregate || resolved === node_path.join(parentAggregate, 'index'));
2345
- const { codeFiles, resolve } = projectImports(projectRoot);
2346
- const resolved = (specifier, file)=>resolve(specifier, file)?.resolved;
2347
- const withoutUnitImports = (content, file)=>content.split('\n').filter((line)=>{
2348
- const specifier = line.match(importLine)?.[2];
2349
- const target = specifier && resolved(specifier, file);
2350
- return !(target && isUnit(target));
2351
- }).join('\n');
2352
- const cleaned = new Map();
2353
- const inMemoryDb = inMemoryDbFile(rootFolderPath);
2354
- if ('aggregate' === unit.kind && codeFiles.has(inMemoryDb)) {
2355
- const section = new UnknownFormatNaming(plural(unit.name));
2356
- const original = codeFiles.get(inMemoryDb);
2357
- const content = withoutUnitImports(original.replace(new RegExp(`^[ \\t]*${escapeRegExp(section.variableName)}\\s*=\\s*this\\.section<[^\\n]*\\n?`, 'm'), ''), inMemoryDb);
2358
- if (content !== original) cleaned.set(inMemoryDb, content);
2336
+ const testcontainersSetupEnv = `import 'dotenv/config';
2337
+ import { inject } from 'vitest';
2338
+
2339
+ // Runs before each spec's imports: development implementations get the .env
2340
+ // config, and DATABASE_URL points to the container instead of the one from .env.
2341
+ if (process.env.NODE_ENV !== 'development') {
2342
+ throw new Error(
2343
+ \`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
2344
+ );
2345
+ }
2346
+
2347
+ process.env.DATABASE_URL = inject('databaseUrl');
2348
+ `;
2349
+ const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
2350
+
2351
+ test('connects to the database in the container', () => {
2352
+ expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
2353
+ });
2354
+ `;
2355
+ const excludeFromUnitTests = (content)=>{
2356
+ const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
2357
+ if (!exclude.test(content)) return;
2358
+ const entry = `'${integrationFolder}/**'`;
2359
+ return content.replace(exclude, (_, items, comma, whitespace)=>{
2360
+ const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
2361
+ const separator = void 0 === indent ? ', ' : `,\n${indent}`;
2362
+ return `${items}${separator}${entry}${comma}${whitespace}]`;
2363
+ }).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
2364
+ };
2365
+ const testcontainers_stageFile = (filePath, content)=>{
2366
+ const file = new File(filePath);
2367
+ if (!file.exists || file.data !== content) file.data = content;
2368
+ };
2369
+ const configureIntegrationTests = async (root)=>{
2370
+ if (!ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) return;
2371
+ const kindsOf = new Map();
2372
+ for (const kind of implementationKinds)for (const label of savedImplementations(kind, 'primary'))if (!systemImplementationTypes.has(label)) kindsOf.set(label, [
2373
+ ...kindsOf.get(label) ?? [],
2374
+ kind
2375
+ ]);
2376
+ const current = integrationTestTypes();
2377
+ if (kindsOf.size) {
2378
+ const selected = await interaction_checkbox({
2379
+ key: 'integrationTestTypes',
2380
+ message: 'Integration tests for implementation types:',
2381
+ choices: [
2382
+ ...kindsOf
2383
+ ].map(([value, kinds])=>({
2384
+ name: `${value} (${kinds.join(', ')})`,
2385
+ value,
2386
+ checked: current.includes(value)
2387
+ }))
2388
+ });
2389
+ const kept = current.filter((label)=>!kindsOf.has(label));
2390
+ const next = [
2391
+ ...selected,
2392
+ ...kept
2393
+ ];
2394
+ if (next.length !== current.length || next.some((label)=>!current.includes(label))) setIntegrationTestTypes(next);
2359
2395
  }
2360
- if (parentAggregate) {
2361
- const index = node_path.join(parentAggregate, 'index.ts');
2362
- const original = codeFiles.get(index);
2363
- if (void 0 !== original) {
2364
- const content = withoutUnitImports(original, index);
2365
- if (content !== original) cleaned.set(index, content);
2396
+ const types = integrationTestTypes();
2397
+ if (!types.length) return;
2398
+ const testBranch = wire_branches_envBranches().test;
2399
+ const source = new Folder(root).subitem([
2400
+ ConfigFile.Instance.data.project.rootFolder
2401
+ ]);
2402
+ const owners = [
2403
+ source.subitem([
2404
+ 'shared-kernel'
2405
+ ]),
2406
+ ...source.subitem([
2407
+ 'bounded-contexts'
2408
+ ]).content.subfolderNames.sort().map((name)=>source.subitem([
2409
+ 'bounded-contexts',
2410
+ name
2411
+ ]))
2412
+ ];
2413
+ for (const owner of owners)for (const unit of findContracts(owner.path)){
2414
+ const wireFile = new File(node_path.join(owner.path, contractWireFile(unit)));
2415
+ if (!wireFile.exists) continue;
2416
+ let wired;
2417
+ try {
2418
+ wired = wireBranches(wireFile.data, `wire${contractClassName(unit)}`);
2419
+ } catch {
2420
+ continue;
2366
2421
  }
2422
+ const primaryWires = new Set([
2423
+ ...wired
2424
+ ].filter(([branch])=>branch !== testBranch).map(([, wire])=>wire));
2425
+ for (const label of unit.labels)if (types.includes(label) && primaryWires.has(implementationWireName(label))) scaffoldIntegrationSpec(unit, label);
2367
2426
  }
2368
- const ClassName = new UnknownFormatNaming(unit.name).ClassName;
2369
- const namedImports = /import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\2/g;
2370
- const usedBy = [];
2371
- const relative = (file)=>toPosix(node_path.relative(projectRoot, file));
2372
- for (const [file, original] of codeFiles){
2373
- if (fileSet.has(file)) continue;
2374
- const content = cleaned.get(file) ?? original;
2375
- for (const [, , specifier] of content.matchAll(importSpecifier)){
2376
- const target = resolved(specifier, file);
2377
- if (target && isUnit(target)) usedBy.push([
2378
- relative(file),
2379
- relative(target)
2380
- ]);
2381
- }
2382
- for (const [, names, , specifier] of content.matchAll(namedImports)){
2383
- const target = resolved(specifier, file);
2384
- if (target && isParentBarrel(target) && new RegExp(`(?<![\\w$])${ClassName}(?![\\w$])`).test(names)) usedBy.push([
2385
- relative(file),
2386
- `${relative(target)} (${ClassName})`
2387
- ]);
2427
+ };
2428
+ const addTestcontainers = async ()=>{
2429
+ const config = ConfigFile.Instance.data;
2430
+ const root = new ProjectRoot().path;
2431
+ const manifestFile = new File(node_path.join(root, 'package.json'));
2432
+ const manifest = JSON.parse(manifestFile.data);
2433
+ const dependencies = {
2434
+ ...manifest.dependencies,
2435
+ ...manifest.devDependencies
2436
+ };
2437
+ const selected = await addPackageScripts(manifestFile, testcontainersScripts);
2438
+ const withPrisma = new File(node_path.resolve(root, config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
2439
+ const migrationCommand = withPrisma ? `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
2440
+ const folder = node_path.join(root, integrationFolder);
2441
+ testcontainers_stageFile(node_path.join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
2442
+ testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
2443
+ testcontainers_stageFile(node_path.join(folder, 'setup-env.ts'), testcontainersSetupEnv);
2444
+ const example = new File(node_path.join(folder, 'database/database.spec.ts'));
2445
+ if (!example.exists) example.data = testcontainers_exampleSpec;
2446
+ const unitConfig = new File(node_path.join(root, 'vitest.config.ts'));
2447
+ let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
2448
+ if (!excludedFromUnitTests) {
2449
+ const excluded = excludeFromUnitTests(unitConfig.data);
2450
+ if (excluded) {
2451
+ unitConfig.update(excluded);
2452
+ excludedFromUnitTests = true;
2388
2453
  }
2389
2454
  }
2390
- if (usedBy.length) return {
2391
- usedBy
2392
- };
2393
- for (const file of files)new File(file).delete(rootFolderPath);
2394
- for (const [file, content] of cleaned)new File(file).update(content);
2395
- return {
2396
- deleted: files,
2397
- updated: [
2398
- ...cleaned.keys()
2399
- ]
2400
- };
2455
+ await configureIntegrationTests(root);
2456
+ const missing = [
2457
+ 'vitest',
2458
+ 'testcontainers',
2459
+ 'dotenv'
2460
+ ].filter((name)=>!dependencies[name]);
2461
+ return [
2462
+ ...missing.length ? [
2463
+ `npm install --save-dev ${missing.join(' ')}`
2464
+ ] : [],
2465
+ `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.`,
2466
+ ...migrationCommand ? [] : [
2467
+ `Apply your migrations in ${integrationFolder}/global-setup.ts.`
2468
+ ],
2469
+ ...excludedFromUnitTests ? [] : [
2470
+ `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
2471
+ ],
2472
+ ...wire_branches_envBranches().custom ? [
2473
+ `${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.`
2474
+ ] : [],
2475
+ 'Docker must be running for integration specs.',
2476
+ ...describeScripts(selected, {
2477
+ 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
2478
+ })
2479
+ ];
2401
2480
  };
2402
- const contractKinds = [
2403
- 'aggregate',
2404
- 'command',
2405
- 'query',
2406
- 'port'
2407
- ];
2408
- const implementations_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
2409
- const withHandlers = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers');
2410
- const contractFile = (unit)=>'aggregate' === unit.kind ? `domain/aggregates/${unit.name}/${unit.name}-repository.ts` : kindLayouts[unit.kind].files(unit, [])[0];
2411
- const findContracts = (ownerPath)=>findBackendUnits(ownerPath).filter((unit)=>contractKinds.includes(unit.kind) && node_fs.existsSync(node_path.join(ownerPath, contractFile(unit))));
2412
- const implementationWireName = (label)=>`wire${new UnknownFormatNaming(label).ClassName}Implementation`;
2413
- const contractClassName = (unit)=>kindLayouts[unit.kind].core(new UnknownFormatNaming(unit.name).ClassName);
2414
- const implementationClassName = (unit, label)=>`${new UnknownFormatNaming(label).ClassName}${contractClassName(unit)}`;
2415
- const implementationFile = (unit, label)=>{
2416
- const { implementations } = kindLayouts[unit.kind];
2417
- return kindLayouts[unit.kind].files(unit, [
2418
- label
2419
- ]).find((file)=>file.startsWith(`${implementations}/`));
2481
+ const vitestScripts = {
2482
+ test: 'vitest run --reporter=dot --silent=passed-only',
2483
+ 'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
2420
2484
  };
2421
- const contractWireFile = (unit)=>kindLayouts[unit.kind].files(unit, []).find((file)=>file.startsWith('wiring/'));
2422
- const handlerImplementation = (ContractName, ClassName, contractImport)=>withHandlers() ? `
2423
- import { defineHandler } from '@domain-first/handlers'
2424
- import { ${ContractName} } from '${contractImport}'
2485
+ const vitestConfig = (rootFolder, inlineHandlersNext)=>{
2486
+ const folder = (subpath)=>JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), subpath));
2487
+ const server = inlineHandlersNext ? `,
2488
+ server: {
2489
+ deps: {
2490
+ // Imports \`next/headers\` without an extension, which only a bundler can resolve
2491
+ inline: ['@domain-first/handlers-next']
2492
+ }
2493
+ }` : '';
2494
+ return `import { configDefaults, defineConfig } from 'vitest/config';
2425
2495
 
2426
- export class ${ClassName} extends ${ContractName} {
2427
- constructor() {
2428
- super()
2496
+ export default defineConfig({
2497
+ resolve: {
2498
+ tsconfigPaths: true
2499
+ },
2500
+ test: {
2501
+ // Playwright runs end-to-end specs, test:integration runs integration ones
2502
+ exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
2503
+ coverage: {
2504
+ provider: 'v8',
2505
+ include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
2506
+ exclude: [
2507
+ '**/*.spec.ts',
2508
+ ${folder('shared-kernel/infrastructure/**')},
2509
+ ${folder('bounded-contexts/*/infrastructure/**')},
2510
+ ${folder('bounded-contexts/*/presentation/rest/**')},
2511
+ ${folder('shared-kernel/wiring/**')},
2512
+ ${folder('bounded-contexts/*/wiring/**')}
2513
+ ],
2514
+ reporter: [['text', { skipFull: true }], 'html']
2515
+ }${server}
2429
2516
  }
2430
-
2431
- handle = defineHandler({
2432
- inputSchema: ${ContractName}.inputSchema,
2433
- outputSchema: ${ContractName}.outputSchema,
2434
- handler: async (input) => {
2435
- return {}
2517
+ });
2518
+ `;
2519
+ };
2520
+ const addVitest = async ()=>{
2521
+ const config = ConfigFile.Instance.data;
2522
+ if (ConfigFile.backend.testingLibrary && 'vitest' !== ConfigFile.backend.testingLibrary && !await interaction_confirm({
2523
+ key: 'replaceTestingLibrary',
2524
+ requestRequired: true,
2525
+ message: `Replace testing library "${ConfigFile.backend.testingLibrary}" with vitest for generated tests?`,
2526
+ default: false
2527
+ })) return [];
2528
+ const root = new ProjectRoot().path;
2529
+ const manifestFile = new File(node_path.join(root, 'package.json'));
2530
+ const manifest = JSON.parse(manifestFile.data);
2531
+ const dependencies = {
2532
+ ...manifest.dependencies,
2533
+ ...manifest.devDependencies
2534
+ };
2535
+ const selected = await addPackageScripts(manifestFile, vitestScripts);
2536
+ const configFile = new File(node_path.join(root, 'vitest.config.ts'));
2537
+ const content = vitestConfig(config.project.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
2538
+ if (!configFile.exists || configFile.data !== content) configFile.data = content;
2539
+ if ('vitest' !== ConfigFile.backend.testingLibrary) ConfigFile.update({
2540
+ backend: {
2541
+ ...ConfigFile.backend,
2542
+ testingLibrary: 'vitest'
2436
2543
  }
2437
- })
2438
- }
2439
- `.trim() : `
2440
- import { ${ContractName} } from '${contractImport}'
2441
-
2442
- export class ${ClassName} extends ${ContractName} {
2443
- constructor() {
2444
- super()
2544
+ });
2545
+ addGitignoreEntry(root, '/coverage/');
2546
+ const missing = [
2547
+ 'vitest',
2548
+ '@vitest/coverage-v8'
2549
+ ].filter((name)=>!dependencies[name]);
2550
+ return [
2551
+ ...missing.length ? [
2552
+ `npm install --save-dev ${missing.join(' ')}`
2553
+ ] : [],
2554
+ ...describeScripts(selected, {
2555
+ test: 'run unit tests',
2556
+ 'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
2557
+ })
2558
+ ];
2559
+ };
2560
+ const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
2561
+ const mergeInstallCommands = (commands)=>{
2562
+ const runtime = new Set();
2563
+ const development = new Set();
2564
+ const rest = [];
2565
+ for (const command of commands){
2566
+ const match = installCommand.exec(command);
2567
+ if (!match) {
2568
+ rest.push(command);
2569
+ continue;
2570
+ }
2571
+ for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
2445
2572
  }
2446
- }
2447
- `.trim();
2448
- const createImplementation = (ownerFolder, unit, label)=>{
2449
- const naming = new UnknownFormatNaming(unit.name);
2450
- const ContractName = contractClassName(unit);
2451
- const className = implementationClassName(unit, label);
2452
- const [folder, fileName] = [
2453
- node_path.dirname(implementationFile(unit, label)),
2454
- node_path.basename(implementationFile(unit, label))
2573
+ const devOnly = [
2574
+ ...development
2575
+ ].filter((name)=>!runtime.has(name));
2576
+ return [
2577
+ ...runtime.size ? [
2578
+ `npm install ${[
2579
+ ...runtime
2580
+ ].join(' ')}`
2581
+ ] : [],
2582
+ ...devOnly.length ? [
2583
+ `npm install --save-dev ${devOnly.join(' ')}`
2584
+ ] : [],
2585
+ ...rest
2455
2586
  ];
2456
- const implementationFolder = ownerFolder.subitem(folder.split('/'));
2457
- const inMemoryDb = !implementations_withWiring() && usesInMemoryDb(label);
2458
- switch(unit.kind){
2459
- case 'aggregate':
2460
- {
2461
- const contractImport = `../../../domain/aggregates/${unit.name}`;
2462
- if (inMemoryDb) {
2463
- const section = addInMemoryDbSection(naming, ownerFolder.subitem([
2464
- 'domain',
2465
- 'aggregates',
2466
- unit.name
2467
- ]).path);
2468
- const file = implementationFolder.createFile(fileName, `
2469
- ${inMemoryDbTypeImport(implementationFolder.subitem([
2470
- fileName
2471
- ]).path)}
2472
- import { ${ContractName} } from '${contractImport}'
2473
-
2474
- export class ${className} implements ${ContractName} {
2475
- ${inMemoryDbSectionMembers(section, false)}
2476
- }
2477
- `.trim());
2478
- return {
2479
- file,
2480
- className
2481
- };
2482
- }
2483
- const file = implementationFolder.createFile(fileName, `
2484
- import { ${ContractName} } from '${contractImport}'
2485
-
2486
- export class ${className} implements ${ContractName} {
2487
- constructor() {}
2488
- }
2489
-
2490
- `.trim());
2491
- return {
2492
- file,
2493
- className
2494
- };
2495
- }
2496
- case 'command':
2497
- case 'query':
2498
- {
2499
- const folderName = 'command' === unit.kind ? 'commands' : 'queries';
2500
- const file = implementationFolder.createFile(fileName, handlerImplementation(ContractName, className, `../../../application/${folderName}/${naming.fileName}-${unit.kind}`));
2501
- if (inMemoryDb) injectInMemoryDb(file, className);
2502
- return {
2503
- file,
2504
- className
2505
- };
2506
- }
2507
- case 'port':
2508
- {
2509
- const file = implementationFolder.createFile(fileName, `
2510
- import { ${ContractName} } from '../../../application/ports/${naming.fileName}'
2511
-
2512
- export class ${className} extends ${ContractName} {
2513
-
2514
- }
2515
- `.trim());
2516
- return {
2517
- file,
2518
- className
2519
- };
2520
- }
2521
- default:
2522
- throw new Error(`${unit.kind} has no implementations`);
2587
+ };
2588
+ const printNextSteps = (nextSteps)=>{
2589
+ const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
2590
+ const commands = mergeInstallCommands(nextSteps.filter(isCommand));
2591
+ const notes = nextSteps.filter((line)=>!isCommand(line));
2592
+ const sections = [];
2593
+ if (commands.length) sections.push([
2594
+ 'Run this command to install the required dependencies:',
2595
+ styleText([
2596
+ 'bold',
2597
+ 'cyan'
2598
+ ], commands.join(' && '))
2599
+ ].join('\n'));
2600
+ if (notes.length) sections.push([
2601
+ 'Additional information:',
2602
+ ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
2603
+ 'bold',
2604
+ 'cyan'
2605
+ ], path)))
2606
+ ].join('\n'));
2607
+ if (sections.length) console.log(sections.join('\n\n'));
2608
+ };
2609
+ const savePendingChanges = async ()=>{
2610
+ assertAnswersConsumed();
2611
+ const overwrittenFiles = filesToOverwrite({
2612
+ changedOnly: isNonInteractive()
2613
+ });
2614
+ if (isNonInteractive() && overwrittenFiles.length && !answerFor('overwrite', false)) throw new RequestError('OVERWRITE_REQUIRED', 'Set overwrite to true to replace existing files.', {
2615
+ files: overwrittenFiles.map((file)=>node_path.relative(new ProjectRoot().path, file).split(node_path.sep).join('/'))
2616
+ });
2617
+ if (overwrittenFiles.length) {
2618
+ const root = new ProjectRoot().path;
2619
+ report('These files already exist and will be overwritten:');
2620
+ for (const filePath of overwrittenFiles)report(` ${node_path.relative(root, filePath)}`);
2621
+ const overwrite = await interaction_confirm({
2622
+ key: 'overwrite',
2623
+ message: 'Overwrite them?',
2624
+ default: false
2625
+ });
2626
+ if (!overwrite) {
2627
+ discardPendingChanges();
2628
+ report('Cancelled: nothing was written.');
2629
+ return false;
2630
+ }
2523
2631
  }
2632
+ writePendingChanges();
2633
+ return true;
2524
2634
  };
2525
- const inMemoryRepositoryWiring = (ownerFolder, unit, wireFile)=>(implementation, dependency)=>{
2526
- if ('aggregate' !== unit.kind || !isInMemoryDb(dependency)) return false;
2527
- keepInMemoryDbSection(new File(implementation.file), addInMemoryDbSection(new UnknownFormatNaming(unit.name), ownerFolder.subitem([
2528
- 'domain',
2529
- 'aggregates',
2530
- unit.name
2531
- ]).path));
2532
- wireInMemoryDb(wireFile, implementation.className);
2533
- return true;
2635
+ const withHandlersRest = ()=>ConfigFile.Instance.data.backend?.domainFirstPackages.includes('@domain-first/handlers-rest') ?? false;
2636
+ const created = (...segments)=>new File(node_path.join(new ProjectRoot().path, ...segments)).exists;
2637
+ const createdInRoot = (...segments)=>created(ConfigFile.Instance.data.project.rootFolder, ...segments);
2638
+ const integrationIds = [
2639
+ 'storybook',
2640
+ 'rest-endpoint-generator',
2641
+ 'in-memory-db',
2642
+ 'prisma',
2643
+ 'vitest',
2644
+ 'playwright',
2645
+ 'testcontainers',
2646
+ 'openapi',
2647
+ 'orval'
2648
+ ];
2649
+ const integrations = [
2650
+ {
2651
+ id: 'storybook',
2652
+ name: 'Storybook (React + Vite)',
2653
+ group: 'frontend',
2654
+ run: addStorybook,
2655
+ applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
2656
+ },
2657
+ {
2658
+ id: 'rest-endpoint-generator',
2659
+ name: 'REST endpoint generator',
2660
+ group: 'backend',
2661
+ run: addRestEndpointGenerator,
2662
+ available: ()=>withHandlersRest(),
2663
+ applied: restEndpointGeneratorApplied
2664
+ },
2665
+ {
2666
+ id: 'in-memory-db',
2667
+ name: 'In-memory DB',
2668
+ group: 'backend',
2669
+ run: addInMemoryDb,
2670
+ applied: inMemoryDbApplied
2671
+ },
2672
+ {
2673
+ id: 'prisma',
2674
+ name: 'Prisma 8 (PostgreSQL, RC)',
2675
+ group: 'backend',
2676
+ run: addPrisma,
2677
+ applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
2678
+ },
2679
+ {
2680
+ id: 'vitest',
2681
+ name: 'Vitest',
2682
+ group: 'backend',
2683
+ run: addVitest,
2684
+ applied: ()=>created('vitest.config.ts')
2685
+ },
2686
+ {
2687
+ id: 'playwright',
2688
+ name: 'Playwright',
2689
+ group: 'frontend',
2690
+ run: addPlaywright,
2691
+ applied: ()=>created('playwright.config.ts')
2692
+ },
2693
+ {
2694
+ id: 'testcontainers',
2695
+ name: 'Integration tests (Testcontainers, PostgreSQL)',
2696
+ group: 'backend',
2697
+ run: addTestcontainers,
2698
+ applied: ()=>created('specs/integration/vitest.config.ts')
2699
+ },
2700
+ {
2701
+ id: 'openapi',
2702
+ name: 'OpenAPI',
2703
+ group: 'backend',
2704
+ run: addOpenapi,
2705
+ available: ()=>withHandlersRest(),
2706
+ applied: ()=>created(openapiScriptPath)
2707
+ },
2708
+ {
2709
+ id: 'orval',
2710
+ name: 'Orval (API client)',
2711
+ group: 'frontend',
2712
+ run: addOrval,
2713
+ available: ()=>withHandlersRest(),
2714
+ applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
2715
+ }
2716
+ ];
2717
+ const addIntegration = async ({ save = true } = {})=>{
2718
+ const available = integrations.filter(({ group, available })=>('backend' !== group || Boolean(ConfigFile.Instance.data.backend)) && (available?.() ?? true)).map((value)=>({
2719
+ value,
2720
+ applied: value.applied()
2721
+ }));
2722
+ const section = (title, applied)=>{
2723
+ const items = [
2724
+ 'backend',
2725
+ 'frontend'
2726
+ ].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
2727
+ return items.length ? [
2728
+ new Separator(title),
2729
+ ...items.map(({ value })=>({
2730
+ name: `${value.name} · ${value.group}`,
2731
+ value
2732
+ }))
2733
+ ] : [];
2534
2734
  };
2735
+ const choices = [
2736
+ ...section('New integrations', false),
2737
+ ...section('Already applied (select to reapply)', true)
2738
+ ];
2739
+ const selected = await interaction_checkbox({
2740
+ key: 'integrations',
2741
+ id: (integration)=>integration.id,
2742
+ message: 'Integrations:',
2743
+ choices,
2744
+ pageSize: choices.length
2745
+ });
2746
+ const nextSteps = [];
2747
+ for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
2748
+ if (save && await savePendingChanges()) printNextSteps(nextSteps);
2749
+ return nextSteps;
2750
+ };
2751
+ const integrationDescriptions = ()=>integrations.map((integration)=>({
2752
+ id: integration.id,
2753
+ name: integration.name,
2754
+ group: integration.group,
2755
+ available: ('backend' !== integration.group || Boolean(ConfigFile.Instance.data.backend)) && (integration.available?.() ?? true)
2756
+ }));
2535
2757
  const reactKindLayouts = {
2536
2758
  page: {
2537
2759
  folder: 'pages',
@@ -3372,16 +3594,23 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
3372
3594
  if (!implementation) throw new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
3373
3595
  field: key
3374
3596
  });
3597
+ if ('test' === purpose && void 0 !== implementation.integrationTests) throw new RequestError('UNUSED_PARAMETERS', 'Test implementations get no integration specs.', {
3598
+ fields: [
3599
+ `${key}.integrationTests`
3600
+ ]
3601
+ });
3375
3602
  const valid = validateLabel(implementation.type);
3376
3603
  if (true !== valid) throw new RequestError('INVALID_IMPLEMENTATION', valid, {
3377
3604
  field: key
3378
3605
  });
3379
3606
  const label = implementation.type.trim();
3380
3607
  const saveForFutureUse = implementation.save ?? false;
3608
+ const entered = !choices.some((choice)=>choice.value === label);
3381
3609
  if (remember && saveForFutureUse && !system.some((choice)=>choice.value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
3382
3610
  return {
3383
3611
  label,
3384
- saveForFutureUse
3612
+ saveForFutureUse,
3613
+ entered
3385
3614
  };
3386
3615
  }
3387
3616
  const type = await interaction_select({
@@ -3397,7 +3626,8 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
3397
3626
  });
3398
3627
  if ('string' == typeof type) return {
3399
3628
  label: type,
3400
- saveForFutureUse: true
3629
+ saveForFutureUse: true,
3630
+ entered: false
3401
3631
  };
3402
3632
  const saveForFutureUse = type !== enterImplementationTypeOnce;
3403
3633
  const label = (await interaction_input({
@@ -3408,7 +3638,8 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
3408
3638
  if (saveForFutureUse && remember && !choices.some(({ value })=>value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
3409
3639
  return {
3410
3640
  label,
3411
- saveForFutureUse
3641
+ saveForFutureUse,
3642
+ entered: !choices.some(({ value })=>value === label)
3412
3643
  };
3413
3644
  };
3414
3645
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
@@ -3454,7 +3685,12 @@ describe('${aggregateNaming.withSpaces}', () => {
3454
3685
  if (withRepository) {
3455
3686
  aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.ts`, `export abstract class ${aggregateNaming.ClassName}Repository { }`);
3456
3687
  barrelFile.addLine(`export * from './${aggregateNaming.fileName}-repository'`);
3457
- const { label: infrastructureImplementationType } = await promptImplementationType('Repository infrastructure implementation type:', 'repositories');
3688
+ const primary = await promptImplementationType('Repository infrastructure implementation type:', 'repositories');
3689
+ const infrastructureImplementationType = primary.label;
3690
+ const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
3691
+ entered: primary.entered,
3692
+ save: primary.saveForFutureUse
3693
+ });
3458
3694
  let addTestImplementation = false;
3459
3695
  let testImplementationType = '';
3460
3696
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -3494,6 +3730,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
3494
3730
  export const wire${aggregateNaming.ClassName}Repository = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
3495
3731
  `.trim());
3496
3732
  await wireNewModuleDependencies(boundedContextFolder, wireFile, inMemoryRepositoryWiring(boundedContextFolder, repository, wireFile));
3733
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
3734
+ kind: 'aggregate',
3735
+ name: aggregateNaming.fileName,
3736
+ ownerPath: boundedContextFolder.path
3737
+ }, new UnknownFormatNaming(infrastructureImplementationType).fileName);
3497
3738
  }
3498
3739
  }
3499
3740
  };
@@ -3517,9 +3758,14 @@ export abstract class ${naming.ClassName} {
3517
3758
  }
3518
3759
  `.trim());
3519
3760
  const crossContext = hasNeighboringBoundedContext(boundedContextFolder.path);
3520
- const { label: implementationType } = await promptImplementationType('Adapter implementation type:', 'ports', {
3761
+ const primary = await promptImplementationType('Adapter implementation type:', 'ports', {
3521
3762
  crossContext
3522
3763
  });
3764
+ const implementationType = primary.label;
3765
+ const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
3766
+ entered: primary.entered,
3767
+ save: primary.saveForFutureUse
3768
+ });
3523
3769
  const addTestImplementation = offersTestImplementation() && await interaction_confirm({
3524
3770
  key: 'withTestImplementation',
3525
3771
  message: 'With test implementation'
@@ -3560,6 +3806,11 @@ export const wire${naming.ClassName} = envBranchedWire(${envBranchedWireArgument
3560
3806
 
3561
3807
  `.trim());
3562
3808
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
3809
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
3810
+ kind: 'port',
3811
+ name: naming.fileName,
3812
+ ownerPath: boundedContextFolder.path
3813
+ }, new UnknownFormatNaming(implementationType).fileName);
3563
3814
  }
3564
3815
  };
3565
3816
  const scaffoldNewApplicationService = async (boundedContextFolder)=>{
@@ -3638,7 +3889,12 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
3638
3889
  message: 'Name: '
3639
3890
  });
3640
3891
  const naming = new UnknownFormatNaming(commandName);
3641
- const { label: implementationType } = await promptImplementationType('Command infrastructure implementation type:', 'commands');
3892
+ const primary = await promptImplementationType('Command infrastructure implementation type:', 'commands');
3893
+ const implementationType = primary.label;
3894
+ const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
3895
+ entered: primary.entered,
3896
+ save: primary.saveForFutureUse
3897
+ });
3642
3898
  let addTestImplementation = false;
3643
3899
  let testImplementationType = '';
3644
3900
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -3691,6 +3947,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
3691
3947
  export const wire${naming.ClassName}Command = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
3692
3948
  `.trim());
3693
3949
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
3950
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
3951
+ kind: 'command',
3952
+ name: naming.fileName,
3953
+ ownerPath: boundedContextFolder.path
3954
+ }, new UnknownFormatNaming(implementationType).fileName);
3694
3955
  }
3695
3956
  };
3696
3957
  const scaffold_new_domain_object_noAggregate = 'No aggregate';
@@ -4064,7 +4325,7 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
4064
4325
  pageSize: 20
4065
4326
  });
4066
4327
  const kind = 'aggregate' === unit.kind ? 'repositories' : 'command' === unit.kind ? 'commands' : 'query' === unit.kind ? 'queries' : 'ports';
4067
- const { label, saveForFutureUse } = await promptImplementationType('Implementation type:', kind, {
4328
+ const { label, saveForFutureUse, entered } = await promptImplementationType('Implementation type:', kind, {
4068
4329
  existing: unit.labels,
4069
4330
  purpose: 'all',
4070
4331
  remember: false,
@@ -4078,12 +4339,23 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
4078
4339
  if (branches.test && environments.includes(branches.test)) rememberImplementation(kind, 'test', label);
4079
4340
  if (environments.some((environment)=>environment !== branches.test)) rememberImplementation(kind, 'primary', label);
4080
4341
  };
4081
- if (!ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) return void rememberFor(branches.primary);
4342
+ if (!ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
4343
+ rememberFor(branches.primary);
4344
+ await wantsIntegrationTests(label, {
4345
+ entered: false,
4346
+ save: false
4347
+ });
4348
+ return;
4349
+ }
4082
4350
  const wireFile = new File(ownerFolder.path).subitem(contractWireFile(unit).split('/'));
4083
4351
  const wireName = `wire${contractClassName(unit)}`;
4084
4352
  const wired = branchesOf(wireFile, wireName);
4085
4353
  if (!wired) {
4086
4354
  rememberFor(branches.primary);
4355
+ await wantsIntegrationTests(label, {
4356
+ entered: false,
4357
+ save: false
4358
+ });
4087
4359
  report(`${wireFile.path} has no ${wireName} = envBranchedWire({...}): wire ${className} there yourself.`);
4088
4360
  return;
4089
4361
  }
@@ -4112,6 +4384,11 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
4112
4384
  required: true
4113
4385
  });
4114
4386
  rememberFor(chosenEnvironments);
4387
+ const primaryRole = chosenEnvironments.some((environment)=>environment !== branches.test);
4388
+ const withIntegrationSpec = await wantsIntegrationTests(label, {
4389
+ entered: primaryRole && entered,
4390
+ save: saveForFutureUse
4391
+ }) && primaryRole;
4115
4392
  const before = readWiredModule(wireFile.path, ownerFolder.path);
4116
4393
  wireFile.update(addBranchedImplementation(wireFile.data, wireName, {
4117
4394
  importLine: `import { ${className} } from '${relativeImport(wireFile.path, file.path)}'`,
@@ -4120,6 +4397,7 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
4120
4397
  environments: chosenEnvironments
4121
4398
  }));
4122
4399
  const after = readWiredModule(wireFile.path, ownerFolder.path);
4400
+ if (withIntegrationSpec) scaffoldIntegrationSpec(unit, label);
4123
4401
  const unused = (before?.implementations ?? []).filter((x)=>!after?.implementations.some((y)=>y.className === x.className));
4124
4402
  for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
4125
4403
  await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
@@ -4172,6 +4450,7 @@ const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
4172
4450
  message: 'Name: '
4173
4451
  });
4174
4452
  const naming = new UnknownFormatNaming(name);
4453
+ const withIntegrationSpec = await wantsServiceIntegrationSpec();
4175
4454
  const withWiring = ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
4176
4455
  const wiringFolder = boundedContextFolder.subitem([
4177
4456
  'wiring',
@@ -4197,6 +4476,11 @@ export const wire${naming.ClassName}InfrastructureService = wireClass(
4197
4476
  )
4198
4477
  `.trim());
4199
4478
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
4479
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
4480
+ kind: 'infrastructure-service',
4481
+ name: naming.fileName,
4482
+ ownerPath: boundedContextFolder.path
4483
+ });
4200
4484
  }
4201
4485
  };
4202
4486
  const scaffoldNewQuery = async (boundedContextFolder)=>{
@@ -4209,7 +4493,12 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
4209
4493
  message: 'Name: '
4210
4494
  });
4211
4495
  const naming = new UnknownFormatNaming(queryName);
4212
- const { label: implementationType } = await promptImplementationType('Query infrastructure implementation type:', 'queries');
4496
+ const primary = await promptImplementationType('Query infrastructure implementation type:', 'queries');
4497
+ const implementationType = primary.label;
4498
+ const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
4499
+ entered: primary.entered,
4500
+ save: primary.saveForFutureUse
4501
+ });
4213
4502
  let addTestImplementation = false;
4214
4503
  let testImplementationType = '';
4215
4504
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -4262,6 +4551,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
4262
4551
  export const wire${naming.ClassName}Query = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
4263
4552
  `.trim());
4264
4553
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
4554
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
4555
+ kind: 'query',
4556
+ name: naming.fileName,
4557
+ ownerPath: boundedContextFolder.path
4558
+ }, new UnknownFormatNaming(implementationType).fileName);
4265
4559
  }
4266
4560
  };
4267
4561
  const scaffoldNewUseCase = async (boundedContextFolder)=>{
@@ -4522,4 +4816,4 @@ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps
4522
4816
  break;
4523
4817
  }
4524
4818
  };
4525
- export { RequestError, addIntegration, assertAnswersConsumed, configurationSections, deleteBackendUnitUseCase, deleteReactModuleUseCase, findBackendUnits, findContracts, findReactModules, findRestEndpointGenerator, helperImplementationTypes, initializeUseCase, integrationDescriptions, integrationIds, moduleId, moveBackendUnitUseCase, moveReactModuleUseCase, printNextSteps, reactKindTitles, rootControllerChoice, runWithAnswers, savePendingChanges, savedImplementations, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewImplementation, scaffoldNewInfrastructureHelper, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, systemImplementationChoices, unitId, wireDependency };
4819
+ export { RequestError, addIntegration, assertAnswersConsumed, configurationSections, deleteBackendUnitUseCase, deleteReactModuleUseCase, findBackendUnits, findContracts, findReactModules, findRestEndpointGenerator, helperImplementationTypes, initializeUseCase, integrationDescriptions, integrationIds, integrationSpecFile, integrationSpecsAvailable, moduleId, moveBackendUnitUseCase, moveReactModuleUseCase, printNextSteps, reactKindTitles, rootControllerChoice, runWithAnswers, savePendingChanges, savedImplementations, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewImplementation, scaffoldNewInfrastructureHelper, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, systemImplementationChoices, unitId, wireDependency };