@domain-first/project-structure 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -164,6 +164,7 @@ const configSchema = zod.object({
164
164
  '@domain-first/handlers-rest'
165
165
  ])),
166
166
  defaultPersistenceLayerImplementation: zod.string(),
167
+ withInMemoryDb: zod.boolean().optional(),
167
168
  useReact: zod.boolean(),
168
169
  storybookFramework: zod.string().optional(),
169
170
  testingLibrary: zod.string().optional()
@@ -190,6 +191,27 @@ class ConfigFile {
190
191
  new File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
191
192
  };
192
193
  }
194
+ const printNextSteps = (nextSteps)=>{
195
+ const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
196
+ const commands = nextSteps.filter(isCommand);
197
+ const notes = nextSteps.filter((line)=>!isCommand(line));
198
+ const sections = [];
199
+ if (commands.length) sections.push([
200
+ 'Run these commands to install the required dependencies:',
201
+ ...commands.map((line)=>styleText([
202
+ 'bold',
203
+ 'cyan'
204
+ ], line))
205
+ ].join('\n'));
206
+ if (notes.length) sections.push([
207
+ 'Additional information:',
208
+ ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
209
+ 'bold',
210
+ 'cyan'
211
+ ], path)))
212
+ ].join('\n'));
213
+ if (sections.length) console.log(sections.join('\n\n'));
214
+ };
193
215
  const savePendingChanges = async ()=>{
194
216
  const overwrittenFiles = filesToOverwrite();
195
217
  if (overwrittenFiles.length) {
@@ -1132,27 +1154,7 @@ const addIntegration = async ()=>{
1132
1154
  }))
1133
1155
  });
1134
1156
  const nextSteps = await integration.run();
1135
- if (await savePendingChanges()) {
1136
- const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
1137
- const commands = nextSteps.filter(isCommand);
1138
- const notes = nextSteps.filter((line)=>!isCommand(line));
1139
- const sections = [];
1140
- if (commands.length) sections.push([
1141
- 'Run these commands to install the required dependencies:',
1142
- ...commands.map((line)=>styleText([
1143
- 'bold',
1144
- 'cyan'
1145
- ], line))
1146
- ].join('\n'));
1147
- if (notes.length) sections.push([
1148
- 'Additional information:',
1149
- ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
1150
- 'bold',
1151
- 'cyan'
1152
- ], path)))
1153
- ].join('\n'));
1154
- if (sections.length) console.log(sections.join('\n\n'));
1155
- }
1157
+ if (await savePendingChanges()) printNextSteps(nextSteps);
1156
1158
  };
1157
1159
  class UnknownFormatNaming {
1158
1160
  rawSource;
@@ -1457,6 +1459,15 @@ const addConstructorParameters = (source, className, parameters)=>{
1457
1459
  ...parameters
1458
1460
  ], indent) + source.slice(closeIndex);
1459
1461
  };
