@domain-first/project-structure 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -188,7 +188,7 @@ admin/panel/users → pages/admin/panel/admin-panel-users-page.tsx (AdminPane
188
188
 
189
189
  ### How to add tooling
190
190
 
191
- Choose **Add integration** to configure Storybook, Prisma 8, Vitest, Playwright, OpenAPI generation or an Orval React Query client. Integrations add config files, package scripts and `.gitignore` entries, then print the install commands. Nothing is installed or run for you.
191
+ Choose **Add integration** to configure Storybook, Prisma 8, Vitest, Playwright, integration tests on PostgreSQL in Testcontainers, OpenAPI generation or an Orval React Query client. Integrations add config files, package scripts and `.gitignore` entries, then print the install commands. Nothing is installed or run for you.
192
192
 
193
193
  **Missing domain-first packages** prints the `npm i` command for packages from the config that are not in `package.json`.
194
194
 
package/dist/index.cjs CHANGED
@@ -1311,6 +1311,161 @@ const addStorybook = async ()=>{
1311
1311
  })
1312
1312
  ];
1313
1313
  };
1314
+ const integrationFolder = 'specs/integration';
1315
+ const testcontainersScripts = {
1316
+ 'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
1317
+ };
1318
+ const testcontainersVitestConfig = (inlineHandlersNext)=>{
1319
+ const server = inlineHandlersNext ? `,
1320
+ server: {
1321
+ deps: {
1322
+ // Imports \`next/headers\` without an extension, which only a bundler can resolve
1323
+ inline: ['@domain-first/handlers-next']
1324
+ }
1325
+ }` : '';
1326
+ return `import { fileURLToPath } from 'node:url';
1327
+ import { defineConfig } from 'vitest/config';
1328
+
1329
+ // Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
1330
+ export default defineConfig({
1331
+ // Paths below are relative to the project root, not this folder
1332
+ root: fileURLToPath(new URL('../..', import.meta.url)),
1333
+ resolve: {
1334
+ tsconfigPaths: true
1335
+ },
1336
+ test: {
1337
+ include: ['${integrationFolder}/**/*.spec.ts'],
1338
+ // Development implementations work with the real database
1339
+ env: { NODE_ENV: 'development' },
1340
+ globalSetup: ['${integrationFolder}/global-setup.ts'],
1341
+ setupFiles: ['${integrationFolder}/setup-env.ts'],
1342
+ // Pulling the image on the first run takes a while
1343
+ hookTimeout: 120_000${server}
1344
+ }
1345
+ });
1346
+ `;
1347
+ };
1348
+ const testcontainersGlobalSetup = (migrationCommand)=>{
1349
+ const migrations = migrationCommand ? `
1350
+ // dotenv in the Prisma config does not override an already set variable
1351
+ execSync(${JSON.stringify(migrationCommand)}, {
1352
+ cwd: project.config.root,
1353
+ env: { ...process.env, DATABASE_URL: databaseUrl },
1354
+ // On failure the error carries the command's output
1355
+ stdio: 'pipe'
1356
+ });
1357
+ ` : `
1358
+ // Apply your migrations to databaseUrl here.
1359
+ `;
1360
+ return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
1361
+ import type { TestProject } from 'vitest/node';
1362
+
1363
+ declare module 'vitest' {
1364
+ export interface ProvidedContext {
1365
+ databaseUrl: string;
1366
+ }
1367
+ }
1368
+
1369
+ const POSTGRES_IMAGE = 'postgres:15';
1370
+ const POSTGRES_PORT = 5432;
1371
+ const POSTGRES_USER = 'test';
1372
+ const POSTGRES_PASSWORD = 'test';
1373
+ const POSTGRES_DB = 'test';
1374
+
1375
+ export default async function setup(project: TestProject) {
1376
+ const container = await new GenericContainer(POSTGRES_IMAGE)
1377
+ .withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
1378
+ .withExposedPorts(POSTGRES_PORT)
1379
+ // During init PostgreSQL listens on a unix socket only and restarts,
1380
+ // so checking over TCP passes once the final server is up
1381
+ .withHealthCheck({
1382
+ test: [
1383
+ 'CMD-SHELL',
1384
+ \`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
1385
+ ],
1386
+ interval: 250,
1387
+ timeout: 1000,
1388
+ retries: 1000
1389
+ })
1390
+ .withWaitStrategy(Wait.forHealthCheck())
1391
+ .withStartupTimeout(120_000)
1392
+ .start();
1393
+
1394
+ const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
1395
+ ${migrations}
1396
+ project.provide('databaseUrl', databaseUrl);
1397
+
1398
+ return async () => {
1399
+ await container.stop();
1400
+ };
1401
+ }
1402
+ `;
1403
+ };
1404
+ const testcontainersSetupEnv = `import 'dotenv/config';
1405
+ import { inject } from 'vitest';
1406
+
1407
+ // Runs before each spec's imports: development implementations get the .env
1408
+ // config, and DATABASE_URL points to the container instead of the one from .env.
1409
+ if (process.env.NODE_ENV !== 'development') {
1410
+ throw new Error(
1411
+ \`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
1412
+ );
1413
+ }
1414
+
1415
+ process.env.DATABASE_URL = inject('databaseUrl');
1416
+ `;
1417
+ const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
1418
+
1419
+ test('connects to the database in the container', () => {
1420
+ expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
1421
+ });
1422
+ `;
1423
+ const testcontainers_stageFile = (filePath, content)=>{
1424
+ const file = new File(filePath);
1425
+ if (!file.exists || file.data !== content) file.data = content;
1426
+ };
1427
+ const addTestcontainers = async ()=>{
1428
+ const config = ConfigFile.Instance.data;
1429
+ const root = new ProjectRoot().path;
1430
+ const manifestFile = new File(external_node_path_default().join(root, 'package.json'));
1431
+ const manifest = JSON.parse(manifestFile.data);
1432
+ const dependencies = {
1433
+ ...manifest.dependencies,
1434
+ ...manifest.devDependencies
1435
+ };
1436
+ const selected = await addPackageScripts(manifestFile, testcontainersScripts);
1437
+ const withPrisma = new File(external_node_path_default().resolve(root, config.rootFolder, 'shared/infrastructure/prisma/prisma.config.ts')).exists;
1438
+ const migrationCommand = withPrisma ? `npx ${prismaScripts(config.rootFolder)['prisma:migration:apply']}` : void 0;
1439
+ const folder = external_node_path_default().join(root, integrationFolder);
1440
+ testcontainers_stageFile(external_node_path_default().join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
1441
+ testcontainers_stageFile(external_node_path_default().join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
1442
+ testcontainers_stageFile(external_node_path_default().join(folder, 'setup-env.ts'), testcontainersSetupEnv);
1443
+ const example = new File(external_node_path_default().join(folder, 'database/database.spec.ts'));
1444
+ if (!example.exists) example.data = testcontainers_exampleSpec;
1445
+ const unitConfig = new File(external_node_path_default().join(root, 'vitest.config.ts'));
1446
+ const excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
1447
+ const missing = [
1448
+ 'vitest',
1449
+ 'testcontainers',
1450
+ 'dotenv'
1451
+ ].filter((name)=>!dependencies[name]);
1452
+ return [
1453
+ ...missing.length ? [
1454
+ `npm install --save-dev ${missing.join(' ')}`
1455
+ ] : [],
1456
+ `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.`,
1457
+ ...migrationCommand ? [] : [
1458
+ `Apply your migrations in ${integrationFolder}/global-setup.ts.`
1459
+ ],
1460
+ ...excludedFromUnitTests ? [] : [
1461
+ `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
1462
+ ],
1463
+ 'Docker must be running for integration specs.',
1464
+ ...describeScripts(selected, {
1465
+ 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
1466
+ })
1467
+ ];
1468
+ };
1314
1469
  const vitestScripts = {
1315
1470
  test: 'vitest run --reporter=dot --silent=passed-only',
1316
1471
  'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
@@ -1331,8 +1486,8 @@ export default defineConfig({
1331
1486
  tsconfigPaths: true
1332
1487
  },
1333
1488
  test: {
1334
- // Playwright runs end-to-end specs
1335
- exclude: [...configDefaults.exclude, 'specs/e2e/**'],
1489
+ // Playwright runs end-to-end specs, test:integration runs integration ones
1490
+ exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
1336
1491
  coverage: {
1337
1492
  provider: 'v8',
1338
1493
  include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared/**/*.ts')}],
@@ -1404,6 +1559,10 @@ const integrations = [
1404
1559
  name: 'Playwright',
1405
1560
  run: addPlaywright
1406
1561
  },
1562
+ {
1563
+ name: 'Integration tests (Testcontainers, PostgreSQL)',
1564
+ run: addTestcontainers
1565
+ },
1407
1566
  {
1408
1567
  name: 'OpenAPI',
1409
1568
  run: addOpenapi,
package/dist/index.js CHANGED
@@ -929,6 +929,161 @@ const addStorybook = async ()=>{
929
929
  })
930
930
  ];
931
931
  };
932
+ const integrationFolder = 'specs/integration';
933
+ const testcontainersScripts = {
934
+ 'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
935
+ };
936
+ const testcontainersVitestConfig = (inlineHandlersNext)=>{
937
+ const server = inlineHandlersNext ? `,
938
+ server: {
939
+ deps: {
940
+ // Imports \`next/headers\` without an extension, which only a bundler can resolve
941
+ inline: ['@domain-first/handlers-next']
942
+ }
943
+ }` : '';
944
+ return `import { fileURLToPath } from 'node:url';
945
+ import { defineConfig } from 'vitest/config';
946
+
947
+ // Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
948
+ export default defineConfig({
949
+ // Paths below are relative to the project root, not this folder
950
+ root: fileURLToPath(new URL('../..', import.meta.url)),
951
+ resolve: {
952
+ tsconfigPaths: true
953
+ },
954
+ test: {
955
+ include: ['${integrationFolder}/**/*.spec.ts'],
956
+ // Development implementations work with the real database
957
+ env: { NODE_ENV: 'development' },
958
+ globalSetup: ['${integrationFolder}/global-setup.ts'],
959
+ setupFiles: ['${integrationFolder}/setup-env.ts'],
960
+ // Pulling the image on the first run takes a while
961
+ hookTimeout: 120_000${server}
962
+ }
963
+ });
964
+ `;
965
+ };
966
+ const testcontainersGlobalSetup = (migrationCommand)=>{
967
+ const migrations = migrationCommand ? `
968
+ // dotenv in the Prisma config does not override an already set variable
969
+ execSync(${JSON.stringify(migrationCommand)}, {
970
+ cwd: project.config.root,
971
+ env: { ...process.env, DATABASE_URL: databaseUrl },
972
+ // On failure the error carries the command's output
973
+ stdio: 'pipe'
974
+ });
975
+ ` : `
976
+ // Apply your migrations to databaseUrl here.
977
+ `;
978
+ return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
979
+ import type { TestProject } from 'vitest/node';
980
+
981
+ declare module 'vitest' {
982
+ export interface ProvidedContext {
983
+ databaseUrl: string;
984
+ }
985
+ }
986
+
987
+ const POSTGRES_IMAGE = 'postgres:15';
988
+ const POSTGRES_PORT = 5432;
989
+ const POSTGRES_USER = 'test';
990
+ const POSTGRES_PASSWORD = 'test';
991
+ const POSTGRES_DB = 'test';
992
+
993
+ export default async function setup(project: TestProject) {
994
+ const container = await new GenericContainer(POSTGRES_IMAGE)
995
+ .withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
996
+ .withExposedPorts(POSTGRES_PORT)
997
+ // During init PostgreSQL listens on a unix socket only and restarts,
998
+ // so checking over TCP passes once the final server is up
999
+ .withHealthCheck({
1000
+ test: [
1001
+ 'CMD-SHELL',
1002
+ \`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
1003
+ ],
1004
+ interval: 250,
1005
+ timeout: 1000,
1006
+ retries: 1000
1007
+ })
1008
+ .withWaitStrategy(Wait.forHealthCheck())
1009
+ .withStartupTimeout(120_000)
1010
+ .start();
1011
+
1012
+ const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
1013
+ ${migrations}
1014
+ project.provide('databaseUrl', databaseUrl);
1015
+
1016
+ return async () => {
1017
+ await container.stop();
1018
+ };
1019
+ }
1020
+ `;
1021
+ };
1022
+ const testcontainersSetupEnv = `import 'dotenv/config';
1023
+ import { inject } from 'vitest';
1024
+
1025
+ // Runs before each spec's imports: development implementations get the .env
1026
+ // config, and DATABASE_URL points to the container instead of the one from .env.
1027
+ if (process.env.NODE_ENV !== 'development') {
1028
+ throw new Error(
1029
+ \`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
1030
+ );
1031
+ }
1032
+
1033
+ process.env.DATABASE_URL = inject('databaseUrl');
1034
+ `;
1035
+ const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
1036
+
1037
+ test('connects to the database in the container', () => {
1038
+ expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
1039
+ });
1040
+ `;
1041
+ const testcontainers_stageFile = (filePath, content)=>{
1042
+ const file = new File(filePath);
1043
+ if (!file.exists || file.data !== content) file.data = content;
1044
+ };
1045
+ const addTestcontainers = async ()=>{
1046
+ const config = ConfigFile.Instance.data;
1047
+ const root = new ProjectRoot().path;
1048
+ const manifestFile = new File(node_path.join(root, 'package.json'));
1049
+ const manifest = JSON.parse(manifestFile.data);
1050
+ const dependencies = {
1051
+ ...manifest.dependencies,
1052
+ ...manifest.devDependencies
1053
+ };
1054
+ const selected = await addPackageScripts(manifestFile, testcontainersScripts);
1055
+ const withPrisma = new File(node_path.resolve(root, config.rootFolder, 'shared/infrastructure/prisma/prisma.config.ts')).exists;
1056
+ const migrationCommand = withPrisma ? `npx ${prismaScripts(config.rootFolder)['prisma:migration:apply']}` : void 0;
1057
+ const folder = node_path.join(root, integrationFolder);
1058
+ testcontainers_stageFile(node_path.join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
1059
+ testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
1060
+ testcontainers_stageFile(node_path.join(folder, 'setup-env.ts'), testcontainersSetupEnv);
1061
+ const example = new File(node_path.join(folder, 'database/database.spec.ts'));
1062
+ if (!example.exists) example.data = testcontainers_exampleSpec;
1063
+ const unitConfig = new File(node_path.join(root, 'vitest.config.ts'));
1064
+ const excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
1065
+ const missing = [
1066
+ 'vitest',
1067
+ 'testcontainers',
1068
+ 'dotenv'
1069
+ ].filter((name)=>!dependencies[name]);
1070
+ return [
1071
+ ...missing.length ? [
1072
+ `npm install --save-dev ${missing.join(' ')}`
1073
+ ] : [],
1074
+ `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.`,
1075
+ ...migrationCommand ? [] : [
1076
+ `Apply your migrations in ${integrationFolder}/global-setup.ts.`
1077
+ ],
1078
+ ...excludedFromUnitTests ? [] : [
1079
+ `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
1080
+ ],
1081
+ 'Docker must be running for integration specs.',
1082
+ ...describeScripts(selected, {
1083
+ 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
1084
+ })
1085
+ ];
1086
+ };
932
1087
  const vitestScripts = {
933
1088
  test: 'vitest run --reporter=dot --silent=passed-only',
934
1089
  'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
@@ -949,8 +1104,8 @@ export default defineConfig({
949
1104
  tsconfigPaths: true
950
1105
  },
951
1106
  test: {
952
- // Playwright runs end-to-end specs
953
- exclude: [...configDefaults.exclude, 'specs/e2e/**'],
1107
+ // Playwright runs end-to-end specs, test:integration runs integration ones
1108
+ exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
954
1109
  coverage: {
955
1110
  provider: 'v8',
956
1111
  include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared/**/*.ts')}],
@@ -1022,6 +1177,10 @@ const integrations = [
1022
1177
  name: 'Playwright',
1023
1178
  run: addPlaywright
1024
1179
  },
1180
+ {
1181
+ name: 'Integration tests (Testcontainers, PostgreSQL)',
1182
+ run: addTestcontainers
1183
+ },
1025
1184
  {
1026
1185
  name: 'OpenAPI',
1027
1186
  run: addOpenapi,
@@ -5,4 +5,5 @@ export * from './package-scripts';
5
5
  export * from './playwright';
6
6
  export * from './prisma';
7
7
  export * from './storybook';
8
+ export * from './testcontainers';
8
9
  export * from './vitest';
@@ -0,0 +1,7 @@
1
+ export declare const testcontainersScripts: {
2
+ 'test:integration': string;
3
+ };
4
+ export declare const testcontainersVitestConfig: (inlineHandlersNext: boolean) => string;
5
+ export declare const testcontainersGlobalSetup: (migrationCommand?: string) => string;
6
+ export declare const testcontainersSetupEnv = "import 'dotenv/config';\nimport { inject } from 'vitest';\n\n// Runs before each spec's imports: development implementations get the .env\n// config, and DATABASE_URL points to the container instead of the one from .env.\nif (process.env.NODE_ENV !== 'development') {\n throw new Error(\n `Integration specs need NODE_ENV=development to wire development implementations, got \"${process.env.NODE_ENV}\"`\n );\n}\n\nprocess.env.DATABASE_URL = inject('databaseUrl');\n";
7
+ export declare const addTestcontainers: () => Promise<string[]>;
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@domain-first/project-structure",
3
3
  "description": "Build and manage your Domain-First project structure with CLI",
4
- "version": "5.0.0",
4
+ "version": "5.1.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -49,12 +49,20 @@ It exits with 1 when anything is found. Checks turned off in the config (`rules.
49
49
 
50
50
  ```ts
51
51
  export class Order extends domainType(
52
- z.object({ id: z.instanceof(OrderId), lines: z.array(z.instanceof(OrderLine)), status: z.enum(['open', 'paid']) })
52
+ z.object({
53
+ id: z.instanceof(OrderId),
54
+ lines: z.array(z.instanceof(OrderLine)),
55
+ status: z.enum(["open", "paid"]),
56
+ }),
53
57
  ) {
54
- pay = () => {
55
- if (this.status === 'paid') throw new AlreadyPaidOrderSalesError({ id: this.id.value })
56
- return new Order({ id: this.id, lines: this.lines, status: 'paid' })
57
- }
58
+ withPayment = () => {
59
+ if (this.status === "paid") {
60
+ throw new AlreadyPaidOrderSalesError({
61
+ id: this.id.snapshot,
62
+ });
63
+ }
64
+ return this.with({ status: "paid" });
65
+ };
58
66
  }
59
67
  ```
60
68
 
@@ -76,7 +84,10 @@ export class Order extends domainType(
76
84
  Dependencies (constructor parameters and their wires) are added only by `df-ps` (`df-ps-scaffold`, rule 3): the generator's `Dependencies:` step or `Wire dependency`. It keeps each `wireClass(X, [...])` in the order of the constructor, which TypeScript checks:
77
85
 
78
86
  ```ts
79
- export const wirePlaceOrderUseCase = wireClass(PlaceOrderUseCase, [wireOrderRepository, wirePaymentGateway])
87
+ export const wirePlaceOrderUseCase = wireClass(PlaceOrderUseCase, [
88
+ wireOrderRepository,
89
+ wirePaymentGateway,
90
+ ]);
80
91
  ```
81
92
 
82
93
  - Use the injected dependencies in the class body; don't edit the parameter list or the wire list.