@domain-first/project-structure 8.7.0 → 8.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +2 -0
  2. package/dist/287.js +1275 -1127
  3. package/dist/561.js +19 -3
  4. package/dist/780.js +9 -2
  5. package/dist/agent-cli.d.ts +35 -4
  6. package/dist/agent-requests.d.ts +22 -0
  7. package/dist/backend-module-move.d.ts +16 -0
  8. package/dist/config-file.d.ts +38 -18
  9. package/dist/graph.cjs +9 -2
  10. package/dist/implementation-options-schema.d.ts +19 -9
  11. package/dist/in-memory-db.d.ts +5 -6
  12. package/dist/index.cjs +1635 -1464
  13. package/dist/init.cjs +53 -59
  14. package/dist/integration-tests.d.ts +39 -0
  15. package/dist/integration-tests.spec.d.ts +1 -0
  16. package/dist/integration.cjs +1635 -1464
  17. package/dist/lint.cjs +9 -2
  18. package/dist/react.cjs +1635 -1464
  19. package/dist/upgrade-steps.d.ts +19 -4
  20. package/dist/upgrade.cjs +9 -2
  21. package/dist/use-cases/prompt-implementation-type.d.ts +2 -0
  22. package/package.json +1 -1
  23. package/skills/df-ps-implement/SKILL.md +2 -1
  24. package/skills/df-ps-scaffold/SKILL.md +2 -1
  25. package/skills/df-ps-scaffold/references/agent-mode.md +1 -1
  26. package/skills/df-ps-scaffold/references/agent-operations.md +2 -2
  27. package/skills/df-ps-scaffold/references/generators.md +31 -7
  28. package/skills/df-ps-scaffold/references/units/aggregate.md +3 -2
  29. package/skills/df-ps-scaffold/references/units/command-query.md +3 -2
  30. package/skills/df-ps-scaffold/references/units/helper.md +1 -1
  31. package/skills/df-ps-scaffold/references/units/implementation.md +1 -1
  32. package/skills/df-ps-scaffold/references/units/port.md +2 -1
  33. package/skills/df-ps-scaffold/references/units/services.md +4 -3
package/dist/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";
@@ -127,23 +127,6 @@ export const wireInMemoryDbInfrastructureService = wireClass(
127
127
  []
128
128
  );
129
129
  `;
130
- const inMemoryDbSpec = (testingLibrary, withWiring)=>`
131
- import { describe, test, expect, beforeEach } from '${testingLibrary}'
132
- ${withWiring ? `import { type InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'
133
- import { wireInMemoryDbInfrastructureService } from '../../wiring/infrastructure-services/wire-in-memory-db-infrastructure-service'` : "import { InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'"}
134
-
135
- let inMemoryDbInfrastructureService: InMemoryDbInfrastructureService
136
-
137
- beforeEach(() => {
138
- inMemoryDbInfrastructureService = ${withWiring ? 'wireInMemoryDbInfrastructureService()' : 'new InMemoryDbInfrastructureService()'}
139
- })
140
-
141
- describe('in memory db', () => {
142
- test('can be ${withWiring ? 'wired' : 'created'}', () => {
143
- expect(inMemoryDbInfrastructureService).toBeDefined()
144
- })
145
- })
146
- `.trim();
147
130
  const in_memory_db_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
148
131
  const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
149
132
  ConfigFile.Instance.data.project.rootFolder,
@@ -160,13 +143,11 @@ const in_memory_db_wireFile = ()=>new File(in_memory_db_sharedFolder().path).sub
160
143
  'wire-in-memory-db-infrastructure-service.ts'
161
144
  ]);
162
145
  const scaffoldInMemoryDb = (shared)=>{
163
- const { testingLibrary } = ConfigFile.backend;
164
146
  const servicesFolder = shared.subitem([
165
147
  'infrastructure',
166
148
  'services'
167
149
  ]);
168
150
  servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
169
- if (testingLibrary) servicesFolder.createFile('in-memory-db-infrastructure-service.spec.ts', inMemoryDbSpec(testingLibrary, in_memory_db_withWiring()));
170
151
  if (in_memory_db_withWiring()) shared.subitem([
171
152
  'wiring',
172
153
  'infrastructure-services'
@@ -228,9 +209,6 @@ const wireInMemoryDb = (consumerWireFile, implementationName)=>{
228
209
  in_memory_db_wireName
229
210
  ]));
230
211
  };
231
- const passInMemoryDb = (specFile, implementationName)=>{
232
- specFile.update(addImport(specFile.data, `import { ${in_memory_db_className} } from '${relativeImport(specFile.path, serviceFile().path)}'`).replace(`new ${implementationName}()`, `new ${implementationName}(new ${in_memory_db_className}())`));
233
- };
234
212
  const addInMemoryDb = ()=>{
235
213
  const config = ConfigFile.Instance.data;
236
214
  if (!ConfigFile.backend.withInMemoryDb) ConfigFile.update({
@@ -1522,1038 +1500,1260 @@ const addStorybook = async ()=>{
1522
1500
  })
1523
1501
  ];
1524
1502
  };
1525
- const defaultEnvBranches = {
1526
- names: [
1527
- 'test',
1528
- 'development',
1529
- 'production'
1530
- ],
1531
- 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
+ };
1532
1530
  };
1533
- const wire_branches_envBranches = ()=>{
1534
- const configured = ConfigFile.exists ? ConfigFile.Instance.data.backend?.envBranches : void 0;
1535
- const { names, test } = configured ?? defaultEnvBranches;
1531
+ const domainModelLayout = (kind)=>{
1532
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
1536
1533
  return {
1537
- names,
1538
- test,
1539
- primary: names.filter((name)=>name !== test),
1540
- 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
1541
1545
  };
1542
1546
  };
1543
- const offersTestImplementation = ()=>{
1544
- const backend = ConfigFile.exists ? ConfigFile.Instance.data.backend : void 0;
1545
- 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
+ }
1546
1599
  };
1547
- const envBranchedWireArgument = (testWire, primaryWire)=>{
1548
- const { test, primary } = wire_branches_envBranches();
1549
- return `{\n${[
1550
- ...test ? [
1551
- ` ${test}: ${testWire}`
1552
- ] : [],
1553
- ...primary.map((name)=>` ${name}: ${primaryWire}`)
1554
- ].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
+ }
1555
1609
  };
1556
- const envBranchedWireSource = ()=>{
1557
- const { names, custom } = wire_branches_envBranches();
1558
- if (!custom) return `import { branchedWire } from '@domain-first/wire'
1559
-
1560
- export const envBranchedWire = branchedWire(() => {
1561
- return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1562
- });`;
1563
- return `import { branchedWire } from '@domain-first/wire'
1564
-
1565
- export type EnvBranch = ${names.map((name)=>`'${name}'`).join(' | ')}
1566
-
1567
- /**
1568
- * The branch this process runs in. Write how it is selected:
1569
- * until then, this function doesn't compile.
1570
- */
1571
- const currentBranch = (): EnvBranch => {
1572
- }
1573
-
1574
- 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;
1575
1631
  };
1576
- const integrationFolder = 'specs/integration';
1577
- const testcontainersScripts = {
1578
- '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))));
1579
1645
  };
1580
- const testcontainersVitestConfig = (inlineHandlersNext)=>{
1581
- const server = inlineHandlersNext ? `,
1582
- server: {
1583
- deps: {
1584
- // Imports \`next/headers\` without an extension, which only a bundler can resolve
1585
- inline: ['@domain-first/handlers-next']
1586
- }
1587
- }` : '';
1588
- return `import { fileURLToPath } from 'node:url';
1589
- import { defineConfig } from 'vitest/config';
1590
-
1591
- // Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
1592
- export default defineConfig({
1593
- // Paths below are relative to the project root, not this folder
1594
- root: fileURLToPath(new URL('../..', import.meta.url)),
1595
- resolve: {
1596
- tsconfigPaths: true
1597
- },
1598
- test: {
1599
- include: ['${integrationFolder}/**/*.spec.ts'],
1600
- // Development implementations work with the real database
1601
- env: { NODE_ENV: 'development' },
1602
- globalSetup: ['${integrationFolder}/global-setup.ts'],
1603
- setupFiles: ['${integrationFolder}/setup-env.ts'],
1604
- // Pulling the image on the first run takes a while
1605
- hookTimeout: 120_000${server}
1606
- }
1607
- });
1608
- `;
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
+ ];
1609
1673
  };
1610
- const testcontainersGlobalSetup = (migrationCommand)=>{
1611
- const migrations = migrationCommand ? `
1612
- // dotenv in the Prisma config does not override an already set variable
1613
- execSync(${JSON.stringify(migrationCommand)}, {
1614
- cwd: project.config.root,
1615
- env: { ...process.env, DATABASE_URL: databaseUrl },
1616
- // On failure the error carries the command's output
1617
- 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]));
1618
1684
  });