1462
+ const addClassMember = (source, className, member)=>{
1463
+ const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
1464
+ if (!classMatch) throw new Error(`Class ${className} not found`);
1465
+ const bodyStart = classMatch.index + classMatch[0].length;
1466
+ const bodyEnd = closingIndex(source, bodyStart - 1);
1467
+ const body = source.slice(bodyStart, bodyEnd).trimEnd();
1468
+ const separator = body.trim() ? '\n\n' : '\n';
1469
+ return `${source.slice(0, bodyStart)}${body}${separator} ${member}\n${source.slice(bodyEnd)}`;
1470
+ };
1460
1471
  const wireListRange = (source, className)=>{
1461
1472
  const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
1462
1473
  if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
@@ -1485,6 +1496,206 @@ const wireDependencies = (consumer, implementation, dependencies)=>{
1485
1496
  for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
1486
1497
  classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
1487
1498
  };
1499
+ const inMemoryImplementationType = 'in-memory';
1500
+ const in_memory_db_className = 'InMemoryDbInfrastructureService';
1501
+ const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
1502
+ const in_memory_db_parameterName = 'inMemoryDbInfrastructureService';
1503
+ const inMemoryDbService = `type Entry = {
1504
+ id: unknown;
1505
+ item: any;
1506
+ };
1507
+
1508
+ declare global {
1509
+ var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
1510
+ }
1511
+
1512
+ type Section<T, TId> = {
1513
+ all: (predicate?: (x: T) => boolean) => T[];
1514
+ first: (predicate: (x: T) => boolean) => T | null;
1515
+ withId: (id: TId) => T | null;
1516
+ lastAddedItem: () => T | null;
1517
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
1518
+ deleteById: (id: TId) => void;
1519
+ delete: (predicate: (x: T) => boolean) => void;
1520
+ };
1521
+
1522
+ type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
1523
+
1524
+ const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
1525
+
1526
+ const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
1527
+ if (typeof a !== 'object' || a === null) {
1528
+ return Object.is(a, b);
1529
+ }
1530
+
1531
+ for (const methodName of comparisonMethodNames) {
1532
+ const method: unknown = (a as Record<string, unknown>)[methodName];
1533
+ if (typeof method === 'function') {
1534
+ return Boolean(method.call(a, b));
1535
+ }
1536
+ }
1537
+
1538
+ return Object.is(a, b);
1539
+ };
1540
+
1541
+ const hasId = (x: unknown): x is { id: unknown } =>
1542
+ typeof x === 'object' && x !== null && 'id' in x;
1543
+
1544
+ export class InMemoryDbInfrastructureService {
1545
+ protected section<T extends { id: unknown }>(
1546
+ key: string,
1547
+ idsAreEqual?: IdsAreEqual<T['id']>
1548
+ ): Section<T, T['id']>;
1549
+ protected section<T, TId>(
1550
+ key: string,
1551
+ idsAreEqual?: IdsAreEqual<TId>
1552
+ ): Section<T, TId>;
1553
+ protected section<T, TId>(
1554
+ key: string,
1555
+ idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
1556
+ ): Section<T, TId> {
1557
+ if (!globalThis.___SHARED_IN_MEMORY_DB___) {
1558
+ globalThis.___SHARED_IN_MEMORY_DB___ = {};
1559
+ }
1560
+
1561
+ if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
1562
+ globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
1563
+ }
1564
+
1565
+ const items = (): T[] =>
1566
+ globalThis.___SHARED_IN_MEMORY_DB___![key].map(
1567
+ (entry) => entry.item
1568
+ );
1569
+
1570
+ return {
1571
+ all: (predicate: (x: T) => boolean = () => true): T[] =>
1572
+ items().filter(predicate),
1573
+ first: (predicate: (x: T) => boolean): T | null =>
1574
+ items().find(predicate) ?? null,
1575
+ withId: (id: TId): T | null =>
1576
+ items().find(
1577
+ (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
1578
+ ) ?? null,
1579
+ lastAddedItem: (): T | null =>
1580
+ globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
1581
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => {
1582
+ const id = Array.isArray(payload) ? payload[0] : payload.id;
1583
+ const item = Array.isArray(payload) ? payload[1] : payload;
1584
+ const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
1585
+ const existing = entries.find((entry) =>
1586
+ idsAreEqual(entry.id as TId, id)
1587
+ );
1588
+ if (existing) {
1589
+ existing.item = item;
1590
+ return;
1591
+ }
1592
+ entries.push({ id, item });
1593
+ },
1594
+ deleteById: (id: TId) => {
1595
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
1596
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
1597
+ (entry) => !idsAreEqual(entry.id as TId, id)
1598
+ );
1599
+ },
1600
+ delete: (predicate: (x: T) => boolean) => {
1601
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
1602
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
1603
+ (entry) => !predicate(entry.item)
1604
+ );
1605
+ }
1606
+ };
1607
+ }
1608
+ }
1609
+ `;
1610
+ const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
1611
+ import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
1612
+
1613
+ export const wireInMemoryDbInfrastructureService = wireClass(
1614
+ InMemoryDbInfrastructureService,
1615
+ []
1616
+ );
1617
+ `;
1618
+ const inMemoryDbSpec = (testingLibrary, withWiring)=>`
1619
+ import { describe, test, expect, beforeEach } from '${testingLibrary}'
1620
+ ${withWiring ? `import { type InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'
1621
+ import { wireInMemoryDbInfrastructureService } from '../../wiring/infrastructure-services/wire-in-memory-db-infrastructure-service'` : "import { InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'"}
1622
+
1623
+ let inMemoryDbInfrastructureService: InMemoryDbInfrastructureService
1624
+
1625
+ beforeEach(() => {
1626
+ inMemoryDbInfrastructureService = ${withWiring ? 'wireInMemoryDbInfrastructureService()' : 'new InMemoryDbInfrastructureService()'}
1627
+ })
1628
+
1629
+ describe('in memory db', () => {
1630
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
1631
+ expect(inMemoryDbInfrastructureService).toBeDefined()
1632
+ })
1633
+ })
1634
+ `.trim();
1635
+ const in_memory_db_withWiring = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1636
+ const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
1637
+ ConfigFile.Instance.data.rootFolder,
1638
+ 'shared'
1639
+ ]);
1640
+ const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
1641
+ 'infrastructure',
1642
+ 'services',
1643
+ 'in-memory-db-infrastructure-service.ts'
1644
+ ]);
1645
+ const in_memory_db_wireFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
1646
+ 'wiring',
1647
+ 'infrastructure-services',
1648
+ 'wire-in-memory-db-infrastructure-service.ts'
1649
+ ]);
1650
+ const scaffoldInMemoryDb = (shared)=>{
1651
+ const { testingLibrary } = ConfigFile.Instance.data;
1652
+ const servicesFolder = shared.subitem([
1653
+ 'infrastructure',
1654
+ 'services'
1655
+ ]);
1656
+ servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
1657
+ if (testingLibrary) servicesFolder.createFile('in-memory-db-infrastructure-service.spec.ts', inMemoryDbSpec(testingLibrary, in_memory_db_withWiring()));
1658
+ if (in_memory_db_withWiring()) shared.subitem([
1659
+ 'wiring',
1660
+ 'infrastructure-services'
1661
+ ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
1662
+ };
1663
+ const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
1664
+ const plural = (word)=>{
1665
+ if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
1666
+ if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
1667
+ return `${word}s`;
1668
+ };
1669
+ const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
1670
+ const file = serviceFile();
1671
+ const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
1672
+ const field = sectionNaming.variableName;
1673
+ if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
1674
+ const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
1675
+ file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
1676
+ return field;
1677
+ };
1678
+ const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
1679
+ const inMemoryDbSectionMembers = (field, derived)=>`
1680
+ private readonly data: ${in_memory_db_className}['${field}']
1681
+
1682
+ constructor(${in_memory_db_parameterName}: ${in_memory_db_className}) {
1683
+ ${derived ? 'super()\n ' : ''}this.data = ${in_memory_db_parameterName}.${field}
1684
+ }
1685
+ `.trim();
1686
+ const injectInMemoryDb = (classFile, implementationName)=>{
1687
+ classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
1688
+ `private readonly ${in_memory_db_parameterName}: ${in_memory_db_className}`
1689
+ ]));
1690
+ };
1691
+ const wireInMemoryDb = (consumerWireFile, implementationName)=>{
1692
+ consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${in_memory_db_wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
1693
+ in_memory_db_wireName
1694
+ ]));
1695
+ };
1696
+ const passInMemoryDb = (specFile, implementationName)=>{
1697
+ 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}())`));
1698
+ };
1488
1699
  const kindTitles = {
1489
1700
  repositories: 'Repositories',
1490
1701
  'domain-services': 'Domain services',
@@ -1655,44 +1866,44 @@ const scaffoldNewPresentationService = async (boundedContextFolder)=>{
1655
1866
  if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
1656
1867
  };
1657
1868
  const rest_endpoint_generator_name = 'rest-endpoint-generator';
1658
- const scaffoldRestEndpointGenerator = (sharedFolder)=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>`
1869
+ const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false } = {})=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>{
1870
+ const adapter = withNextAdapter ? 'nextAdapter' : 'adapter';
1871
+ return `
1659
1872
  import {
1660
- type Adapter,
1661
- type EndpointGenerator,
1873
+ ${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
1662
1874
  type ErrorStatuses,
1663
1875
  createEndpoint,
1664
1876
  InputMappingError,
1665
1877
  RequestParsingError
1666
1878
  } from '@domain-first/handlers-rest'
1879
+ ${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
1880
+ /**
1881
+ * The adapter of your HTTP framework.
1882
+ */
1883
+ const adapter = undefined as unknown as Adapter<any[], any>`}
1667
1884
 
1668
1885
  export class ${className} {
1886
+ /**
1887
+ * Default errors of a client request, to spread into a generator's
1888
+ * own checks.
1889
+ */
1890
+ private get defaultClientRequestErrors(): ErrorStatuses[number]['checks'] {
1891
+ return [RequestParsingError.is, InputMappingError.is]
1892
+ }
1893
+
1669
1894
  get withoutGuards(): EndpointGenerator {
1670
1895
  return createEndpoint({
1671
1896
  errorStatuses: {
1672
1897
  400: {
1673
- checks: this.invalidRequestChecks,
1898
+ checks: this.defaultClientRequestErrors,
1674
1899
  description: 'Invalid request'
1675
1900
  }
1676
1901
  }
1677
- })(this.adapter) as EndpointGenerator
1678
- }
1679
-
1680
- /**
1681
- * Default checks of an invalid request, to spread into a generator's
1682
- * own checks.
1683
- */
1684
- private get invalidRequestChecks(): ErrorStatuses[number]['checks'] {
1685
- return [RequestParsingError.is, InputMappingError.is]
1686
- }
1687
-
1688
- /**
1689
- * The adapter of your HTTP framework.
1690
- */
1691
- private get adapter(): Adapter<any[], any> {
1692
- throw new Error('REST adapter is not set')
1902
+ })(${adapter}) as EndpointGenerator
1693
1903
  }
1694
1904
  }
1695
- `.trim());
1905
+ `.trim();
1906
+ });
1696
1907
  const findRestEndpointGenerator = (sharedFolder)=>{
1697
1908
  const typeFile = node_path.join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
1698
1909
  if (!new File(typeFile).exists) return;
@@ -1703,7 +1914,18 @@ const findRestEndpointGenerator = (sharedFolder)=>{
1703
1914
  wireFile: node_path.join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
1704
1915
  };
1705
1916
  };
1917
+ const hasDependency = (root, name)=>{
1918
+ const manifestFile = new File(node_path.join(root, 'package.json'));
1919
+ if (!manifestFile.exists) return false;
1920
+ const manifest = JSON.parse(manifestFile.data);
1921
+ return [
1922
+ manifest.dependencies,
1923
+ manifest.devDependencies,
1924
+ manifest.optionalDependencies
1925
+ ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
1926
+ };
1706
1927
  const initializeUseCase = async ()=>{
1928
+ const nextSteps = [];
1707
1929
  const rootFolderName = await input({
1708
1930
  message: 'Root folder (use "/" for inner folders):',
1709
1931
  default: 'src'
@@ -1718,9 +1940,15 @@ const initializeUseCase = async ()=>{
1718
1940
  '@domain-first/handlers-rest'
1719
1941
  ]
1720
1942
  });
1943
+ const withNextAdapter = domainFirstPackages.includes('@domain-first/handlers-rest') && hasDependency(new ProjectRoot().path, 'next') && await prompts_confirm({
1944
+ message: 'Use Next adapter for REST endpoints'
1945
+ });
1721
1946
  const defaultPersistenceLayerImplementation = await input({
1722
1947
  message: 'Default persistence layer implementation:'
1723
1948
  });
1949
+ const withInMemoryDb = await prompts_confirm({
1950
+ message: 'Scaffold in-memory DB for test implementations'
1951
+ });
1724
1952
  const useReact = await prompts_confirm({
1725
1953
  message: 'Use React'
1726
1954
  });
@@ -1744,6 +1972,7 @@ const initializeUseCase = async ()=>{
1744
1972
  rootFolder: rootFolderName,
1745
1973
  domainFirstPackages,
1746
1974
  defaultPersistenceLayerImplementation,
1975
+ withInMemoryDb,
1747
1976
  useReact,
1748
1977
  storybookFramework,
1749
1978
  testingLibrary
@@ -1761,6 +1990,10 @@ export const envBranchedWire = branchedWire(() => {
1761
1990
  return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1762
1991
  });
1763
1992
  `.trim());
1993
+ if (withInMemoryDb) scaffoldInMemoryDb(rootFolder.subitem([
1994
+ rootFolderName,
1995
+ 'shared'
1996
+ ]));
1764
1997
  if (domainFirstPackages.includes('@domain-first/errors')) rootFolder.subitem([
1765
1998
  rootFolderName,
1766
1999
  'shared'
@@ -1772,10 +2005,16 @@ import { errorNamespace } from '@domain-first/errors'
1772
2005
 
1773
2006
  export const SharedErrors = errorNamespace('shared')
1774
2007
  `.trim());
1775
- if (domainFirstPackages.includes('@domain-first/handlers-rest')) scaffoldRestEndpointGenerator(rootFolder.subitem([
1776
- rootFolderName,
1777
- 'shared'
1778
- ]));
2008
+ if (domainFirstPackages.includes('@domain-first/handlers-rest')) {
2009
+ scaffoldRestEndpointGenerator(rootFolder.subitem([
2010
+ rootFolderName,
2011
+ 'shared'
2012
+ ]), {
2013
+ withNextAdapter
2014
+ });
2015
+ if (withNextAdapter && !hasDependency(path, '@domain-first/handlers-next')) nextSteps.push('npm i @domain-first/handlers-next');
2016
+ }
2017
+ return nextSteps;
1779
2018
  };
1780
2019
  const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1781
2020
  class NestedName {
@@ -2103,9 +2342,25 @@ describe('${aggregateNaming.withSpaces}', () => {
2103
2342
  ].filter((x)=>!!x);
2104
2343
  for (const implementation of implementationTypes){
2105
2344
  const naming = new UnknownFormatNaming(implementation);
2106
- infrastructureRepositoriesFolder.subitem([
2345
+ const repositoryFolder = infrastructureRepositoriesFolder.subitem([
2107
2346
  naming.fileName
2108
- ]).createFile(`${naming.fileName}-${aggregateName}-repository.ts`, `
2347
+ ]);
2348
+ const repositoryFileName = `${naming.fileName}-${aggregateName}-repository.ts`;
2349
+ if (usesInMemoryDb(implementation)) {
2350
+ const section = addInMemoryDbSection(aggregateNaming, aggregatesFolder.path);
2351
+ repositoryFolder.createFile(repositoryFileName, `
2352
+ ${inMemoryDbTypeImport(repositoryFolder.subitem([
2353
+ repositoryFileName
2354
+ ]).path)}
2355
+ import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2356
+
2357
+ export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
2358
+ ${inMemoryDbSectionMembers(section, false)}
2359
+ }
2360
+ `.trim());
2361
+ continue;
2362
+ }
2363
+ repositoryFolder.createFile(repositoryFileName, `
2109
2364
  import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2110
2365
 
2111
2366
  export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
@@ -2116,7 +2371,7 @@ export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implement
2116
2371
  }
2117
2372
  if (scaffoldUnitTests) {
2118
2373
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
2119
- aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
2374
+ const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
2120
2375
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2121
2376
  ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `import { wire${aggregateNaming.ClassName}Repository } from '../../../wiring/repositories/wire-${aggregateNaming.fileName}-repository'
2122
2377
  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'
@@ -2135,6 +2390,7 @@ describe('${aggregateNaming.withSpaces} repository', () => {
2135
2390
  })
2136
2391
  })
