@domain-first/project-structure 5.0.1 → 5.1.1

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,178 @@ 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 excludeFromUnitTests = (content)=>{
1424
+ const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
1425
+ if (!exclude.test(content)) return;
1426
+ const entry = `'${integrationFolder}/**'`;
1427
+ return content.replace(exclude, (_, items, comma, whitespace)=>{
1428
+ const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
1429
+ const separator = void 0 === indent ? ', ' : `,\n${indent}`;
1430
+ return `${items}${separator}${entry}${comma}${whitespace}]`;
1431
+ }).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
1432
+ };
1433
+ const testcontainers_stageFile = (filePath, content)=>{
1434
+ const file = new File(filePath);
1435
+ if (!file.exists || file.data !== content) file.data = content;
1436
+ };
1437
+ const addTestcontainers = async ()=>{
1438
+ const config = ConfigFile.Instance.data;
1439
+ const root = new ProjectRoot().path;
1440
+ const manifestFile = new File(external_node_path_default().join(root, 'package.json'));
1441
+ const manifest = JSON.parse(manifestFile.data);
1442
+ const dependencies = {
1443
+ ...manifest.dependencies,
1444
+ ...manifest.devDependencies
1445
+ };
1446
+ const selected = await addPackageScripts(manifestFile, testcontainersScripts);
1447
+ const withPrisma = new File(external_node_path_default().resolve(root, config.rootFolder, 'shared/infrastructure/prisma/prisma.config.ts')).exists;
1448
+ const migrationCommand = withPrisma ? `npx ${prismaScripts(config.rootFolder)['prisma:migration:apply']}` : void 0;
1449
+ const folder = external_node_path_default().join(root, integrationFolder);
1450
+ testcontainers_stageFile(external_node_path_default().join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
1451
+ testcontainers_stageFile(external_node_path_default().join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
1452
+ testcontainers_stageFile(external_node_path_default().join(folder, 'setup-env.ts'), testcontainersSetupEnv);
1453
+ const example = new File(external_node_path_default().join(folder, 'database/database.spec.ts'));
1454
+ if (!example.exists) example.data = testcontainers_exampleSpec;
1455
+ const unitConfig = new File(external_node_path_default().join(root, 'vitest.config.ts'));
1456
+ let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
1457
+ if (!excludedFromUnitTests) {
1458
+ const excluded = excludeFromUnitTests(unitConfig.data);
1459
+ if (excluded) {
1460
+ unitConfig.update(excluded);
1461
+ excludedFromUnitTests = true;
1462
+ }
1463
+ }
1464
+ const missing = [
1465
+ 'vitest',
1466
+ 'testcontainers',
1467
+ 'dotenv'
1468
+ ].filter((name)=>!dependencies[name]);
1469
+ return [
1470
+ ...missing.length ? [
1471
+ `npm install --save-dev ${missing.join(' ')}`
1472
+ ] : [],
1473
+ `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.`,
1474
+ ...migrationCommand ? [] : [
1475
+ `Apply your migrations in ${integrationFolder}/global-setup.ts.`
1476
+ ],
1477
+ ...excludedFromUnitTests ? [] : [
1478
+ `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
1479
+ ],
1480
+ 'Docker must be running for integration specs.',
1481
+ ...describeScripts(selected, {
1482
+ 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
1483
+ })
1484
+ ];
1485
+ };
1314
1486
  const vitestScripts = {
1315
1487
  test: 'vitest run --reporter=dot --silent=passed-only',
1316
1488
  'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
@@ -1331,8 +1503,8 @@ export default defineConfig({
1331
1503
  tsconfigPaths: true
1332
1504
  },
1333
1505
  test: {
1334
- // Playwright runs end-to-end specs
1335
- exclude: [...configDefaults.exclude, 'specs/e2e/**'],
1506
+ // Playwright runs end-to-end specs, test:integration runs integration ones
1507
+ exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
1336
1508
  coverage: {
1337
1509
  provider: 'v8',
1338
1510
  include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared/**/*.ts')}],
@@ -1404,6 +1576,10 @@ const integrations = [
1404
1576
  name: 'Playwright',
1405
1577
  run: addPlaywright
1406
1578
  },
1579
+ {
1580
+ name: 'Integration tests (Testcontainers, PostgreSQL)',
1581
+ run: addTestcontainers
1582
+ },
1407
1583
  {
1408
1584
  name: 'OpenAPI',
1409
1585
  run: addOpenapi,
package/dist/index.js CHANGED
@@ -929,6 +929,178 @@ 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 excludeFromUnitTests = (content)=>{
1042
+ const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
1043
+ if (!exclude.test(content)) return;
1044
+ const entry = `'${integrationFolder}/**'`;
1045
+ return content.replace(exclude, (_, items, comma, whitespace)=>{
1046
+ const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
1047
+ const separator = void 0 === indent ? ', ' : `,\n${indent}`;
1048
+ return `${items}${separator}${entry}${comma}${whitespace}]`;
1049
+ }).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
1050
+ };
1051
+ const testcontainers_stageFile = (filePath, content)=>{
1052
+ const file = new File(filePath);
1053
+ if (!file.exists || file.data !== content) file.data = content;
1054
+ };
1055
+ const addTestcontainers = async ()=>{
1056
+ const config = ConfigFile.Instance.data;
1057
+ const root = new ProjectRoot().path;
1058
+ const manifestFile = new File(node_path.join(root, 'package.json'));
1059
+ const manifest = JSON.parse(manifestFile.data);
1060
+ const dependencies = {
1061
+ ...manifest.dependencies,
1062
+ ...manifest.devDependencies
1063
+ };
1064
+ const selected = await addPackageScripts(manifestFile, testcontainersScripts);
1065
+ const withPrisma = new File(node_path.resolve(root, config.rootFolder, 'shared/infrastructure/prisma/prisma.config.ts')).exists;
1066
+ const migrationCommand = withPrisma ? `npx ${prismaScripts(config.rootFolder)['prisma:migration:apply']}` : void 0;
1067
+ const folder = node_path.join(root, integrationFolder);
1068
+ testcontainers_stageFile(node_path.join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
1069
+ testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
1070
+ testcontainers_stageFile(node_path.join(folder, 'setup-env.ts'), testcontainersSetupEnv);
1071
+ const example = new File(node_path.join(folder, 'database/database.spec.ts'));
1072
+ if (!example.exists) example.data = testcontainers_exampleSpec;
1073
+ const unitConfig = new File(node_path.join(root, 'vitest.config.ts'));
1074
+ let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
1075
+ if (!excludedFromUnitTests) {
1076
+ const excluded = excludeFromUnitTests(unitConfig.data);
1077
+ if (excluded) {
1078
+ unitConfig.update(excluded);
1079
+ excludedFromUnitTests = true;
1080
+ }
1081
+ }
1082
+ const missing = [
1083
+ 'vitest',
1084
+ 'testcontainers',
1085
+ 'dotenv'
1086
+ ].filter((name)=>!dependencies[name]);
1087
+ return [
1088
+ ...missing.length ? [
1089
+ `npm install --save-dev ${missing.join(' ')}`
1090
+ ] : [],
1091
+ `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.`,
1092
+ ...migrationCommand ? [] : [
1093
+ `Apply your migrations in ${integrationFolder}/global-setup.ts.`
1094
+ ],
1095
+ ...excludedFromUnitTests ? [] : [
1096
+ `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
1097
+ ],
1098
+ 'Docker must be running for integration specs.',
1099
+ ...describeScripts(selected, {
1100
+ 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
1101
+ })
1102
+ ];
1103
+ };
932
1104
  const vitestScripts = {
933
1105
  test: 'vitest run --reporter=dot --silent=passed-only',
934
1106
  'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
@@ -949,8 +1121,8 @@ export default defineConfig({
949
1121
  tsconfigPaths: true
950
1122
  },
951
1123
  test: {
952
- // Playwright runs end-to-end specs
953
- exclude: [...configDefaults.exclude, 'specs/e2e/**'],
1124
+ // Playwright runs end-to-end specs, test:integration runs integration ones
1125
+ exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
954
1126
  coverage: {
955
1127
  provider: 'v8',
956
1128
  include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared/**/*.ts')}],
@@ -1022,6 +1194,10 @@ const integrations = [
1022
1194
  name: 'Playwright',
1023
1195
  run: addPlaywright
1024
1196
  },
1197
+ {
1198
+ name: 'Integration tests (Testcontainers, PostgreSQL)',
1199
+ run: addTestcontainers
1200
+ },
1025
1201
  {
1026
1202
  name: 'OpenAPI',
1027
1203
  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,13 @@
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
+ /**
8
+ * Adds the integration folder to `test.exclude` of the unit test config.
9
+ * The array is found by `...configDefaults.exclude`, which coverage
10
+ * excludes don't use. Returns `undefined` for configs of another shape.
11
+ */
12
+ export declare const excludeFromUnitTests: (content: string) => string | undefined;
13
+ 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.1",
4
+ "version": "5.1.1",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",