1619
- ` : `
1620
- // Apply your migrations to databaseUrl here.
1621
- `;
1622
- return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
1623
- import type { TestProject } from 'vitest/node';
1624
-
1625
- declare module 'vitest' {
1626
- export interface ProvidedContext {
1627
- 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);
1628
1693
  }
1629
- }
1630
-
1631
- const POSTGRES_IMAGE = 'postgres:15';
1632
- const POSTGRES_PORT = 5432;
1633
- const POSTGRES_USER = 'test';
1634
- const POSTGRES_PASSWORD = 'test';
1635
- const POSTGRES_DB = 'test';
1636
-
1637
- export default async function setup(project: TestProject) {
1638
- const container = await new GenericContainer(POSTGRES_IMAGE)
1639
- .withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
1640
- .withExposedPorts(POSTGRES_PORT)
1641
- // During init PostgreSQL listens on a unix socket only and restarts,
1642
- // so checking over TCP passes once the final server is up
1643
- .withHealthCheck({
1644
- test: [
1645
- 'CMD-SHELL',
1646
- \`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
1647
- ],
1648
- interval: 250,
1649
- timeout: 1000,
1650
- retries: 1000
1651
- })
1652
- .withWaitStrategy(Wait.forHealthCheck())
1653
- .withStartupTimeout(120_000)
1654
- .start();
1655
-
1656
- const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
1657
- ${migrations}
1658
- project.provide('databaseUrl', databaseUrl);
1659
-
1660
- return async () => {
1661
- await container.stop();
1662
- };
1663
- }
1664
- `;
1665
- };
1666
- const testcontainersSetupEnv = `import 'dotenv/config';
1667
- import { inject } from 'vitest';
1668
-
1669
- // Runs before each spec's imports: development implementations get the .env
1670
- // config, and DATABASE_URL points to the container instead of the one from .env.
1671
- if (process.env.NODE_ENV !== 'development') {
1672
- throw new Error(
1673
- \`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
1674
- );
1675
- }
1676
-
1677
- process.env.DATABASE_URL = inject('databaseUrl');
1678
- `;
1679
- const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
1680
-
1681
- test('connects to the database in the container', () => {
1682
- expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
1683
- });
1684
- `;
1685
- const excludeFromUnitTests = (content)=>{
1686
- const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
1687
- if (!exclude.test(content)) return;
1688
- const entry = `'${integrationFolder}/**'`;
1689
- return content.replace(exclude, (_, items, comma, whitespace)=>{
1690
- const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
1691
- const separator = void 0 === indent ? ', ' : `,\n${indent}`;
1692
- return `${items}${separator}${entry}${comma}${whitespace}]`;
1693
- }).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;
1694
1701
  };
1695
- const testcontainers_stageFile = (filePath, content)=>{
1696
- const file = new File(filePath);
1697
- 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;
1698
1708
  };
1699
- const addTestcontainers = async ()=>{
1700
- const config = ConfigFile.Instance.data;
1701
- const root = new ProjectRoot().path;
1702
- const manifestFile = new File(node_path.join(root, 'package.json'));
1703
- const manifest = JSON.parse(manifestFile.data);
1704
- const dependencies = {
1705
- ...manifest.dependencies,
1706
- ...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)
1707
1718
  };
1708
- const selected = await addPackageScripts(manifestFile, testcontainersScripts);
1709
- const withPrisma = new File(node_path.resolve(root, config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
1710
- const migrationCommand = withPrisma ? `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
1711
- const folder = node_path.join(root, integrationFolder);
1712
- testcontainers_stageFile(node_path.join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
1713
- testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
1714
- testcontainers_stageFile(node_path.join(folder, 'setup-env.ts'), testcontainersSetupEnv);
1715
- const example = new File(node_path.join(folder, 'database/database.spec.ts'));
1716
- if (!example.exists) example.data = testcontainers_exampleSpec;
1717
- const unitConfig = new File(node_path.join(root, 'vitest.config.ts'));
1718
- let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
1719
- if (!excludedFromUnitTests) {
1720
- const excluded = excludeFromUnitTests(unitConfig.data);
1721
- if (excluded) {
1722
- unitConfig.update(excluded);
1723
- excludedFromUnitTests = true;
1724
- }
1725
- }
1726
- const missing = [
1727
- 'vitest',
1728
- 'testcontainers',
1729
- 'dotenv'
1730
- ].filter((name)=>!dependencies[name]);
1731
- return [
1732
- ...missing.length ? [
1733
- `npm install --save-dev ${missing.join(' ')}`
1734
- ] : [],
1735
- `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.`,
1736
- ...migrationCommand ? [] : [
1737
- `Apply your migrations in ${integrationFolder}/global-setup.ts.`
1738
- ],
1739
- ...excludedFromUnitTests ? [] : [
1740
- `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
1741
- ],
1742
- ...wire_branches_envBranches().custom ? [
1743
- `${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.`
1744
- ] : [],
1745
- 'Docker must be running for integration specs.',
1746
- ...describeScripts(selected, {
1747
- 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
1748
- })
1749
- ];
1750
1719
  };
1751
- const vitestScripts = {
1752
- test: 'vitest run --reporter=dot --silent=passed-only',
1753
- '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');
1754
1728
  };
1755
- const vitestConfig = (rootFolder, inlineHandlersNext)=>{
1756
- const folder = (subpath)=>JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), subpath));
1757
- const server = inlineHandlersNext ? `,
1758
- server: {
1759
- deps: {
1760
- // Imports \`next/headers\` without an extension, which only a bundler can resolve
1761
- 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
+ ]);
1762
1776
  }
1763
- }` : '';
1764
- return `import { configDefaults, defineConfig } from 'vitest/config';
1765
-
1766
- export default defineConfig({
1767
- resolve: {
1768
- tsconfigPaths: true
1769
- },
1770
- test: {
1771
- // Playwright runs end-to-end specs, test:integration runs integration ones
1772
- exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
1773
- coverage: {
1774
- provider: 'v8',
1775
- include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
1776
- exclude: [
1777
- '**/*.spec.ts',
1778
- ${folder('shared-kernel/infrastructure/**')},
1779
- ${folder('bounded-contexts/*/infrastructure/**')},
1780
- ${folder('bounded-contexts/*/presentation/rest/**')},
1781
- ${folder('shared-kernel/wiring/**')},
1782
- ${folder('bounded-contexts/*/wiring/**')}
1783
- ],
1784
- reporter: [['text', { skipFull: true }], 'html']
1785
- }${server}
1777
+ }
1786
1778
  }
1787
- });
1788
- `;
1789
- };
1790
- const addVitest = async ()=>{
1791
- const config = ConfigFile.Instance.data;
1792
- if (ConfigFile.backend.testingLibrary && 'vitest' !== ConfigFile.backend.testingLibrary && !await interaction_confirm({
1793
- key: 'replaceTestingLibrary',
1794
- requestRequired: true,
1795
- message: `Replace testing library "${ConfigFile.backend.testingLibrary}" with vitest for generated tests?`,
1796
- default: false
1797
- })) return [];
1798
- const root = new ProjectRoot().path;
1799
- const manifestFile = new File(node_path.join(root, 'package.json'));
1800
- const manifest = JSON.parse(manifestFile.data);
1801
- const dependencies = {
1802
- ...manifest.dependencies,
1803
- ...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
1804
1785
  };
1805
- const selected = await addPackageScripts(manifestFile, vitestScripts);
1806
- const configFile = new File(node_path.join(root, 'vitest.config.ts'));
1807
- const content = vitestConfig(config.project.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
1808
- if (!configFile.exists || configFile.data !== content) configFile.data = content;
1809
- if ('vitest' !== ConfigFile.backend.testingLibrary) ConfigFile.update({
1810
- backend: {
1811
- ...ConfigFile.backend,
1812
- testingLibrary: 'vitest'
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
+ ] : []
1796
+ ];
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
1813
1810
  }
1814
- });
1815
- addGitignoreEntry(root, '/coverage/');
1816
- const missing = [
1817
- 'vitest',
1818
- '@vitest/coverage-v8'
1819
- ].filter((name)=>!dependencies[name]);
1820
- return [
1821
- ...missing.length ? [
1822
- `npm install --save-dev ${missing.join(' ')}`
1823
- ] : [],
1824
- ...describeScripts(selected, {
1825
- test: 'run unit tests',
1826
- 'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
1827
- })
1828
1811
  ];
1829
- };
1830
- const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
1831
- const mergeInstallCommands = (commands)=>{
1832
- const runtime = new Set();
1833
- const development = new Set();
1834
- const rest = [];
1835
- for (const command of commands){
1836
- const match = installCommand.exec(command);
1837
- if (!match) {
1838
- rest.push(command);
1839
- continue;
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
1819
+ });
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
1824
+ });
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);
1840
1861
  }
1841
- for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
1842
1862
  }
1843
- const devOnly = [
1844
- ...development
1845
- ].filter((name)=>!runtime.has(name));
1846
- return [
1847
- ...runtime.size ? [
1848
- `npm install ${[
1849
- ...runtime
1850
- ].join(' ')}`
1851
- ] : [],
1852
- ...devOnly.length ? [
1853
- `npm install --save-dev ${devOnly.join(' ')}`
1854
- ] : [],
1855
- ...rest
1856
- ];
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;
1857
1870
  };
1858
- const printNextSteps = (nextSteps)=>{
1859
- const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
1860
- const commands = mergeInstallCommands(nextSteps.filter(isCommand));
1861
- const notes = nextSteps.filter((line)=>!isCommand(line));
1862
- const sections = [];
1863
- if (commands.length) sections.push([
1864
- 'Run this command to install the required dependencies:',
1865
- styleText([
1866
- 'bold',
1867
- 'cyan'
1868
- ], commands.join(' && '))
1869
- ].join('\n'));
1870
- if (notes.length) sections.push([
1871
- 'Additional information:',
1872
- ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
1873
- 'bold',
1874
- 'cyan'
1875
- ], path)))
1876
- ].join('\n'));
1877
- if (sections.length) console.log(sections.join('\n\n'));
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}`;
1878
1874
  };