2137
2392
  `.trim());
2393
+ if (!ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') && usesInMemoryDb(infrastructureImplementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`);
2138
2394
  }
2139
2395
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2140
2396
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
@@ -2155,6 +2411,7 @@ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
2155
2411
  production: wire${implementationNaming.ClassName}Implementation
2156
2412
  })
2157
2413
  `.trim());
2414
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${aggregateNaming.ClassName}Repository`);
2158
2415
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2159
2416
  }
2160
2417
  }
@@ -2371,7 +2628,7 @@ const scaffoldNewCommand = async (boundedContextFolder)=>{
2371
2628
  ].filter((x)=>!!x);
2372
2629
  for (const implementation of implementationTypes){
2373
2630
  const formatNaming = new UnknownFormatNaming(implementation);
2374
- infrastructureFolder.subitem([
2631
+ const implementationFile = infrastructureFolder.subitem([
2375
2632
  formatNaming.fileName
2376
2633
  ]).createFile(`${formatNaming.fileName}-${naming.fileName}-command.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2377
2634
  import { defineHandler } from '@domain-first/handlers'
@@ -2399,6 +2656,7 @@ export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${namin
2399
2656
  }
2400
2657
  }
2401
2658
  `.trim());
2659
+ if (usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Command`);
2402
2660
  }
2403
2661
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) commandsFolder.subitem([
2404
2662
  'execution'
@@ -2420,7 +2678,7 @@ export abstract class ${naming.ClassName}Command {
2420
2678
  }`.trim());
2421
2679
  if (scaffoldUnitTests) {
2422
2680
  const implementationNaming = new UnknownFormatNaming(implementationType);
2423
- commandsFolder.subitem([
2681
+ const specFile = commandsFolder.subitem([
2424
2682
  'execution'
2425
2683
  ]).createFile(`${naming.fileName}-command.spec.ts`, `
2426
2684
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
@@ -2441,6 +2699,7 @@ describe('${naming.withSpaces} command', () => {
2441
2699
  })
2442
2700
  })
2443
2701
  `.trim());
2702
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Command`);
2444
2703
  }
2445
2704
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2446
2705
  const implementationNaming = new UnknownFormatNaming(implementationType);
@@ -2461,6 +2720,7 @@ export const wire${naming.ClassName}Command = envBranchedWire({
2461
2720
  production: wire${implementationNaming.ClassName}Implementation
2462
2721
  })
2463
2722
  `.trim());
2723
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${naming.ClassName}Command`);
2464
2724
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2465
2725
  }
2466
2726
  return;
@@ -2881,7 +3141,7 @@ const scaffoldNewQuery = async (boundedContextFolder)=>{
2881
3141
  ].filter((x)=>!!x);
2882
3142
  for (const implementation of implementationTypes){
2883
3143
  const formatNaming = new UnknownFormatNaming(implementation);
2884
- infrastructureFolder.subitem([
3144
+ const implementationFile = infrastructureFolder.subitem([
2885
3145
  formatNaming.fileName
2886
3146
  ]).createFile(`${formatNaming.fileName}-${naming.fileName}-query.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2887
3147
  import { defineHandler } from '@domain-first/handlers'
@@ -2909,6 +3169,7 @@ export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.
2909
3169
  }
2910
3170
  }
2911
3171
  `.trim());
3172
+ if (usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Query`);
2912
3173
  }
2913
3174
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) queriesFolder.subitem([
2914
3175
  'execution'
@@ -2930,7 +3191,7 @@ export abstract class ${naming.ClassName}Query {
2930
3191
  }`.trim());
2931
3192
  if (scaffoldUnitTests) {
2932
3193
  const implementationNaming = new UnknownFormatNaming(implementationType);
2933
- queriesFolder.subitem([
3194
+ const specFile = queriesFolder.subitem([
2934
3195
  'execution'
2935
3196
  ]).createFile(`${naming.fileName}-query.spec.ts`, `
2936
3197
  import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
@@ -2951,6 +3212,7 @@ describe('${naming.withSpaces} query', () => {
2951
3212
  })
2952
3213
  })
2953
3214
  `.trim());
3215
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Query`);
2954
3216
  }
2955
3217
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2956
3218
  const implementationNaming = new UnknownFormatNaming(implementationType);
@@ -2971,6 +3233,7 @@ export const wire${naming.ClassName}Query = envBranchedWire({
2971
3233
  production: wire${implementationNaming.ClassName}Implementation
2972
3234
  })
2973
3235
  `.trim());
3236
+ for (const implementation of implementationTypes.filter(usesInMemoryDb))wireInMemoryDb(wireFile, `${new UnknownFormatNaming(implementation).ClassName}${naming.ClassName}Query`);
2974
3237
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2975
3238
  }
2976
3239
  return;
@@ -3307,7 +3570,11 @@ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps
3307
3570
  }
3308
3571
  };
3309
3572
  const main = async ()=>{
3310
- if (!ConfigFile.exists) return void await initializeUseCase();
3573
+ if (!ConfigFile.exists) {
3574
+ const nextSteps = await initializeUseCase();
3575
+ if (await savePendingChanges()) printNextSteps(nextSteps);
3576
+ return;
3577
+ }
3311
3578
  const rootPath = new ProjectRoot().path;
3312
3579
  const currentBoundedContextOptions = new Folder(rootPath).subitem([
3313
3580
  ConfigFile.Instance.data.rootFolder,
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Prints the steps left after a use case: installation commands first,
3
+ * then additional information.
4
+ */
5
+ export declare const printNextSteps: (nextSteps: string[]) => void;
@@ -1 +1,4 @@
1
- export declare const initializeUseCase: () => Promise<void>;
1
+ /**
2
+ * Initializes the project and returns the steps left to the user.
3
+ */
4
+ export declare const initializeUseCase: () => Promise<string[]>;
@@ -2,9 +2,12 @@ import { File, type Folder } from '../file-system';
2
2
  /**
3
3
  * The one endpoint generator of the project: a Shared Layer presentation
4
4
  * service, scaffolded like any other. Every generating method is a getter
5
- * typed as `EndpointGenerator`.
5
+ * typed as `EndpointGenerator`. With `withNextAdapter`, the adapter is
6
+ * `nextAdapter` of `@domain-first/handlers-next` instead of a placeholder.
6
7
  */
7
- export declare const scaffoldRestEndpointGenerator: (sharedFolder: Folder) => File | undefined;
8
+ export declare const scaffoldRestEndpointGenerator: (sharedFolder: Folder, { withNextAdapter }?: {
9
+ withNextAdapter?: boolean;
10
+ }) => File | undefined;
8
11
  /**
9
12
  * The generator's type and factory, or undefined in projects initialized
10
13
  * without it.
@@ -0,0 +1 @@
1
+ export {};
package/dist/wiring.d.ts CHANGED
@@ -73,6 +73,10 @@ export declare const addImport: (source: string, importLine: string) => string;
73
73
  * Appends parameters to the class constructor, adding one if missing.
74
74
  */
75
75
  export declare const addConstructorParameters: (source: string, className: string, parameters: string[]) => string;
76
+ /**
77
+ * Appends a member at the end of the class body.
78
+ */
79
+ export declare const addClassMember: (source: string, className: string, member: string) => string;
76
80
  export declare const wiredDependencyNames: (source: string, className: string) => string[];
77
81
  /**
78
82
  * Appends wires to the dependency list of `wireClass(className, [...])`,
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": "3.0.0",
4
+ "version": "3.2.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -77,7 +77,7 @@ export const wirePlaceOrderUseCase = wireClass(PlaceOrderUseCase, [wireOrderRepo
77
77
 
78
78
  ## REST endpoints ({handlers-rest})
79
79
 
80
- 1. Generator: initialization creates `RestEndpointGeneratorPresentationService` in `<rootFolder>/shared/presentation/services/`; every endpoint uses it. Replace its private `adapter` getter with the HTTP framework's adapter. The default `400` checks live in the private `invalidRequestChecks` getter; extend a status with `checks: [...this.invalidRequestChecks, MyError.is]`. Map domain errors to statuses in the generator's `errorStatuses`, importing them from the contexts' `domain/errors` (the only thing `shared/` may import from a context). A new kind of endpoint (auth, other context) is a new getter returning `createEndpoint({ context, errorStatuses })(this.adapter) as EndpointGenerator`, next to `withoutGuards`. Generate the exposed handler before the endpoint: with wire, the `Handler:` pick fills its type and the wire (`[wireRestEndpointGeneratorPresentationService, wireGetRecentOrdersUseCase]`).
80
+ 1. Generator: initialization creates `RestEndpointGeneratorPresentationService` in `<rootFolder>/shared/presentation/services/`; every endpoint uses it. Set the module-level `const adapter` above the class (`undefined` until set) to the HTTP framework's adapter; the class reads it through closure. If initialization connected the Next adapter, the file already imports `nextAdapter` from `@domain-first/handlers-next` and passes it instead; just make sure that package is installed. The default `400` checks live in the private `defaultClientRequestErrors` getter; extend a status with `checks: [...this.defaultClientRequestErrors, MyError.is]`. Map domain errors to statuses in the generator's `errorStatuses`, importing them from the contexts' `domain/errors` (the only thing `shared/` may import from a context). A new kind of endpoint (auth, other context) is a new getter returning `createEndpoint({ context, errorStatuses })(adapter) as EndpointGenerator` (`nextAdapter` with the Next adapter), next to `withoutGuards`. Generate the exposed handler before the endpoint: with wire, the `Handler:` pick fills its type and the wire (`[wireRestEndpointGeneratorPresentationService, wireGetRecentOrdersUseCase]`).
81
81
  2. If `handler: never` is left (no handler existed at generation), re-run the endpoint generator as an approved overwrite to pick it (rule 3); don't replace it by hand.
82
82
  3. Complete `get handle()`: the generated `this.endpointGenerator(...)` doesn't compile on purpose. Pick the generating getter that fits the endpoint (`this.endpointGenerator.withoutGuards(...)`, or one with the needed guards), then `.input(...)`, `.mapInput(...)`, optional `.output(...)`, `.mapOutput(...)`.
83
83
  4. Register `restHandlers` from `<rootFolder>/presentation/rest/index.ts` in the server bootstrap (rule 2, exception 5).
@@ -21,6 +21,7 @@ Prompts: name → `With Repository` → if yes: implementation (default = config
21
21
  - `<C>/domain/aggregates/n/`: `n.aggregate-root.ts` (`class N extends domainType()` {types}), `index.ts`, spec; with repository: `n-repository.ts` (`abstract class NRepository`), spec
22
22
  - `<C>/infrastructure/repositories/I/I-n-repository.ts` per implementation (`class INRepository implements NRepository`)
23
23
  - {wire} `<C>/wiring/repositories/wire-n-repository.ts` (env-branched)
24
+ - With `withInMemoryDb` in the config, the `in-memory` implementation is not empty: `private readonly data: InMemoryDbInfrastructureService['ns']`, set in the constructor from its `inMemoryDbInfrastructureService` parameter; `ns = this.section<N>('NS');` is added to `<rootFolder>/shared/infrastructure/services/in-memory-db-infrastructure-service.ts` if missing (`N` needs an `id`), and {wire} its `wireClass` already has `wireInMemoryDbInfrastructureService`, so `Dependencies for InMemoryNRepository:` doesn't list it.
24
25
 
25
26
  ## Domain → New Entity / New Value Object (context and Shared Layer)
26
27
 
@@ -77,6 +78,7 @@ Execution:
77
78
  - `<C>/application/commands/execution/n-command.ts`: abstract `NCommand` ({handlers} schemas + abstract `handle: Handler<…>`), spec
78
79
  - `<C>/infrastructure/commands/I/I-n-command.ts` per implementation (`extends NCommand`, implements `handle`)
79
80
  - {wire} `<C>/wiring/commands/wire-n-command.ts` (env-branched)
81
+ - With `withInMemoryDb` in the config, the `in-memory` implementation gets the whole DB: `constructor(private readonly inMemoryDbInfrastructureService: InMemoryDbInfrastructureService)`, {wire} already in its `wireClass`. No section is added.
80
82
 
81
83
  Orchestrator: `<C>/application/commands/orchestration/n-command.ts` (concrete class), spec, {wire} `wire-n-command.ts`.
82
84