1879
- const savePendingChanges = async ()=>{
1880
- assertAnswersConsumed();
1881
- const overwrittenFiles = filesToOverwrite({
1882
- changedOnly: isNonInteractive()
1883
- });
1884
- if (isNonInteractive() && overwrittenFiles.length && !answerFor('overwrite', false)) throw new RequestError('OVERWRITE_REQUIRED', 'Set overwrite to true to replace existing files.', {
1885
- files: overwrittenFiles.map((file)=>node_path.relative(new ProjectRoot().path, file).split(node_path.sep).join('/'))
1886
- });
1887
- if (overwrittenFiles.length) {
1888
- const root = new ProjectRoot().path;
1889
- report('These files already exist and will be overwritten:');
1890
- for (const filePath of overwrittenFiles)report(` ${node_path.relative(root, filePath)}`);
1891
- const overwrite = await interaction_confirm({
1892
- key: 'overwrite',
1893
- message: 'Overwrite them?',
1894
- default: false
1895
- });
1896
- if (!overwrite) {
1897
- discardPendingChanges();
1898
- report('Cancelled: nothing was written.');
1899
- return false;
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);
1901
+ }
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);
1900
1908
  }
1901
1909
  }
1902
- writePendingChanges();
1903
- return true;
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
1934
+ };
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);
1937
+ return {
1938
+ deleted: files,
1939
+ updated: [
1940
+ ...cleaned.keys()
1941
+ ]
1942
+ };
1904
1943
  };
1905
- const withHandlersRest = ()=>ConfigFile.Instance.data.backend?.domainFirstPackages.includes('@domain-first/handlers-rest') ?? false;
1906
- const created = (...segments)=>new File(node_path.join(new ProjectRoot().path, ...segments)).exists;
1907
- const createdInRoot = (...segments)=>created(ConfigFile.Instance.data.project.rootFolder, ...segments);
1908
- const integrationIds = [
1909
- 'storybook',
1910
- 'rest-endpoint-generator',
1911
- 'in-memory-db',
1912
- 'prisma',
1913
- 'vitest',
1914
- 'playwright',
1915
- 'testcontainers',
1916
- 'openapi',
1917
- 'orval'
1944
+ const contractKinds = [
1945
+ 'aggregate',
1946
+ 'command',
1947
+ 'query',
1948
+ 'port'
1918
1949
  ];
1919
- const integrations = [
1920
- {
1921
- id: 'storybook',
1922
- name: 'Storybook (React + Vite)',
1923
- group: 'frontend',
1924
- run: addStorybook,
1925
- applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
1926
- },
1927
- {
1928
- id: 'rest-endpoint-generator',
1929
- name: 'REST endpoint generator',
1930
- group: 'backend',
1931
- run: addRestEndpointGenerator,
1932
- available: ()=>withHandlersRest(),
1933
- applied: restEndpointGeneratorApplied
1934
- },
1935
- {
1936
- id: 'in-memory-db',
1937
- name: 'In-memory DB',
1938
- group: 'backend',
1939
- run: addInMemoryDb,
1940
- applied: inMemoryDbApplied
1941
- },
1942
- {
1943
- id: 'prisma',
1944
- name: 'Prisma 8 (PostgreSQL, RC)',
1945
- group: 'backend',
1946
- run: addPrisma,
1947
- applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
1948
- },
1949
- {
1950
- id: 'vitest',
1951
- name: 'Vitest',
1952
- group: 'backend',
1953
- run: addVitest,
1954
- applied: ()=>created('vitest.config.ts')
1955
- },
1956
- {
1957
- id: 'playwright',
1958
- name: 'Playwright',
1959
- group: 'frontend',
1960
- run: addPlaywright,
1961
- applied: ()=>created('playwright.config.ts')
1962
- },
1963
- {
1964
- id: 'testcontainers',
1965
- name: 'Integration tests (Testcontainers, PostgreSQL)',
1966
- group: 'backend',
1967
- run: addTestcontainers,
1968
- applied: ()=>created('specs/integration/vitest.config.ts')
1969
- },
1970
- {
1971
- id: 'openapi',
1972
- name: 'OpenAPI',
1973
- group: 'backend',
1974
- run: addOpenapi,
1975
- available: ()=>withHandlersRest(),
1976
- applied: ()=>created(openapiScriptPath)
1977
- },
1978
- {
1979
- id: 'orval',
1980
- name: 'Orval (API client)',
1981
- group: 'frontend',
1982
- run: addOrval,
1983
- available: ()=>withHandlersRest(),
1984
- applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
1985
- }
1986
- ];
1987
- const addIntegration = async ({ save = true } = {})=>{
1988
- const available = integrations.filter(({ group, available })=>('backend' !== group || Boolean(ConfigFile.Instance.data.backend)) && (available?.() ?? true)).map((value)=>({
1989
- value,
1990
- applied: value.applied()
1991
- }));
1992
- const section = (title, applied)=>{
1993
- const items = [
1994
- 'backend',
1995
- 'frontend'
1996
- ].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
1997
- return items.length ? [
1998
- new Separator(title),
1999
- ...items.map(({ value })=>({
2000
- name: `${value.name} · ${value.group}`,
2001
- value
2002
- }))
2003
- ] : [];
2004
- };
2005
- const choices = [
2006
- ...section('New integrations', false),
2007
- ...section('Already applied (select to reapply)', true)
2008
- ];
2009
- const selected = await interaction_checkbox({
2010
- key: 'integrations',
2011
- id: (integration)=>integration.id,
2012
- message: 'Integrations:',
2013
- choices,
2014
- pageSize: choices.length
2015
- });
2016
- const nextSteps = [];
2017
- for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
2018
- if (save && await savePendingChanges()) printNextSteps(nextSteps);
2019
- return nextSteps;
2020
- };
2021
- const integrationDescriptions = ()=>integrations.map((integration)=>({
2022
- id: integration.id,
2023
- name: integration.name,
2024
- group: integration.group,
2025
- available: ('backend' !== integration.group || Boolean(ConfigFile.Instance.data.backend)) && (integration.available?.() ?? true)
2026
- }));
2027
- const serviceLayout = (layer)=>({
2028
- title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
2029
- core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
2030
- files: ({ name })=>[
2031
- `${layer}/services/${name}-${layer}-service.ts`,
2032
- `${layer}/services/${name}-${layer}-service.spec.ts`,
2033
- `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
2034
- ],
2035
- wired: true,
2036
- sharedKernel: true
2037
- });
2038
- const handlerLayout = (kind)=>{
2039
- const folder = 'command' === kind ? 'commands' : 'queries';
2040
- const Suffix = 'command' === kind ? 'Command' : 'Query';
2041
- return {
2042
- title: 'command' === kind ? 'Commands' : 'Queries',
2043
- core: (ClassName)=>`${ClassName}${Suffix}`,
2044
- files: ({ name }, labels)=>[
2045
- `application/${folder}/${name}-${kind}.ts`,
2046
- `application/${folder}/${name}-${kind}.spec.ts`,
2047
- ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
2048
- `wiring/${folder}/wire-${name}-${kind}.ts`
2049
- ],
2050
- implementations: `infrastructure/${folder}`,
2051
- wired: true,
2052
- sharedKernel: false
2053
- };
2054
- };
2055
- const domainModelLayout = (kind)=>{
2056
- const folder = 'entity' === kind ? 'entities' : 'value-objects';
2057
- return {
2058
- title: 'entity' === kind ? 'Entities' : 'Value objects',
2059
- core: (ClassName)=>ClassName,
2060
- files: ({ name, aggregate })=>{
2061
- const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
2062
- return [
2063
- `${base}/${name}.${kind}.ts`,
2064
- `${base}/${name}.${kind}.spec.ts`
2065
- ];
2066
- },
2067
- wired: false,
2068
- sharedKernel: true
2069
- };
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}/`));
2070
1962
  };
2071
- const aggregateOwnFiles = (name)=>[
2072
- `${name}.aggregate-root.ts`,
2073
- `${name}.aggregate-root.spec.ts`,
2074
- `${name}-repository.ts`,
2075
- `${name}-repository.spec.ts`,
2076
- 'index.ts'
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()
1971
+ }
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))
2077
1997
  ];
2078
- const kindLayouts = {
2079
- aggregate: {
2080
- title: 'Aggregates',
2081
- core: (ClassName)=>`${ClassName}Repository`,
2082
- files: ({ name }, labels)=>[
2083
- ...aggregateOwnFiles(name).map((file)=>`domain/aggregates/${name}/${file}`),
2084
- ...labels.map((label)=>`infrastructure/repositories/${label}/${label}-${name}-repository.ts`),
2085
- `wiring/repositories/wire-${name}-repository.ts`
2086
- ],
2087
- implementations: 'infrastructure/repositories',
2088
- wired: true,
2089
- sharedKernel: false
2090
- },
2091
- entity: domainModelLayout('entity'),
2092
- 'value-object': domainModelLayout('value-object'),
2093
- 'domain-service': serviceLayout('domain'),
2094
- 'application-service': serviceLayout('application'),
2095
- 'infrastructure-service': serviceLayout('infrastructure'),
2096
- 'presentation-service': serviceLayout('presentation'),
2097
- 'use-case': {
2098
- title: 'Use cases',
2099
- core: (ClassName)=>`${ClassName}UseCase`,
2100
- files: ({ name })=>[
2101
- `application/use-cases/${name}-use-case.ts`,
2102
- `application/use-cases/${name}-use-case.spec.ts`,
2103
- `wiring/use-cases/wire-${name}-use-case.ts`
2104
- ],
2105
- wired: true,
2106
- sharedKernel: false
2107
- },
2108
- command: handlerLayout('command'),
2109
- query: handlerLayout('query'),
2110
- port: {
2111
- title: 'Ports',
2112
- core: (ClassName)=>ClassName,
2113
- files: ({ name }, labels)=>[
2114
- `application/ports/${name}.ts`,
2115
- `application/ports/${name}.spec.ts`,
2116
- ...labels.map((label)=>`infrastructure/application-adapters/${label}/${label}-${name}.ts`),
2117
- `wiring/application-ports/wire-${name}.ts`
2118
- ],
2119
- implementations: 'infrastructure/application-adapters',
2120
- wired: true,
2121
- sharedKernel: true
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`);
2122
2065
  }
2123
2066
  };
2124
- const subfolders = (folder)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder, {
2125
- withFileTypes: true
2126
- }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
2127
- 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() : [];
2128
- const labelsOf = (ownerPath, kind, name)=>{
2129
- const { implementations } = kindLayouts[kind];
2130
- if (!implementations) return [];
2131
- return subfolders(node_path.join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
2132
- ownerPath,
2133
- name
2134
- }, [
2135
- label
2136
- ]).some((file)=>file.startsWith(`${implementations}/`) && node_fs.existsSync(node_path.join(ownerPath, file))));
2137
- };
2138
- 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`)));
2139
- const findBackendUnits = (ownerPath)=>{
2140
- const unit = (kind, name, aggregate)=>({
2141
- kind,
2142
- name,
2143
- ownerPath,
2144
- aggregate,
2145
- labels: labelsOf(ownerPath, kind, name)
2146
- });
2147
- const aggregates = aggregatesOf(ownerPath);
2148
- 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)));
2149
- const at = (folder, suffix, kind)=>namesBySuffix(node_path.join(ownerPath, folder), suffix).map((name)=>unit(kind, name));
2150
- return [
2151
- ...aggregates.map((name)=>unit('aggregate', name)),
2152
- ...inAggregates('entity'),
2153
- ...at('domain/entities', '.entity.ts', 'entity'),
2154
- ...inAggregates('value-object'),
2155
- ...at('domain/value-objects', '.value-object.ts', 'value-object'),
2156
- ...at('domain/services', '-domain-service.ts', 'domain-service'),
2157
- ...at('application/ports', '.ts', 'port'),
2158
- ...at('application/queries', '-query.ts', 'query'),
2159
- ...at('application/commands', '-command.ts', 'command'),
2160
- ...at('application/use-cases', '-use-case.ts', 'use-case'),
2161
- ...at('application/services', '-application-service.ts', 'application-service'),
2162
- ...at('infrastructure/services', '-infrastructure-service.ts', 'infrastructure-service'),
2163
- ...at('presentation/services', '-presentation-service.ts', 'presentation-service')
2164
- ];
2165
- };
2166
- const kebabName = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
2167
- const lowerFirst = (value)=>value[0].toLowerCase() + value.slice(1);
2168
- const unitMoves = (unit, target)=>{
2169
- const layout = kindLayouts[unit.kind];
2170
- const from = layout.files(unit, unit.labels);
2171
- const to = layout.files(target, unit.labels);
2172
- const moves = new Map();
2173
- from.forEach((file, index)=>{
2174
- const oldPath = node_path.join(unit.ownerPath, file);
2175
- if (node_fs.existsSync(oldPath)) moves.set(oldPath, node_path.join(target.ownerPath, to[index]));
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;
2076
+ };
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
+ ]
2094
+ }
2095
+ }
2176
2096
  });
2177
- if ('aggregate' === unit.kind) {
2178
- const oldFolder = node_path.join(unit.ownerPath, 'domain/aggregates', unit.name);
2179
- const newFolder = node_path.join(target.ownerPath, 'domain/aggregates', target.name);
2180
- const own = new Set(aggregateOwnFiles(unit.name).map((file)=>node_path.join(oldFolder, file)));
2181
- for (const file of walk(oldFolder))if (!own.has(file)) moves.set(file, node_path.join(newFolder, node_path.relative(oldFolder, file)));
2182
- }
2183
- return moves;
2184
- };
2185
- const validateBackendMove = (unit, target, sharedKernelPath)=>{
2186
- if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
2187
- if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
2188
- 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';
2189
- for (const [from, to] of unitMoves(unit, target))if (to !== from && node_fs.existsSync(to)) return `${node_path.relative(target.ownerPath, to)} already exists`;
2190
- return true;
2191
2097
  };
2192
- const ownerOf = (rootFolderPath, file)=>{
2193
- const [area, context] = node_path.relative(rootFolderPath, file).split(node_path.sep);
2194
- if ('bounded-contexts' === area && context) return {
2195
- context,
2196
- path: node_path.join(rootFolderPath, area, context)
2197
- };
2198
- if ('shared-kernel' === area) return {
2199
- context: void 0,
2200
- path: node_path.join(rootFolderPath, area)
2201
- };
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}`;
2202
2101
  };
2203
- const inMemoryDbFile = (rootFolderPath)=>node_path.join(rootFolderPath, 'shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts');
2204
- const isolationAllows = (rootFolderPath, from, to)=>{
2205
- const fromOwner = ownerOf(rootFolderPath, from);
2206
- const toOwner = ownerOf(rootFolderPath, to);
2207
- if (!fromOwner || !toOwner?.context) return true;
2208
- if (fromOwner.context) return fromOwner.context === toOwner.context || true === crossContextImportAllowed(from, to);
2209
- const inside = (folder)=>to === node_path.join(toOwner.path, folder) || to.startsWith(node_path.join(toOwner.path, folder) + node_path.sep);
2210
- return inside('domain/errors') || from.replace(codeExtension, '') === inMemoryDbFile(rootFolderPath).replace(codeExtension, '') && inside('domain');
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;
2211
2110
  };
2212
- const moveBackendUnit = (projectRoot, rootFolderPath, unit, target)=>{
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;
2213
2129
  const layout = kindLayouts[unit.kind];
2214
- const moves = unitMoves(unit, target);
2215
- const withoutExtension = new Map([
2216
- ...moves
2217
- ].map(([from, to])=>[
2218
- from.replace(codeExtension, ''),
2219
- to.replace(codeExtension, '')
2220
- ]));
2221
- const folders = 'aggregate' === unit.kind ? [
2222
- [
2223
- node_path.join(unit.ownerPath, 'domain/aggregates', unit.name),
2224
- node_path.join(target.ownerPath, 'domain/aggregates', target.name)
2225
- ]
2226
- ] : [];
2227
- const movedPath = (candidate)=>{
2228
- const extension = candidate.match(codeExtension)?.[0];
2229
- if (extension) return moves.get(candidate);
2230
- return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
2231
- };
2232
- const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
2233
- const oldNaming = new UnknownFormatNaming(unit.name);
2234
- const newNaming = new UnknownFormatNaming(target.name);
2235
- const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
2236
- const oldAggregateFolder = unit.aggregate && node_path.join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
2237
- const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === node_path.join(oldAggregateFolder, 'index'));
2238
- const mainFile = [
2239
- ...moves.keys()
2240
- ][0];
2241
- const newMainFile = moves.get(mainFile);
2242
- const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
2243
- const barrelImporters = leavesAggregate ? [
2244
- ...codeFiles
2245
- ].filter(([file, content])=>!moves.has(file) && [
2246
- ...content.matchAll(namedImports)
2247
- ].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
2248
- const violations = [];
2249
- const relative = (file)=>toPosix(node_path.relative(projectRoot, file));
2250
- for (const file of codeFiles.keys()){
2251
- const from = moves.get(file) ?? file;
2252
- for (const imported of importsOf(file)){
2253
- const to = movedPath(imported);
2254
- if (moves.has(file) || to) {
2255
- if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
2256
- relative(from),
2257
- relative(to ?? imported)
2258
- ]);
2259
- }
2260
- }
2261
- }
2262
- for (const [file] of barrelImporters)if (!isolationAllows(rootFolderPath, file, newMainFile)) violations.push([
2263
- relative(file),
2264
- relative(newMainFile)
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
2265
2137
  ]);
2266
- if (violations.length) return {
2267
- violations
2268
- };
2269
- const word = (form)=>`(?<![\\w$])${escapeRegExp(form)}(?![\\w$])`;
2270
- const oldCore = layout.core(oldNaming.ClassName);
2271
- const newCore = layout.core(newNaming.ClassName);
2272
- const prefixes = [
2273
- ...unit.labels.map((label)=>new UnknownFormatNaming(label).ClassName),
2274
- ...layout.wired ? [
2275
- 'wire'
2276
- ] : []
2277
- ];
2278
- const renames = [
2279
- {
2280
- pattern: new RegExp(`(?<![\\w$])(${prefixes.map(escapeRegExp).join('|')})?${escapeRegExp(oldCore)}(?![\\w$])`, 'g'),
2281
- to: `$1${newCore}`
2282
- },
2283
- {
2284
- pattern: new RegExp(word(lowerFirst(oldCore)), 'g'),
2285
- to: lowerFirst(newCore)
2286
- },
2287
- {
2288
- pattern: new RegExp(`(describe\\(\\s*['"\`])${escapeRegExp(oldNaming.withSpaces)}(?=[ '"\`])`, 'g'),
2289
- to: `$1${newNaming.withSpaces}`,
2290
- movedOnly: true
2291
- }
2292
- ];
2293
- if ('aggregate' === unit.kind) renames.push({
2294
- pattern: new RegExp(word(oldNaming.ClassName), 'g'),
2295
- to: newNaming.ClassName
2296
- }, {
2297
- pattern: new RegExp(word(oldNaming.variableName), 'g'),
2298
- to: newNaming.variableName,
2299
- movedOnly: true
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
2300
2165
  });
2301
- if ('entity' === unit.kind || 'value-object' === unit.kind) renames.push({
2302
- pattern: new RegExp(word(oldNaming.variableName), 'g'),
2303
- to: newNaming.variableName,
2304
- movedOnly: true
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
+ ]
2305
2172
  });
2306
- const oldSection = new UnknownFormatNaming(plural(unit.name));
2307
- const newSection = new UnknownFormatNaming(plural(target.name));
2308
- const renamesSection = 'aggregate' === unit.kind && unit.name !== target.name;
2309
- 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;
2310
- const plan = stageModuleMove({
2311
- projectRoot,
2312
- stopAt: rootFolderPath,
2313
- moves,
2314
- movedPath,
2315
- rename: (content, { moved })=>renames.reduce((result, { pattern, to, movedOnly })=>movedOnly && !moved ? result : result.replace(pattern, to), content),
2316
- 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
2317
2183
  });
2318
- if (leavesAggregate && oldAggregateFolder) {
2319
- const indexFile = new File(node_path.join(oldAggregateFolder, 'index.ts'));
2320
- const exportLine = /^export\s+\*\s+from\s+(['"])([^'"\n]+)\1;?\s*$/;
2321
- indexFile.update(indexFile.data.split('\n').filter((line)=>{
2322
- const specifier = line.match(exportLine)?.[2];
2323
- return !specifier || node_path.resolve(node_path.dirname(indexFile.path), specifier) !== newMainFile.replace(codeExtension, '');
2324
- }).join('\n'));
2325
- if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
2326
- for (const [file] of barrelImporters){
2327
- const importer = new File(file);
2328
- let content = importer.data;
2329
- for (const match of content.matchAll(namedImports)){
2330
- const [statement, typeOnly = '', names, quote, specifier] = match;
2331
- if (!isOldBarrel(resolve(specifier, file)?.resolved)) continue;
2332
- const items = names.split(',').map((item)=>item.trim()).filter((item)=>!!item);
2333
- const own = new RegExp(`^(?:type\\s+)?${newNaming.ClassName}(?:\\s+as\\s+[\\w$]+)?$`);
2334
- const moved = items.filter((item)=>own.test(item));
2335
- if (!moved.length) continue;
2336
- const rest = items.filter((item)=>!own.test(item));
2337
- const direct = `import ${typeOnly}{ ${moved.join(', ')} } from ${quote}${projectRelative(file, newMainFile)}${quote}`;
2338
- 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']
2339
2256
  }
2340
- importer.update(content);
2341
- }
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}
2342
2276
  }
2343
- if (target.aggregate && (target.aggregate !== unit.aggregate || target.ownerPath !== unit.ownerPath)) {
2344
- const kindFolder = 'entity' === unit.kind ? 'entities' : 'value-objects';
2345
- const indexFile = new File(node_path.join(target.ownerPath, 'domain/aggregates', target.aggregate, 'index.ts'));
2346
- indexFile.addLineIfMissing(`export * from './${kindFolder}/${target.name}.${unit.kind}'`);
2347
- if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
2277
+ });
2278
+ `;
2279
+ };
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;
2348
2298
  }
2349
- return plan;
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
+ `;
2350
2335
  };
2351
- const projectRelative = (fromFile, toFile)=>{
2352
- const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toFile.replace(codeExtension, '')));
2353
- return relative.startsWith('.') ? relative : `./${relative}`;
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');
2354
2364
  };
2355
- const importSpecifier = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"\n]+)\1/g;
2356
- const importLine = /^\s*(?:import|export)\b[^'"\n]*\bfrom\s*(['"])([^'"\n]+)\1;?\s*$/;
2357
- const deleteBackendUnit = (projectRoot, rootFolderPath, unit)=>{
2358
- const files = [
2359
- ...unitMoves(unit, unit).keys()
2360
- ];
2361
- const fileSet = new Set(files);
2362
- const stems = new Set(files.map((file)=>file.replace(codeExtension, '')));
2363
- const aggregateFolder = 'aggregate' === unit.kind ? node_path.join(unit.ownerPath, 'domain/aggregates', unit.name) : void 0;
2364
- const parentAggregate = unit.aggregate ? node_path.join(unit.ownerPath, 'domain/aggregates', unit.aggregate) : void 0;
2365
- const isUnit = (resolved)=>stems.has(resolved) || !!aggregateFolder && (resolved === aggregateFolder || resolved.startsWith(`${aggregateFolder}${node_path.sep}`));
2366
- const isParentBarrel = (resolved)=>!!parentAggregate && (resolved === parentAggregate || resolved === node_path.join(parentAggregate, 'index'));
2367
- const { codeFiles, resolve } = projectImports(projectRoot);
2368
- const resolved = (specifier, file)=>resolve(specifier, file)?.resolved;
2369
- const withoutUnitImports = (content, file)=>content.split('\n').filter((line)=>{
2370
- const specifier = line.match(importLine)?.[2];
2371
- const target = specifier && resolved(specifier, file);
2372
- return !(target && isUnit(target));
2373
- }).join('\n');
2374
- const cleaned = new Map();
2375
- const inMemoryDb = inMemoryDbFile(rootFolderPath);
2376
- if ('aggregate' === unit.kind && codeFiles.has(inMemoryDb)) {
2377
- const section = new UnknownFormatNaming(plural(unit.name));
2378
- const original = codeFiles.get(inMemoryDb);
2379
- const content = withoutUnitImports(original.replace(new RegExp(`^[ \\t]*${escapeRegExp(section.variableName)}\\s*=\\s*this\\.section<[^\\n]*\\n?`, 'm'), ''), inMemoryDb);
2380
- if (content !== original) cleaned.set(inMemoryDb, content);
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);
2381
2395
  }
2382
- if (parentAggregate) {
2383
- const index = node_path.join(parentAggregate, 'index.ts');
2384
- const original = codeFiles.get(index);
2385
- if (void 0 !== original) {
2386
- const content = withoutUnitImports(original, index);
2387
- 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;
2388
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);
2389
2426
  }
2390
- const ClassName = new UnknownFormatNaming(unit.name).ClassName;
2391
- const namedImports = /import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\2/g;
2392
- const usedBy = [];
2393
- const relative = (file)=>toPosix(node_path.relative(projectRoot, file));
2394
- for (const [file, original] of codeFiles){
2395
- if (fileSet.has(file)) continue;
2396
- const content = cleaned.get(file) ?? original;
2397
- for (const [, , specifier] of content.matchAll(importSpecifier)){
2398
- const target = resolved(specifier, file);
2399
- if (target && isUnit(target)) usedBy.push([
2400
- relative(file),
2401
- relative(target)
2402
- ]);
2403
- }
2404
- for (const [, names, , specifier] of content.matchAll(namedImports)){
2405
- const target = resolved(specifier, file);
2406
- if (target && isParentBarrel(target) && new RegExp(`(?<![\\w$])${ClassName}(?![\\w$])`).test(names)) usedBy.push([
2407
- relative(file),
2408
- `${relative(target)} (${ClassName})`
2409
- ]);
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;
2410
2453
  }
2411
2454
  }
2412
- if (usedBy.length) return {
2413
- usedBy
2414
- };
2415
- for (const file of files)new File(file).delete(rootFolderPath);
2416
- for (const [file, content] of cleaned)new File(file).update(content);
2417
- return {
2418
- deleted: files,
2419
- updated: [
2420
- ...cleaned.keys()
2421
- ]
2422
- };
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
+ ];
2423
2480
  };
2424
- const contractKinds = [
2425
- 'aggregate',
2426
- 'command',
2427
- 'query',
2428
- 'port'
2429
- ];
2430
- const implementations_withWiring = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
2431
- const withHandlers = ()=>ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers');
2432
- const contractFile = (unit)=>'aggregate' === unit.kind ? `domain/aggregates/${unit.name}/${unit.name}-repository.ts` : kindLayouts[unit.kind].files(unit, [])[0];
2433
- const findContracts = (ownerPath)=>findBackendUnits(ownerPath).filter((unit)=>contractKinds.includes(unit.kind) && node_fs.existsSync(node_path.join(ownerPath, contractFile(unit))));
2434
- const implementationWireName = (label)=>`wire${new UnknownFormatNaming(label).ClassName}Implementation`;
2435
- const contractClassName = (unit)=>kindLayouts[unit.kind].core(new UnknownFormatNaming(unit.name).ClassName);
2436
- const implementationClassName = (unit, label)=>`${new UnknownFormatNaming(label).ClassName}${contractClassName(unit)}`;
2437
- const implementationFile = (unit, label)=>{
2438
- const { implementations } = kindLayouts[unit.kind];
2439
- return kindLayouts[unit.kind].files(unit, [
2440
- label
2441
- ]).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'
2442
2484
  };
2443
- const contractWireFile = (unit)=>kindLayouts[unit.kind].files(unit, []).find((file)=>file.startsWith('wiring/'));
2444
- const handlerImplementation = (ContractName, ClassName, contractImport)=>withHandlers() ? `
2445
- import { defineHandler } from '@domain-first/handlers'
2446
- 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';
2447
2495
 
2448
- export class ${ClassName} extends ${ContractName} {
2449
- constructor() {
2450
- 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}
2451
2516
  }
2452
-
2453
- handle = defineHandler({
2454
- inputSchema: ${ContractName}.inputSchema,
2455
- outputSchema: ${ContractName}.outputSchema,
2456
- handler: async (input) => {
2457
- 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'
2458
2543
  }
2459
- })
2460
- }
2461
- `.trim() : `
2462
- import { ${ContractName} } from '${contractImport}'
2463
-
2464
- export class ${ClassName} extends ${ContractName} {
2465
- constructor() {
2466
- 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);
2467
2572
  }
2468
- }
2469
- `.trim();
2470
- const createImplementation = (ownerFolder, unit, label)=>{
2471
- const naming = new UnknownFormatNaming(unit.name);
2472
- const ContractName = contractClassName(unit);
2473
- const className = implementationClassName(unit, label);
2474
- const [folder, fileName] = [
2475
- node_path.dirname(implementationFile(unit, label)),
2476
- 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
2477
2586
  ];
2478
- const implementationFolder = ownerFolder.subitem(folder.split('/'));
2479
- const inMemoryDb = !implementations_withWiring() && usesInMemoryDb(label);
2480
- switch(unit.kind){
2481
- case 'aggregate':
2482
- {
2483
- const contractImport = `../../../domain/aggregates/${unit.name}`;
2484
- if (inMemoryDb) {
2485
- const section = addInMemoryDbSection(naming, ownerFolder.subitem([
2486
- 'domain',
2487
- 'aggregates',
2488
- unit.name
2489
- ]).path);
2490
- const file = implementationFolder.createFile(fileName, `
2491
- ${inMemoryDbTypeImport(implementationFolder.subitem([
2492
- fileName
2493
- ]).path)}
2494
- import { ${ContractName} } from '${contractImport}'
2495
-
2496
- export class ${className} implements ${ContractName} {
2497
- ${inMemoryDbSectionMembers(section, false)}
2498
- }
2499
- `.trim());
2500
- return {
2501
- file,
2502
- className
2503
- };
2504
- }
2505
- const file = implementationFolder.createFile(fileName, `
2506
- import { ${ContractName} } from '${contractImport}'
2507
-
2508
- export class ${className} implements ${ContractName} {
2509
- constructor() {}
2510
- }
2511
-
2512
- `.trim());
2513
- return {
2514
- file,
2515
- className
2516
- };
2517
- }
2518
- case 'command':
2519
- case 'query':
2520
- {
2521
- const folderName = 'command' === unit.kind ? 'commands' : 'queries';
2522
- const file = implementationFolder.createFile(fileName, handlerImplementation(ContractName, className, `../../../application/${folderName}/${naming.fileName}-${unit.kind}`));
2523
- if (inMemoryDb) injectInMemoryDb(file, className);
2524
- return {
2525
- file,
2526
- className
2527
- };
2528
- }
2529
- case 'port':
2530
- {
2531
- const file = implementationFolder.createFile(fileName, `
2532
- import { ${ContractName} } from '../../../application/ports/${naming.fileName}'
2533
-
2534
- export class ${className} extends ${ContractName} {
2535
-
2536
- }
2537
- `.trim());
2538
- return {
2539
- file,
2540
- className
2541
- };
2542
- }
2543
- default:
2544
- 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
+ }
2545
2631
  }
2632
+ writePendingChanges();
2633
+ return true;
2546
2634
  };
2547
- const inMemoryRepositoryWiring = (ownerFolder, unit, wireFile)=>(implementation, dependency)=>{
2548
- if ('aggregate' !== unit.kind || !isInMemoryDb(dependency)) return false;
2549
- keepInMemoryDbSection(new File(implementation.file), addInMemoryDbSection(new UnknownFormatNaming(unit.name), ownerFolder.subitem([
2550
- 'domain',
2551
- 'aggregates',
2552
- unit.name
2553
- ]).path));
2554
- wireInMemoryDb(wireFile, implementation.className);
2555
- 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
+ ] : [];
2556
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
+ }));
2557
2757
  const reactKindLayouts = {
2558
2758
  page: {
2559
2759
  folder: 'pages',
@@ -3394,16 +3594,23 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
3394
3594
  if (!implementation) throw new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
3395
3595
  field: key
3396
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
+ });
3397
3602
  const valid = validateLabel(implementation.type);
3398
3603
  if (true !== valid) throw new RequestError('INVALID_IMPLEMENTATION', valid, {
3399
3604
  field: key
3400
3605
  });
3401
3606
  const label = implementation.type.trim();
3402
3607
  const saveForFutureUse = implementation.save ?? false;
3608
+ const entered = !choices.some((choice)=>choice.value === label);
3403
3609
  if (remember && saveForFutureUse && !system.some((choice)=>choice.value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
3404
3610
  return {
3405
3611
  label,
3406
- saveForFutureUse
3612
+ saveForFutureUse,
3613
+ entered
3407
3614
  };
3408
3615
  }
3409
3616
  const type = await interaction_select({
@@ -3419,7 +3626,8 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
3419
3626
  });
3420
3627
  if ('string' == typeof type) return {
3421
3628
  label: type,
3422
- saveForFutureUse: true
3629
+ saveForFutureUse: true,
3630
+ entered: false
3423
3631
  };
3424
3632
  const saveForFutureUse = type !== enterImplementationTypeOnce;
3425
3633
  const label = (await interaction_input({
@@ -3430,7 +3638,8 @@ const promptImplementationType = async (message, kind, { existing = [], purpose
3430
3638
  if (saveForFutureUse && remember && !choices.some(({ value })=>value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
3431
3639
  return {
3432
3640
  label,
3433
- saveForFutureUse
3641
+ saveForFutureUse,
3642
+ entered: !choices.some(({ value })=>value === label)
3434
3643
  };
3435
3644
  };
3436
3645
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
@@ -3476,7 +3685,12 @@ describe('${aggregateNaming.withSpaces}', () => {
3476
3685
  if (withRepository) {
3477
3686
  aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.ts`, `export abstract class ${aggregateNaming.ClassName}Repository { }`);
3478
3687
  barrelFile.addLine(`export * from './${aggregateNaming.fileName}-repository'`);
3479
- 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
+ });
3480
3694
  let addTestImplementation = false;
3481
3695
  let testImplementationType = '';
3482
3696
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -3500,29 +3714,6 @@ describe('${aggregateNaming.withSpaces}', () => {
3500
3714
  labels: []
3501
3715
  };
3502
3716
  for (const implementation of implementationTypes)createImplementation(boundedContextFolder, repository, new UnknownFormatNaming(implementation).fileName);
3503
- if (scaffoldUnitTests) {
3504
- const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
3505
- const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
3506
- import { describe, test, expect, beforeEach } from '${ConfigFile.backend.testingLibrary}'
3507
- ${ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `import { wire${aggregateNaming.ClassName}Repository } from '../../../wiring/repositories/wire-${aggregateNaming.fileName}-repository'
3508
- import type { ${aggregateNaming.ClassName}Repository } from './${aggregateNaming.fileName}-repository'` : `import { ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository } from '../../../infrastructure/repositories/${implementationNaming.fileName}/${implementationNaming.fileName}-${aggregateNaming.fileName}-repository'
3509
-
3510
- type ${aggregateNaming.ClassName}Repository = ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`}
3511
-
3512
- let ${aggregateNaming.variableName}Repository: ${aggregateNaming.ClassName}Repository
3513
-
3514
- beforeEach(() => {
3515
- ${aggregateNaming.variableName}Repository = ${ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `wire${aggregateNaming.ClassName}Repository()` : `new ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository()`}
3516
- })
3517
-
3518
- describe('${aggregateNaming.withSpaces} repository', () => {
3519
- test('can be ${ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? 'wired' : 'created via constructor'}', () => {
3520
- expect(${aggregateNaming.variableName}Repository).toBeDefined()
3521
- })
3522
- })
3523
- `.trim());
3524
- if (!ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') && usesInMemoryDb(infrastructureImplementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`);
3525
- }
3526
3717
  if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
3527
3718
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
3528
3719
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
@@ -3539,6 +3730,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
3539
3730
  export const wire${aggregateNaming.ClassName}Repository = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
3540
3731
  `.trim());
3541
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);
3542
3738
  }
3543
3739
  }
3544
3740
  };
@@ -3548,7 +3744,6 @@ const scaffoldNewApplicationPort = async (boundedContextFolder)=>{
3548
3744
  message: 'Name: '
3549
3745
  });
3550
3746
  const naming = new UnknownFormatNaming(name);
3551
- const scaffoldUnitTests = Boolean(ConfigFile.backend.testingLibrary);
3552
3747
  const wiringFolder = boundedContextFolder.subitem([
3553
3748
  'wiring',
3554
3749
  'application-ports'
@@ -3563,9 +3758,14 @@ export abstract class ${naming.ClassName} {
3563
3758
  }
3564
3759
  `.trim());
3565
3760
  const crossContext = hasNeighboringBoundedContext(boundedContextFolder.path);
3566
- const { label: implementationType } = await promptImplementationType('Adapter implementation type:', 'ports', {
3761
+ const primary = await promptImplementationType('Adapter implementation type:', 'ports', {
3567
3762
  crossContext
3568
3763
  });
3764
+ const implementationType = primary.label;
3765
+ const withIntegrationSpec = await wantsIntegrationTests(primary.label, {
3766
+ entered: primary.entered,
3767
+ save: primary.saveForFutureUse
3768
+ });
3569
3769
  const addTestImplementation = offersTestImplementation() && await interaction_confirm({
3570
3770
  key: 'withTestImplementation',
3571
3771
  message: 'With test implementation'
@@ -3588,28 +3788,6 @@ export abstract class ${naming.ClassName} {
3588
3788
  ownerPath: boundedContextFolder.path,
3589
3789
  labels: []
3590
3790
  }, implementation);
3591
- if (scaffoldUnitTests) {
3592
- const implementationNaming = new UnknownFormatNaming(implementationType);
3593
- applicationPortsFolder.createFile(`${naming.fileName}.spec.ts`, `
3594
- import { describe, test, expect, beforeEach } from '${ConfigFile.backend.testingLibrary}'
3595
- ${ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `import { type ${naming.ClassName} } from './${naming.fileName}'
3596
- import { wire${naming.ClassName} } from '../../wiring/application-ports/wire-${naming.fileName}'` : `import { ${implementationNaming.ClassName}${naming.ClassName} } from '../../infrastructure/application-adapters/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}'
3597
-
3598
- type ${naming.ClassName} = ${implementationNaming.ClassName}${naming.ClassName}`}
3599
-
3600
- let ${naming.variableName}: ${naming.ClassName}
3601
-
3602
- beforeEach(() => {
3603
- ${naming.variableName} = ${ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `wire${naming.ClassName}()` : `new ${implementationNaming.ClassName}${naming.ClassName}()`}
3604
- })
3605
-
3606
- describe('${naming.withSpaces}', () => {
3607
- test('can be ${ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? 'wired' : 'created via constructor'}', () => {
3608
- expect(${naming.variableName}).toBeDefined()
3609
- })
3610
- })
3611
- `.trim());
3612
- }
3613
3791
  if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
3614
3792
  const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
3615
3793
  import { wireClass } from '@domain-first/wire'
@@ -3628,6 +3806,11 @@ export const wire${naming.ClassName} = envBranchedWire(${envBranchedWireArgument
3628
3806
 
3629
3807
  `.trim());
3630
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);
3631
3814
  }
3632
3815
  };
3633
3816
  const scaffoldNewApplicationService = async (boundedContextFolder)=>{
@@ -3705,10 +3888,13 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
3705
3888
  key: 'name',
3706
3889
  message: 'Name: '
3707
3890
  });
3708
- const scaffoldUnitTests = Boolean(ConfigFile.backend.testingLibrary);
3709
3891
  const naming = new UnknownFormatNaming(commandName);
3710
- const withWiring = ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
3711
- 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
+ });
3712
3898
  let addTestImplementation = false;
3713
3899
  let testImplementationType = '';
3714
3900
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -3745,29 +3931,6 @@ export abstract class ${naming.ClassName}Command {
3745
3931
  export abstract class ${naming.ClassName}Command {
3746
3932
 
3747
3933
  }`.trim());
3748
- if (scaffoldUnitTests) {
3749
- const implementationNaming = new UnknownFormatNaming(implementationType);
3750
- const specFile = commandsFolder.createFile(`${naming.fileName}-command.spec.ts`, `
3751
- import { describe, test, expect, beforeEach } from '${ConfigFile.backend.testingLibrary}'
3752
- ${withWiring ? `import { type ${naming.ClassName}Command } from './${naming.fileName}-command'
3753
- import { wire${naming.ClassName}Command } from '../../wiring/commands/wire-${naming.fileName}-command'` : `import { ${implementationNaming.ClassName}${naming.ClassName}Command } from '../../infrastructure/commands/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}-command'
3754
-
3755
- type ${naming.ClassName}Command = ${implementationNaming.ClassName}${naming.ClassName}Command`}
3756
-
3757
- let ${naming.variableName}Command: ${naming.ClassName}Command
3758
-
3759
- beforeEach(() => {
3760
- ${naming.variableName}Command = ${withWiring ? `wire${naming.ClassName}Command()` : `new ${implementationNaming.ClassName}${naming.ClassName}Command()`}
3761
- })
3762
-
3763
- describe('${naming.withSpaces} command', () => {
3764
- test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
3765
- expect(${naming.variableName}Command).toBeDefined()
3766
- })
3767
- })
3768
- `.trim());
3769
- if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Command`);
3770
- }
3771
3934
  if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
3772
3935
  const implementationNaming = new UnknownFormatNaming(implementationType);
3773
3936
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
@@ -3784,6 +3947,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
3784
3947
  export const wire${naming.ClassName}Command = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
3785
3948
  `.trim());
3786
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);
3787
3955
  }
3788
3956
  };
3789
3957
  const scaffold_new_domain_object_noAggregate = 'No aggregate';
@@ -4157,7 +4325,7 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
4157
4325
  pageSize: 20
4158
4326
  });
4159
4327
  const kind = 'aggregate' === unit.kind ? 'repositories' : 'command' === unit.kind ? 'commands' : 'query' === unit.kind ? 'queries' : 'ports';
4160
- const { label, saveForFutureUse } = await promptImplementationType('Implementation type:', kind, {
4328
+ const { label, saveForFutureUse, entered } = await promptImplementationType('Implementation type:', kind, {
4161
4329
  existing: unit.labels,
4162
4330
  purpose: 'all',
4163
4331
  remember: false,
@@ -4171,12 +4339,23 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
4171
4339
  if (branches.test && environments.includes(branches.test)) rememberImplementation(kind, 'test', label);
4172
4340
  if (environments.some((environment)=>environment !== branches.test)) rememberImplementation(kind, 'primary', label);
4173
4341
  };
4174
- 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
+ }
4175
4350
  const wireFile = new File(ownerFolder.path).subitem(contractWireFile(unit).split('/'));
4176
4351
  const wireName = `wire${contractClassName(unit)}`;
4177
4352
  const wired = branchesOf(wireFile, wireName);
4178
4353
  if (!wired) {
4179
4354
  rememberFor(branches.primary);
4355
+ await wantsIntegrationTests(label, {
4356
+ entered: false,
4357
+ save: false
4358
+ });
4180
4359
  report(`${wireFile.path} has no ${wireName} = envBranchedWire({...}): wire ${className} there yourself.`);
4181
4360
  return;
4182
4361
  }
@@ -4205,6 +4384,11 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
4205
4384
  required: true
4206
4385
  });
4207
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;
4208
4392
  const before = readWiredModule(wireFile.path, ownerFolder.path);
4209
4393
  wireFile.update(addBranchedImplementation(wireFile.data, wireName, {
4210
4394
  importLine: `import { ${className} } from '${relativeImport(wireFile.path, file.path)}'`,
@@ -4213,6 +4397,7 @@ const scaffoldNewImplementation = async (ownerFolder)=>{
4213
4397
  environments: chosenEnvironments
4214
4398
  }));
4215
4399
  const after = readWiredModule(wireFile.path, ownerFolder.path);
4400
+ if (withIntegrationSpec) scaffoldIntegrationSpec(unit, label);
4216
4401
  const unused = (before?.implementations ?? []).filter((x)=>!after?.implementations.some((y)=>y.className === x.className));
4217
4402
  for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
4218
4403
  await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
@@ -4258,16 +4443,6 @@ const scaffoldNewInfrastructureHelper = async (ownerFolder)=>{
4258
4443
  ...name.folders
4259
4444
  ]);
4260
4445
  folder.createFile(`${fileName}.ts`, `export const ${naming.variableName} = () => {}`);
4261
- if (ConfigFile.backend.testingLibrary) folder.createFile(`${fileName}.spec.ts`, `
4262
- import { describe, test, expect } from '${ConfigFile.backend.testingLibrary}'
4263
- import { ${naming.variableName} } from './${fileName}'
4264
-
4265
- describe('${naming.withSpaces}', () => {
4266
- test('is defined', () => {
4267
- expect(${naming.variableName}).toBeDefined()
4268
- })
4269
- })
4270
- `.trim());
4271
4446
  };
4272
4447
  const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
4273
4448
  const name = await interaction_input({
@@ -4275,7 +4450,7 @@ const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
4275
4450
  message: 'Name: '
4276
4451
  });
4277
4452
  const naming = new UnknownFormatNaming(name);
4278
- const scaffoldUnitTests = Boolean(ConfigFile.backend.testingLibrary);
4453
+ const withIntegrationSpec = await wantsServiceIntegrationSpec();
4279
4454
  const withWiring = ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
4280
4455
  const wiringFolder = boundedContextFolder.subitem([
4281
4456
  'wiring',
@@ -4290,23 +4465,6 @@ export class ${naming.ClassName}InfrastructureService {
4290
4465
 
4291
4466
  }
4292
4467
  `.trim());
4293
- if (scaffoldUnitTests) infrastructureServicesFolder.createFile(`${naming.fileName}-infrastructure-service.spec.ts`, `
4294
- import { describe, test, expect, beforeEach } from '${ConfigFile.backend.testingLibrary}'
4295
- ${withWiring ? `import { type ${naming.ClassName}InfrastructureService } from './${naming.fileName}-infrastructure-service'
4296
- import { wire${naming.ClassName}InfrastructureService } from '../../wiring/infrastructure-services/wire-${naming.fileName}-infrastructure-service'` : `import { ${naming.ClassName}InfrastructureService } from './${naming.fileName}-infrastructure-service'`}
4297
-
4298
- let ${naming.variableName}InfrastructureService: ${naming.ClassName}InfrastructureService
4299
-
4300
- beforeEach(() => {
4301
- ${naming.variableName}InfrastructureService = ${withWiring ? `wire${naming.ClassName}InfrastructureService()` : `new ${naming.ClassName}InfrastructureService()`}
4302
- })
4303
-
4304
- describe('${naming.withSpaces}', () => {
4305
- test('can be ${withWiring ? 'wired' : 'created'}', () => {
4306
- expect(${naming.variableName}InfrastructureService).toBeDefined()
4307
- })
4308
- })
4309
- `.trim());
4310
4468
  if (withWiring) {
4311
4469
  const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
4312
4470
  import { wireClass } from '@domain-first/wire'
@@ -4318,6 +4476,11 @@ export const wire${naming.ClassName}InfrastructureService = wireClass(
4318
4476
  )
4319
4477
  `.trim());
4320
4478
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
4479
+ if (withIntegrationSpec) scaffoldIntegrationSpec({
4480
+ kind: 'infrastructure-service',
4481
+ name: naming.fileName,
4482
+ ownerPath: boundedContextFolder.path
4483
+ });
4321
4484
  }
4322
4485
  };
4323
4486
  const scaffoldNewQuery = async (boundedContextFolder)=>{
@@ -4329,10 +4492,13 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
4329
4492
  key: 'name',
4330
4493
  message: 'Name: '
4331
4494
  });
4332
- const scaffoldUnitTests = Boolean(ConfigFile.backend.testingLibrary);
4333
4495
  const naming = new UnknownFormatNaming(queryName);
4334
- const withWiring = ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
4335
- 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
+ });
4336
4502
  let addTestImplementation = false;
4337
4503
  let testImplementationType = '';
4338
4504
  addTestImplementation = offersTestImplementation() && await interaction_confirm({
@@ -4369,29 +4535,6 @@ export abstract class ${naming.ClassName}Query {
4369
4535
  export abstract class ${naming.ClassName}Query {
4370
4536
 
4371
4537
  }`.trim());
4372
- if (scaffoldUnitTests) {
4373
- const implementationNaming = new UnknownFormatNaming(implementationType);
4374
- const specFile = queriesFolder.createFile(`${naming.fileName}-query.spec.ts`, `
4375
- import { describe, test, expect, beforeEach } from '${ConfigFile.backend.testingLibrary}'
4376
- ${withWiring ? `import { type ${naming.ClassName}Query } from './${naming.fileName}-query'
4377
- import { wire${naming.ClassName}Query } from '../../wiring/queries/wire-${naming.fileName}-query'` : `import { ${implementationNaming.ClassName}${naming.ClassName}Query } from '../../infrastructure/queries/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}-query'
4378
-
4379
- type ${naming.ClassName}Query = ${implementationNaming.ClassName}${naming.ClassName}Query`}
4380
-
4381
- let ${naming.variableName}Query: ${naming.ClassName}Query
4382
-
4383
- beforeEach(() => {
4384
- ${naming.variableName}Query = ${withWiring ? `wire${naming.ClassName}Query()` : `new ${implementationNaming.ClassName}${naming.ClassName}Query()`}
4385
- })
4386
-
4387
- describe('${naming.withSpaces} query', () => {
4388
- test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
4389
- expect(${naming.variableName}Query).toBeDefined()
4390
- })
4391
- })
4392
- `.trim());
4393
- if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Query`);
4394
- }
4395
4538
  if (ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
4396
4539
  const implementationNaming = new UnknownFormatNaming(implementationType);
4397
4540
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
@@ -4408,6 +4551,11 @@ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>
4408
4551
  export const wire${naming.ClassName}Query = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
4409
4552
  `.trim());
4410
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);
4411
4559
  }
4412
4560
  };
4413
4561
  const scaffoldNewUseCase = async (boundedContextFolder)=>{
@@ -4668,4 +4816,4 @@ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps
4668
4816
  break;
4669
4817
  }
4670
4818
  };
4671
- 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 };