@domain-first/project-structure 5.1.2 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/287.js ADDED
@@ -0,0 +1,3217 @@
1
+ import { styleText } from "node:util";
2
+ import node_path from "node:path";
3
+ import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, select as prompts_select } from "@inquirer/prompts";
4
+ import node_fs from "node:fs";
5
+ import { addImport, availableDependencies, discardPendingChanges, findWiredModules, UnknownFormatNaming, Folder, writePendingChanges, stripJsonComments, readWiredModule, addClassMember, addWireDependencies, addConstructorParameters, filesToOverwrite, ConfigFile, relativeImport, wireDependencies, File, ProjectRoot, implementationType as wiring_implementationType, compilerOption, isSuggestedFor } from "./201.js";
6
+ const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
7
+ const mergeInstallCommands = (commands)=>{
8
+ const runtime = new Set();
9
+ const development = new Set();
10
+ const rest = [];
11
+ for (const command of commands){
12
+ const match = installCommand.exec(command);
13
+ if (!match) {
14
+ rest.push(command);
15
+ continue;
16
+ }
17
+ for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
18
+ }
19
+ const devOnly = [
20
+ ...development
21
+ ].filter((name)=>!runtime.has(name));
22
+ return [
23
+ ...runtime.size ? [
24
+ `npm install ${[
25
+ ...runtime
26
+ ].join(' ')}`
27
+ ] : [],
28
+ ...devOnly.length ? [
29
+ `npm install --save-dev ${devOnly.join(' ')}`
30
+ ] : [],
31
+ ...rest
32
+ ];
33
+ };
34
+ const printNextSteps = (nextSteps)=>{
35
+ const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
36
+ const commands = mergeInstallCommands(nextSteps.filter(isCommand));
37
+ const notes = nextSteps.filter((line)=>!isCommand(line));
38
+ const sections = [];
39
+ if (commands.length) sections.push([
40
+ 'Run these commands to install the required dependencies:',
41
+ ...commands.map((line)=>styleText([
42
+ 'bold',
43
+ 'cyan'
44
+ ], line))
45
+ ].join('\n'));
46
+ if (notes.length) sections.push([
47
+ 'Additional information:',
48
+ ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
49
+ 'bold',
50
+ 'cyan'
51
+ ], path)))
52
+ ].join('\n'));
53
+ if (sections.length) console.log(sections.join('\n\n'));
54
+ };
55
+ const savePendingChanges = async ()=>{
56
+ const overwrittenFiles = filesToOverwrite();
57
+ if (overwrittenFiles.length) {
58
+ const root = new ProjectRoot().path;
59
+ console.log('These files already exist and will be overwritten:');
60
+ for (const filePath of overwrittenFiles)console.log(` ${node_path.relative(root, filePath)}`);
61
+ const overwrite = await prompts_confirm({
62
+ message: 'Overwrite them?',
63
+ default: false
64
+ });
65
+ if (!overwrite) {
66
+ discardPendingChanges();
67
+ console.log('Cancelled: nothing was written.');
68
+ return false;
69
+ }
70
+ }
71
+ writePendingChanges();
72
+ return true;
73
+ };
74
+ const missingDomainFirstPackages = ()=>{
75
+ const packages = ConfigFile.Instance.data.domainFirstPackages;
76
+ const manifest = JSON.parse(new File(node_path.join(new ProjectRoot().path, 'package.json')).data);
77
+ const dependencies = {
78
+ ...manifest.dependencies,
79
+ ...manifest.devDependencies,
80
+ ...manifest.optionalDependencies
81
+ };
82
+ const missing = [
83
+ ...new Set(packages)
84
+ ].filter((name)=>!Object.hasOwn(dependencies, name));
85
+ return missing.length ? [
86
+ `npm i ${missing.join(' ')}`
87
+ ] : [];
88
+ };
89
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
90
+ class NestedName {
91
+ folders;
92
+ folderName;
93
+ fileName;
94
+ ClassName;
95
+ classNameSegments;
96
+ constructor(rawSource){
97
+ const segments = splitSegments(rawSource);
98
+ this.folders = segments.slice(0, -1);
99
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
100
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
101
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
102
+ this.ClassName = this.classNameSegments.join('');
103
+ }
104
+ static validate = (rawSource)=>{
105
+ const segments = splitSegments(rawSource);
106
+ if (!segments.length) return 'Name is required';
107
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
108
+ return true;
109
+ };
110
+ }
111
+ const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
112
+ ${[
113
+ ...imports,
114
+ "import { type FC } from 'react'"
115
+ ].join('\n')}
116
+
117
+ export type ${ClassName}PageProps = {}
118
+
119
+ export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
120
+ return ${body}
121
+ }
122
+ `.trim();
123
+ const scaffoldReactPage = async (presentationReactFolder)=>{
124
+ const name = await input({
125
+ message: 'Provide name (folders split by "/"):',
126
+ validate: NestedName.validate
127
+ });
128
+ const { folders, ClassName, fileName } = new NestedName(name);
129
+ presentationReactFolder.subitem([
130
+ 'pages',
131
+ ...folders
132
+ ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
133
+ };
134
+ const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
135
+ const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
136
+ const openapiExtractor = (rootFolder)=>`import path from 'node:path';
137
+ import {
138
+ type DocNode,
139
+ DocPlainText,
140
+ TSDocConfiguration,
141
+ TSDocParser,
142
+ TSDocTagDefinition,
143
+ TSDocTagSyntaxKind
144
+ } from '@microsoft/tsdoc';
145
+ import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
146
+
147
+ type BlockTag = \`@\${string}\`;
148
+
149
+ type OpenApiDataTags = {
150
+ /** Omit to take the summary from the comment text before the first tag. */
151
+ summary?: BlockTag;
152
+ description?: BlockTag;
153
+ };
154
+
155
+ type OpenApiData = Partial<{
156
+ summary: string;
157
+ description: string;
158
+ operationId: string;
159
+ }>;
160
+
161
+ const project = new Project({
162
+ tsConfigFilePath: 'tsconfig.json'
163
+ });
164
+
165
+ const getText = (node: DocNode): string =>
166
+ node
167
+ .getChildNodes()
168
+ .map((child) => {
169
+ if (child instanceof DocPlainText) {
170
+ return child.text;
171
+ }
172
+
173
+ return getText(child);
174
+ })
175
+ .join('');
176
+
177
+ const getRawCommentText = (comment: string): string =>
178
+ comment
179
+ .replace(/^\\/\\*\\*/, '')
180
+ .replace(/\\*\\/$/, '')
181
+ .split(/\\r?\\n/)
182
+ .map((line) => line.replace(/^\\s*\\*\\s?/, ''))
183
+ .join('\\n');
184
+
185
+ // TSDoc treats an unknown tag as summary content, so every block tag of the
186
+ // comment has to be registered for the summary section to end before it.
187
+ const parseSummary = (comment: string): string | undefined => {
188
+ const configuration = new TSDocConfiguration();
189
+ const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
190
+
191
+ for (const [, tagName] of tagNames) {
192
+ if (!configuration.tryGetTagDefinition(tagName)) {
193
+ configuration.addTagDefinition(
194
+ new TSDocTagDefinition({
195
+ tagName,
196
+ syntaxKind: TSDocTagSyntaxKind.BlockTag
197
+ })
198
+ );
199
+ }
200
+ }
201
+
202
+ const { docComment } = new TSDocParser(configuration).parseString(comment);
203
+
204
+ return getText(docComment.summarySection).trim() || undefined;
205
+ };
206
+
207
+ // Parsed by hand rather than through TSDoc, which drops the line breaks.
208
+ const getTagText = (comment: string, tag: BlockTag): string | undefined => {
209
+ const tagMatch = getRawCommentText(comment).match(
210
+ new RegExp(
211
+ \`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
212
+ )
213
+ );
214
+
215
+ return tagMatch?.[1].trim() || undefined;
216
+ };
217
+
218
+ // Endpoints pass their logic as the generator's first argument
219
+ // (\`this.endpointGenerator(this.handler.handle, ...)\`), while other injected
220
+ // queries only serve as helpers, e.g. guest checks.
221
+ const findHandlerClass = (endpointFile: SourceFile) =>
222
+ endpointFile
223
+ .getDescendantsOfKind(SyntaxKind.CallExpression)
224
+ .map((call) => call.getArguments()[0])
225
+ .filter(Node.isPropertyAccessExpression)
226
+ .find((argument) => argument.getName() === 'handle')
227
+ ?.getExpression()
228
+ .getType()
229
+ .getSymbol()
230
+ ?.getDeclarations()
231
+ .find(Node.isClassDeclaration);
232
+
233
+ // Path parameters (\`:id\`) can't be part of file and folder names
234
+ // everywhere (Windows), so endpoints name them \`_id_\` there.
235
+ const pathParameterAsName = (segment: string) =>
236
+ segment.startsWith(':') ? \`_\${segment.slice(1)}_\` : segment;
237
+
238
+ export const createOpenApiDataFromEndpointLogicExtractor = ({
239
+ summary: summaryTag,
240
+ description: descriptionTag = '@description'
241
+ }: OpenApiDataTags = {}) => {
242
+ return (routeMetadata: {
243
+ method: string;
244
+ path: readonly string[];
245
+ }): OpenApiData | undefined => {
246
+ try {
247
+ const [currentBoundedContext, controller, ...relativePath] =
248
+ routeMetadata.path;
249
+
250
+ if (!currentBoundedContext || !controller) {
251
+ return undefined;
252
+ }
253
+
254
+ const endpointFile = project.getSourceFile(
255
+ path.join(
256
+ ${rootFolderSegments(rootFolder)}'bounded-contexts',
257
+ currentBoundedContext,
258
+ 'presentation',
259
+ 'rest',
260
+ controller,
261
+ ...relativePath.map(pathParameterAsName),
262
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
263
+ )
264
+ );
265
+
266
+ if (!endpointFile) {
267
+ return undefined;
268
+ }
269
+
270
+ const declaration = findHandlerClass(endpointFile);
271
+ const operationId = declaration?.getName();
272
+ const comment = declaration?.getJsDocs().at(-1)?.getText();
273
+
274
+ if (!comment) {
275
+ return { operationId };
276
+ }
277
+
278
+ return {
279
+ summary: summaryTag
280
+ ? getTagText(comment, summaryTag)
281
+ : parseSummary(comment),
282
+ description: getTagText(comment, descriptionTag),
283
+ operationId
284
+ };
285
+ } catch (e: unknown) {
286
+ console.error(e);
287
+ return undefined;
288
+ }
289
+ };
290
+ };
291
+ `;
292
+ const addPackageScripts = async (file, additions)=>{
293
+ const original = file.data;
294
+ const manifest = JSON.parse(original);
295
+ const scripts = {
296
+ ...manifest.scripts
297
+ };
298
+ const selected = {};
299
+ for (const [name, command] of Object.entries(additions)){
300
+ let target = name;
301
+ if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
302
+ const action = await prompts_select({
303
+ message: `Script "${name}" already exists: ${scripts[name]}`,
304
+ choices: [
305
+ 'Keep existing',
306
+ 'Replace',
307
+ 'Use another name'
308
+ ]
309
+ });
310
+ if ('Keep existing' === action) continue;
311
+ if ('Use another name' === action) target = await input({
312
+ message: "New script name:",
313
+ validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
314
+ });
315
+ }
316
+ scripts[target] = command;
317
+ selected[name] = target;
318
+ }
319
+ if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
320
+ manifest.scripts = scripts;
321
+ const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
322
+ file.update(`${JSON.stringify(manifest, null, indent)}\n`);
323
+ }
324
+ return selected;
325
+ };
326
+ const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
327
+ const openapiScriptPath = "scripts/generate-openapi.ts";
328
+ const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
329
+ const extractorPackages = [
330
+ 'ts-morph',
331
+ '@microsoft/tsdoc'
332
+ ];
333
+ const swaggerPagePath = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
334
+ const swaggerPage = (rootFolder, outputPath)=>{
335
+ const specImport = node_path.posix.relative(node_path.posix.dirname(swaggerPagePath(rootFolder)), outputPath);
336
+ return reactPageContent('Swagger', {
337
+ imports: [
338
+ "import 'swagger-ui-react/swagger-ui.css'",
339
+ "import SwaggerUI from 'swagger-ui-react'",
340
+ `import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
341
+ ],
342
+ body: '<SwaggerUI displayOperationId spec={spec} />'
343
+ });
344
+ };
345
+ const openapiScripts = {
346
+ openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
347
+ };
348
+ const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
349
+ const apiTitle = (packageName)=>{
350
+ const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
351
+ return [
352
+ ...words,
353
+ 'API'
354
+ ].join(' ');
355
+ };
356
+ const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
357
+ const restFolder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
358
+ const restImport = node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), restFolder);
359
+ const prefixSegments = splitPath(routePrefix);
360
+ const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
361
+ const extractorImport = `./${node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
362
+ const handlers = withExtractor ? `
363
+ const extractOpenApiDataFromEndpointLogic =
364
+ createOpenApiDataFromEndpointLogicExtractor();
365
+
366
+ const handlers = restHandlers.map((x) => ({
367
+ ...x,
368
+ metadata: {
369
+ ...x.metadata,
370
+ openApiMetadata: {
371
+ ...extractOpenApiDataFromEndpointLogic(x.metadata.route),
372
+ ...(x.metadata.openApiMetadata ?? {})
373
+ }
374
+ }
375
+ }));
376
+ ` : '';
377
+ return `import { generateOpenAPI } from '@domain-first/handlers-rest';
378
+ import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
379
+ ${handlers}
380
+ generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
381
+ document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
382
+ outputFile: { path: '${outputPath}' }
383
+ });
384
+ `;
385
+ };
386
+ const addOpenapi = async ()=>{
387
+ const { rootFolder } = ConfigFile.Instance.data;
388
+ const root = new ProjectRoot().path;
389
+ const manifestFile = new File(node_path.join(root, 'package.json'));
390
+ const manifest = JSON.parse(manifestFile.data);
391
+ const dependencies = {
392
+ ...manifest.dependencies,
393
+ ...manifest.devDependencies
394
+ };
395
+ const routePrefix = await input({
396
+ message: 'Route prefix the REST handlers are served under:',
397
+ default: '/api'
398
+ });
399
+ const outputPath = await input({
400
+ message: 'OpenAPI document path:',
401
+ default: defaultOpenapiPath(Boolean(dependencies.next)),
402
+ validate: (value)=>splitPath(value).length ? true : 'Path is required'
403
+ });
404
+ const withExtractor = await prompts_confirm({
405
+ message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
406
+ default: true
407
+ });
408
+ const withSwaggerPage = ConfigFile.Instance.data.useReact && await prompts_confirm({
409
+ message: 'Add a Swagger UI page?',
410
+ default: true
411
+ });
412
+ const selected = await addPackageScripts(manifestFile, openapiScripts);
413
+ if (withExtractor) {
414
+ const extractorFile = new File(node_path.join(root, openapiExtractorPath));
415
+ const extractor = openapiExtractor(rootFolder);
416
+ if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
417
+ }
418
+ const generatorFile = new File(node_path.join(root, openapiScriptPath));
419
+ const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
420
+ if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
421
+ if (withSwaggerPage) {
422
+ const pageFile = new File(node_path.join(root, swaggerPagePath(rootFolder)));
423
+ const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
424
+ if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
425
+ }
426
+ const resolveJsonModule = withSwaggerPage ? compilerOption(node_path.join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
427
+ const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
428
+ const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
429
+ return [
430
+ ...dependencies['@domain-first/handlers-rest'] ? [] : [
431
+ 'npm install @domain-first/handlers-rest'
432
+ ],
433
+ ...dependencies.tsx ? [] : [
434
+ 'npm install --save-dev tsx'
435
+ ],
436
+ ...missingExtractorPackages.length ? [
437
+ `npm install --save-dev ${missingExtractorPackages.join(' ')}`
438
+ ] : [],
439
+ ...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
440
+ 'npm install swagger-ui-react'
441
+ ] : [],
442
+ ...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
443
+ 'npm install --save-dev @types/swagger-ui-react'
444
+ ] : [],
445
+ ...true === resolveJsonModule || null === resolveJsonModule ? [] : [
446
+ 'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
447
+ ],
448
+ ...describeScripts(selected, {
449
+ openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
450
+ }),
451
+ ...withSwaggerPage ? [
452
+ `SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
453
+ ] : [],
454
+ ...hasRestHandlers ? [] : [
455
+ `restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
456
+ ]
457
+ ];
458
+ };
459
+ const addGitignoreEntry = (root, entry)=>{
460
+ const gitignore = new File(node_path.join(root, '.gitignore'));
461
+ const ignored = gitignore.exists ? gitignore.data : '';
462
+ if (ignored.split(/\r?\n/).includes(entry)) return;
463
+ const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
464
+ gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${entry}${newline}`);
465
+ };
466
+ const dataLayerFolder = (rootFolder, target)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'hooks' === target ? 'presentation/react/data-layer' : 'presentation/data-layer');
467
+ const orvalScripts = (rootFolder, targets)=>({
468
+ 'client:orval': targets.map((target)=>`orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder, target)}/orval.config.ts`)}`).join(' && ')
469
+ });
470
+ const orvalConfig = (rootFolder, openapiPath, withNext, target = 'hooks', mutatorPath = './api-client/mutator.ts')=>{
471
+ const inputPath = node_path.posix.relative(dataLayerFolder(rootFolder, target), openapiPath);
472
+ const baseUrl = withNext ? `
473
+ baseUrl: {
474
+ runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
475
+ },` : '';
476
+ const client = 'hooks' === target ? `
477
+ client: 'react-query',
478
+ httpClient: 'fetch',` : `
479
+ client: 'fetch',`;
480
+ const query = 'hooks' === target ? `,
481
+ query: {
482
+ version: 5
483
+ }` : '';
484
+ return `import { defineConfig } from 'orval';
485
+
486
+ export default defineConfig({
487
+ api: {
488
+ input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
489
+ output: {
490
+ mode: 'tags-split',
491
+ target: './orval',
492
+ schemas: './orval/model',${client}${baseUrl}
493
+ clean: true,
494
+ override: {
495
+ mutator: {
496
+ path: '${mutatorPath}',
497
+ name: 'customInstance'
498
+ },
499
+ fetch: {
500
+ includeHttpResponseReturnType: false
501
+ }${query}
502
+ }
503
+ }
504
+ }
505
+ });
506
+ `;
507
+ };
508
+ const orvalMutator = `/** Error of the generated requests, with the parsed response body. */
509
+ export class ApiError<Body = unknown> extends Error {
510
+ constructor(
511
+ public readonly status: number,
512
+ public readonly body: Body
513
+ ) {
514
+ super(\`API error \${status}\`);
515
+ this.name = 'ApiError';
516
+ }
517
+ }
518
+
519
+ /** Error type of the generated requests, typed per endpoint by Orval. */
520
+ export type ErrorType<Body> = ApiError<Body>;
521
+
522
+ /** Every generated request goes through here: add auth headers, token refresh, logging. */
523
+ export const customInstance = async <T>(
524
+ url: string,
525
+ init?: RequestInit
526
+ ): Promise<T> => {
527
+ const response = await fetch(url, init);
528
+ const text = await response.text();
529
+ const body = text ? JSON.parse(text) : undefined;
530
+
531
+ if (!response.ok) {
532
+ throw new ApiError(response.status, body);
533
+ }
534
+
535
+ return body as T;
536
+ };
537
+ `;
538
+ const queryProvider = `'use client';
539
+
540
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
541
+ import { type FC, type ReactNode, useState } from 'react';
542
+
543
+ export const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {
544
+ // One client per browser session; a module-level client would be shared between requests on the server
545
+ const [queryClient] = useState(() => new QueryClient());
546
+
547
+ return (
548
+ <QueryClientProvider client={queryClient}>
549
+ {children}
550
+ </QueryClientProvider>
551
+ );
552
+ };
553
+ `;
554
+ const openapiOutputPath = (root)=>{
555
+ const generator = new File(node_path.join(root, openapiScriptPath));
556
+ if (!generator.exists) return;
557
+ return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
558
+ };
559
+ const addOrval = async ()=>{
560
+ const { rootFolder, useReact } = ConfigFile.Instance.data;
561
+ const root = new ProjectRoot().path;
562
+ const manifestFile = new File(node_path.join(root, 'package.json'));
563
+ const manifest = JSON.parse(manifestFile.data);
564
+ const dependencies = {
565
+ ...manifest.dependencies,
566
+ ...manifest.devDependencies
567
+ };
568
+ const withNext = Boolean(dependencies.next);
569
+ const generatedOpenapiPath = openapiOutputPath(root);
570
+ const openapiPath = await input({
571
+ message: 'OpenAPI document path:',
572
+ default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
573
+ validate: (value)=>value.trim() ? true : 'Path is required'
574
+ });
575
+ const targets = useReact ? await prompts_checkbox({
576
+ message: 'Generate:',
577
+ choices: [
578
+ {
579
+ name: 'React Query hooks',
580
+ value: 'hooks',
581
+ checked: true
582
+ },
583
+ {
584
+ name: 'Typed API client',
585
+ value: 'client'
586
+ }
587
+ ],
588
+ required: true
589
+ }) : [
590
+ 'client'
591
+ ];
592
+ const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder, targets));
593
+ const document = node_path.posix.normalize(openapiPath.trim().replaceAll('\\', '/'));
594
+ const withClient = targets.includes('client');
595
+ for (const target of targets){
596
+ const dataLayer = dataLayerFolder(rootFolder, target);
597
+ const sharedMutator = 'hooks' === target && withClient;
598
+ const mutatorPath = sharedMutator ? `${node_path.posix.relative(dataLayer, dataLayerFolder(rootFolder, 'client'))}/api-client/mutator.ts` : void 0;
599
+ const configFile = new File(node_path.join(root, dataLayer, 'orval.config.ts'));
600
+ const content = orvalConfig(rootFolder, document, withNext, target, mutatorPath);
601
+ if (!configFile.exists || configFile.data !== content) configFile.data = content;
602
+ for (const [name, fileContent] of [
603
+ ...sharedMutator ? [] : [
604
+ [
605
+ 'api-client/mutator.ts',
606
+ orvalMutator
607
+ ]
608
+ ],
609
+ ...'hooks' === target ? [
610
+ [
611
+ 'query-provider.tsx',
612
+ queryProvider
613
+ ]
614
+ ] : []
615
+ ]){
616
+ const file = new File(node_path.join(root, dataLayer, name));
617
+ if (!file.exists) file.data = fileContent;
618
+ }
619
+ addGitignoreEntry(root, `/${dataLayer}/orval/`);
620
+ }
621
+ const generated = targets.map((target)=>'hooks' === target ? `React Query hooks in ${dataLayerFolder(rootFolder, 'hooks')}/orval` : `a typed API client in ${dataLayerFolder(rootFolder, 'client')}/orval`);
622
+ const missing = (names)=>names.filter((name)=>!dependencies[name]);
623
+ const runtime = missing(targets.includes('hooks') ? [
624
+ '@tanstack/react-query'
625
+ ] : []);
626
+ const development = missing([
627
+ 'orval'
628
+ ]);
629
+ return [
630
+ ...runtime.length ? [
631
+ `npm install ${runtime.join(' ')}`
632
+ ] : [],
633
+ ...development.length ? [
634
+ `npm install --save-dev ${development.join(' ')}`
635
+ ] : [],
636
+ ...describeScripts(selected, {
637
+ 'client:orval': `generate ${generated.join(' and ')} from ${openapiPath.trim()}`
638
+ }),
639
+ ...targets.includes('hooks') ? [
640
+ `Wrap your app in QueryProvider from ${dataLayerFolder(rootFolder, 'hooks')}/query-provider.tsx`
641
+ ] : [],
642
+ ...generatedOpenapiPath ? [] : [
643
+ 'npx df-integration → OpenAPI generates the OpenAPI document the client is built from'
644
+ ]
645
+ ];
646
+ };
647
+ const playwrightScripts = {
648
+ 'test:e2e': 'playwright test'
649
+ };
650
+ const playwrightConfig = `import { defineConfig, devices } from '@playwright/test';
651
+
652
+ export default defineConfig({
653
+ testDir: './specs/e2e',
654
+ fullyParallel: true,
655
+ forbidOnly: !!process.env.CI,
656
+ retries: process.env.CI ? 2 : 0,
657
+ workers: process.env.CI ? 1 : undefined,
658
+ reporter: 'html',
659
+ use: {
660
+ baseURL: 'http://localhost:3000',
661
+ trace: 'on-first-retry',
662
+ screenshot: 'only-on-failure',
663
+ video: 'retain-on-failure'
664
+ },
665
+
666
+ projects: [
667
+ {
668
+ name: 'chromium',
669
+ use: { ...devices['Desktop Chrome'] }
670
+ },
671
+ {
672
+ name: 'firefox',
673
+ use: { ...devices['Desktop Firefox'] }
674
+ },
675
+ {
676
+ name: 'webkit',
677
+ use: { ...devices['Desktop Safari'] }
678
+ },
679
+ {
680
+ name: 'Mobile Chrome',
681
+ use: { ...devices['Pixel 5'] }
682
+ },
683
+ {
684
+ name: 'Mobile Safari',
685
+ use: { ...devices['iPhone 12'] }
686
+ }
687
+ ],
688
+
689
+ webServer: {
690
+ // Playwright only stops the dev server on a clean shutdown. If its process dies any other
691
+ // way (SIGHUP, SIGKILL), the dev server lives on in its own process group, so it is killed
692
+ // as soon as Playwright is gone.
693
+ command:
694
+ process.platform === 'win32'
695
+ ? 'npm run dev'
696
+ : \`npm run dev & while kill -0 \${process.pid} 2>/dev/null && kill -0 $! 2>/dev/null; do sleep 1; done; kill 0\`,
697
+ url: 'http://localhost:3000',
698
+ timeout: 120000,
699
+ reuseExistingServer: !process.env.CI
700
+ }
701
+ });
702
+ `;
703
+ const exampleSpec = `import { expect, test } from '@playwright/test';
704
+
705
+ test.describe('home page', () => {
706
+ test('opens the home page', async ({ page, baseURL }) => {
707
+ await page.goto('/');
708
+ await expect(page).toHaveURL(\`\${baseURL}/\`);
709
+ });
710
+ });
711
+ `;
712
+ const exampleReadme = `# Home page e2e cases
713
+
714
+ ## User Stories
715
+
716
+ 1. Guest opens \`/\` and stays on the home page.
717
+ `;
718
+ const gitignoreEntries = [
719
+ '/test-results/',
720
+ '/playwright-report/',
721
+ '/blob-report/',
722
+ '/playwright/.cache/',
723
+ '/playwright/.auth/'
724
+ ];
725
+ const addPlaywright = async ()=>{
726
+ const root = new ProjectRoot().path;
727
+ const manifestFile = new File(node_path.join(root, 'package.json'));
728
+ const manifest = JSON.parse(manifestFile.data);
729
+ const dependencies = {
730
+ ...manifest.dependencies,
731
+ ...manifest.devDependencies
732
+ };
733
+ const selected = await addPackageScripts(manifestFile, playwrightScripts);
734
+ const configFile = new File(node_path.join(root, 'playwright.config.ts'));
735
+ if (!configFile.exists || configFile.data !== playwrightConfig) configFile.data = playwrightConfig;
736
+ const exampleFolder = node_path.join(root, 'specs/e2e/home');
737
+ for (const [name, content] of [
738
+ [
739
+ 'home.e2e.spec.ts',
740
+ exampleSpec
741
+ ],
742
+ [
743
+ 'README.MD',
744
+ exampleReadme
745
+ ]
746
+ ]){
747
+ const file = new File(node_path.join(exampleFolder, name));
748
+ if (!file.exists) file.data = content;
749
+ }
750
+ for (const entry of gitignoreEntries)addGitignoreEntry(root, entry);
751
+ return [
752
+ ...dependencies['@playwright/test'] ? [] : [
753
+ 'npm install --save-dev @playwright/test'
754
+ ],
755
+ 'npx playwright install --with-deps',
756
+ ...describeScripts(selected, {
757
+ 'test:e2e': 'start the dev server and run end-to-end specs from specs/e2e'
758
+ })
759
+ ];
760
+ };
761
+ const runtimePackages = [
762
+ '@prisma/orm-postgres',
763
+ 'temporal-polyfill',
764
+ 'dotenv'
765
+ ];
766
+ const developmentPackages = [
767
+ 'prisma',
768
+ '@prisma/cli-engine'
769
+ ];
770
+ const prismaScripts = (rootFolder)=>{
771
+ const config = JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared/infrastructure/prisma/prisma.config.ts'));
772
+ const emit = `prisma contract emit --config ${config}`;
773
+ return {
774
+ 'prisma:emit': emit,
775
+ 'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
776
+ 'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
777
+ };
778
+ };
779
+ const prismaConfig = `import 'dotenv/config';
780
+ import { definePrismaConfig } from '@prisma/cli-engine';
781
+ import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
782
+
783
+ export default definePrismaConfig({
784
+ orm: ormConfig({
785
+ contract: './contract.prisma',
786
+ migrations: { dir: './migrations' },
787
+ db: {
788
+ connection: process.env.DATABASE_URL
789
+ }
790
+ })
791
+ });
792
+ `;
793
+ const prismaService = `import 'temporal-polyfill/global';
794
+ import postgres from '@prisma/orm-postgres/runtime';
795
+ import type {} from 'temporal-polyfill/types/global';
796
+ import type { Contract } from '../prisma/contract.d';
797
+ import contractJson from '../prisma/contract.json' with { type: 'json' };
798
+
799
+ type PrismaClient = ReturnType<typeof postgres<Contract>>;
800
+
801
+ const globalForPrisma = globalThis as typeof globalThis & {
802
+ prismaClient?: PrismaClient;
803
+ };
804
+
805
+ // Reuse the client across development hot reloads.
806
+ const prismaClient = globalForPrisma.prismaClient ??
807
+ postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
808
+
809
+ if (process.env.NODE_ENV !== 'production') {
810
+ globalForPrisma.prismaClient = prismaClient;
811
+ }
812
+
813
+ export class PrismaInfrastructureService {
814
+ readonly orm = prismaClient.orm.public;
815
+ }
816
+ `;
817
+ const prismaWiring = `import { wireClass } from '@domain-first/wire';
818
+ import { PrismaInfrastructureService } from '../../infrastructure/services/prisma-infrastructure-service';
819
+
820
+ export const wirePrismaInfrastructureService = wireClass(
821
+ PrismaInfrastructureService,
822
+ []
823
+ );
824
+ `;
825
+ const stageFile = (filePath, content)=>{
826
+ const file = new File(filePath);
827
+ if (!file.exists || file.data !== content) file.data = content;
828
+ };
829
+ const addPrisma = async ()=>{
830
+ const config = ConfigFile.Instance.data;
831
+ const root = new ProjectRoot().path;
832
+ const manifestFile = new File(node_path.join(root, 'package.json'));
833
+ const manifest = JSON.parse(manifestFile.data);
834
+ const dependencies = {
835
+ ...manifest.dependencies,
836
+ ...manifest.devDependencies
837
+ };
838
+ const shared = node_path.resolve(root, config.rootFolder, 'shared');
839
+ const prismaFolder = node_path.join(shared, 'infrastructure/prisma');
840
+ if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
841
+ node_path.join(root, 'prisma/schema.prisma'),
842
+ node_path.join(prismaFolder, 'schema.prisma')
843
+ ].some((filePath)=>new File(filePath).exists)) throw new Error('This preset adds Prisma 8 for PostgreSQL. Migrate the existing Prisma setup separately before using it.');
844
+ const withService = await prompts_confirm({
845
+ message: 'Create shared Prisma infrastructure service?',
846
+ default: true
847
+ });
848
+ const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await prompts_confirm({
849
+ message: 'Use prisma as the default persistence implementation?',
850
+ default: false
851
+ });
852
+ const selected = await addPackageScripts(manifestFile, prismaScripts(config.rootFolder));
853
+ stageFile(node_path.join(prismaFolder, 'prisma.config.ts'), prismaConfig);
854
+ const contract = new File(node_path.join(prismaFolder, 'contract.prisma'));
855
+ if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
856
+ if (withService) {
857
+ stageFile(node_path.join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
858
+ if (config.domainFirstPackages.includes('@domain-first/wire')) stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
859
+ }
860
+ if (useByDefault) ConfigFile.write({
861
+ ...config,
862
+ defaultPersistenceLayerImplementation: 'prisma'
863
+ });
864
+ const install = (packages, dev)=>{
865
+ const missing = packages.filter((name)=>!dependencies[name]);
866
+ return missing.length ? [
867
+ `npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
868
+ ] : [];
869
+ };
870
+ const relativeFolder = node_path.relative(root, prismaFolder).split(node_path.sep).join('/');
871
+ return [
872
+ ...install(runtimePackages, false),
873
+ ...install(developmentPackages, true),
874
+ `Add !${relativeFolder} in your linter, to ignore prisma files.`,
875
+ ...describeScripts(selected, {
876
+ 'prisma:emit': 'emit contract.json and contract.d.ts from contract.prisma',
877
+ 'prisma:migration:plan': 'emit the contract and plan a migration',
878
+ 'prisma:migration:apply': 'apply planned migrations to the database in DATABASE_URL'
879
+ })
880
+ ];
881
+ };
882
+ const storybookFiles = (relativeProjectRoot)=>({
883
+ 'main.ts': `import { resolve } from 'node:path';
884
+ import react from '@vitejs/plugin-react';
885
+ import type { StorybookConfig } from '@storybook/react-vite';
886
+
887
+ const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
888
+
889
+ const config: StorybookConfig = {
890
+ stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
891
+ framework: {
892
+ name: '@storybook/react-vite',
893
+ options: {}
894
+ },
895
+ core: {
896
+ disableTelemetry: true
897
+ },
898
+ async viteFinal(viteConfig) {
899
+ const { mergeConfig } = await import('vite');
900
+
901
+ return mergeConfig(viteConfig, {
902
+ plugins: [react()],
903
+ resolve: {
904
+ alias: {
905
+ '@': projectRoot
906
+ }
907
+ }
908
+ });
909
+ }
910
+ };
911
+
912
+ export default config;
913
+ `,
914
+ 'preview.ts': `import type { Preview } from '@storybook/react-vite';
915
+
916
+ const preview: Preview = {
917
+ parameters: {
918
+ controls: {
919
+ matchers: {
920
+ color: /(background|color)$/i,
921
+ date: /Date$/i
922
+ }
923
+ }
924
+ }
925
+ };
926
+
927
+ export default preview;
928
+ `
929
+ });
930
+ const storybookScripts = (rootFolder)=>{
931
+ const folder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
932
+ const quote = (value)=>JSON.stringify(value);
933
+ return {
934
+ storybook: `storybook dev -p 6006 -c ${quote(`${folder}/.storybook`)}`,
935
+ 'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
936
+ };
937
+ };
938
+ const addStorybook = async ()=>{
939
+ const config = ConfigFile.Instance.data;
940
+ if ((!config.useReact || config.storybookFramework && '@storybook/react-vite' !== config.storybookFramework) && !await prompts_confirm({
941
+ message: 'Configure React scaffolding with @storybook/react-vite?',
942
+ default: false
943
+ })) return [];
944
+ const root = new ProjectRoot().path;
945
+ const manifestFile = new File(node_path.join(root, 'package.json'));
946
+ const manifest = JSON.parse(manifestFile.data);
947
+ const selected = await addPackageScripts(manifestFile, storybookScripts(config.rootFolder));
948
+ const folder = new Folder(root).subitem([
949
+ config.rootFolder,
950
+ 'presentation',
951
+ 'react',
952
+ '.storybook'
953
+ ]);
954
+ for (const [name, content] of Object.entries(storybookFiles(node_path.relative(folder.path, root).split(node_path.sep).join('/')))){
955
+ const file = new File(node_path.join(folder.path, name));
956
+ if (!file.exists || file.data !== content) file.data = content;
957
+ }
958
+ if (!config.useReact || '@storybook/react-vite' !== config.storybookFramework) ConfigFile.write({
959
+ ...config,
960
+ useReact: true,
961
+ storybookFramework: '@storybook/react-vite'
962
+ });
963
+ const buildFolder = node_path.posix.join(config.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
964
+ addGitignoreEntry(root, `/${buildFolder}/`);
965
+ const dependencies = {
966
+ ...manifest.dependencies,
967
+ ...manifest.devDependencies
968
+ };
969
+ const missing = [
970
+ 'storybook',
971
+ '@storybook/react-vite',
972
+ 'vite',
973
+ '@vitejs/plugin-react'
974
+ ].filter((name)=>!dependencies[name]);
975
+ const missingReact = [
976
+ 'react',
977
+ 'react-dom'
978
+ ].filter((name)=>!dependencies[name]);
979
+ return [
980
+ ...missing.length ? [
981
+ `npm install --save-dev ${missing.join(' ')}`
982
+ ] : [],
983
+ ...missingReact.length ? [
984
+ `npm install ${missingReact.join(' ')}`
985
+ ] : [],
986
+ ...describeScripts(selected, {
987
+ storybook: 'start Storybook on http://localhost:6006',
988
+ 'build-storybook': `build static Storybook into ${buildFolder}`
989
+ })
990
+ ];
991
+ };
992
+ const integrationFolder = 'specs/integration';
993
+ const testcontainersScripts = {
994
+ 'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
995
+ };
996
+ const testcontainersVitestConfig = (inlineHandlersNext)=>{
997
+ const server = inlineHandlersNext ? `,
998
+ server: {
999
+ deps: {
1000
+ // Imports \`next/headers\` without an extension, which only a bundler can resolve
1001
+ inline: ['@domain-first/handlers-next']
1002
+ }
1003
+ }` : '';
1004
+ return `import { fileURLToPath } from 'node:url';
1005
+ import { defineConfig } from 'vitest/config';
1006
+
1007
+ // Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
1008
+ export default defineConfig({
1009
+ // Paths below are relative to the project root, not this folder
1010
+ root: fileURLToPath(new URL('../..', import.meta.url)),
1011
+ resolve: {
1012
+ tsconfigPaths: true
1013
+ },
1014
+ test: {
1015
+ include: ['${integrationFolder}/**/*.spec.ts'],
1016
+ // Development implementations work with the real database
1017
+ env: { NODE_ENV: 'development' },
1018
+ globalSetup: ['${integrationFolder}/global-setup.ts'],
1019
+ setupFiles: ['${integrationFolder}/setup-env.ts'],
1020
+ // Pulling the image on the first run takes a while
1021
+ hookTimeout: 120_000${server}
1022
+ }
1023
+ });
1024
+ `;
1025
+ };
1026
+ const testcontainersGlobalSetup = (migrationCommand)=>{
1027
+ const migrations = migrationCommand ? `
1028
+ // dotenv in the Prisma config does not override an already set variable
1029
+ execSync(${JSON.stringify(migrationCommand)}, {
1030
+ cwd: project.config.root,
1031
+ env: { ...process.env, DATABASE_URL: databaseUrl },
1032
+ // On failure the error carries the command's output
1033
+ stdio: 'pipe'
1034
+ });
1035
+ ` : `
1036
+ // Apply your migrations to databaseUrl here.
1037
+ `;
1038
+ return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
1039
+ import type { TestProject } from 'vitest/node';
1040
+
1041
+ declare module 'vitest' {
1042
+ export interface ProvidedContext {
1043
+ databaseUrl: string;
1044
+ }
1045
+ }
1046
+
1047
+ const POSTGRES_IMAGE = 'postgres:15';
1048
+ const POSTGRES_PORT = 5432;
1049
+ const POSTGRES_USER = 'test';
1050
+ const POSTGRES_PASSWORD = 'test';
1051
+ const POSTGRES_DB = 'test';
1052
+
1053
+ export default async function setup(project: TestProject) {
1054
+ const container = await new GenericContainer(POSTGRES_IMAGE)
1055
+ .withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
1056
+ .withExposedPorts(POSTGRES_PORT)
1057
+ // During init PostgreSQL listens on a unix socket only and restarts,
1058
+ // so checking over TCP passes once the final server is up
1059
+ .withHealthCheck({
1060
+ test: [
1061
+ 'CMD-SHELL',
1062
+ \`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
1063
+ ],
1064
+ interval: 250,
1065
+ timeout: 1000,
1066
+ retries: 1000
1067
+ })
1068
+ .withWaitStrategy(Wait.forHealthCheck())
1069
+ .withStartupTimeout(120_000)
1070
+ .start();
1071
+
1072
+ const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
1073
+ ${migrations}
1074
+ project.provide('databaseUrl', databaseUrl);
1075
+
1076
+ return async () => {
1077
+ await container.stop();
1078
+ };
1079
+ }
1080
+ `;
1081
+ };
1082
+ const testcontainersSetupEnv = `import 'dotenv/config';
1083
+ import { inject } from 'vitest';
1084
+
1085
+ // Runs before each spec's imports: development implementations get the .env
1086
+ // config, and DATABASE_URL points to the container instead of the one from .env.
1087
+ if (process.env.NODE_ENV !== 'development') {
1088
+ throw new Error(
1089
+ \`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
1090
+ );
1091
+ }
1092
+
1093
+ process.env.DATABASE_URL = inject('databaseUrl');
1094
+ `;
1095
+ const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
1096
+
1097
+ test('connects to the database in the container', () => {
1098
+ expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
1099
+ });
1100
+ `;
1101
+ const excludeFromUnitTests = (content)=>{
1102
+ const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
1103
+ if (!exclude.test(content)) return;
1104
+ const entry = `'${integrationFolder}/**'`;
1105
+ return content.replace(exclude, (_, items, comma, whitespace)=>{
1106
+ const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
1107
+ const separator = void 0 === indent ? ', ' : `,\n${indent}`;
1108
+ return `${items}${separator}${entry}${comma}${whitespace}]`;
1109
+ }).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
1110
+ };
1111
+ const testcontainers_stageFile = (filePath, content)=>{
1112
+ const file = new File(filePath);
1113
+ if (!file.exists || file.data !== content) file.data = content;
1114
+ };
1115
+ const addTestcontainers = async ()=>{
1116
+ const config = ConfigFile.Instance.data;
1117
+ const root = new ProjectRoot().path;
1118
+ const manifestFile = new File(node_path.join(root, 'package.json'));
1119
+ const manifest = JSON.parse(manifestFile.data);
1120
+ const dependencies = {
1121
+ ...manifest.dependencies,
1122
+ ...manifest.devDependencies
1123
+ };
1124
+ const selected = await addPackageScripts(manifestFile, testcontainersScripts);
1125
+ const withPrisma = new File(node_path.resolve(root, config.rootFolder, 'shared/infrastructure/prisma/prisma.config.ts')).exists;
1126
+ const migrationCommand = withPrisma ? `npx ${prismaScripts(config.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
1127
+ const folder = node_path.join(root, integrationFolder);
1128
+ testcontainers_stageFile(node_path.join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
1129
+ testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
1130
+ testcontainers_stageFile(node_path.join(folder, 'setup-env.ts'), testcontainersSetupEnv);
1131
+ const example = new File(node_path.join(folder, 'database/database.spec.ts'));
1132
+ if (!example.exists) example.data = testcontainers_exampleSpec;
1133
+ const unitConfig = new File(node_path.join(root, 'vitest.config.ts'));
1134
+ let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
1135
+ if (!excludedFromUnitTests) {
1136
+ const excluded = excludeFromUnitTests(unitConfig.data);
1137
+ if (excluded) {
1138
+ unitConfig.update(excluded);
1139
+ excludedFromUnitTests = true;
1140
+ }
1141
+ }
1142
+ const missing = [
1143
+ 'vitest',
1144
+ 'testcontainers',
1145
+ 'dotenv'
1146
+ ].filter((name)=>!dependencies[name]);
1147
+ return [
1148
+ ...missing.length ? [
1149
+ `npm install --save-dev ${missing.join(' ')}`
1150
+ ] : [],
1151
+ `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.`,
1152
+ ...migrationCommand ? [] : [
1153
+ `Apply your migrations in ${integrationFolder}/global-setup.ts.`
1154
+ ],
1155
+ ...excludedFromUnitTests ? [] : [
1156
+ `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
1157
+ ],
1158
+ 'Docker must be running for integration specs.',
1159
+ ...describeScripts(selected, {
1160
+ 'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
1161
+ })
1162
+ ];
1163
+ };
1164
+ const vitestScripts = {
1165
+ test: 'vitest run --reporter=dot --silent=passed-only',
1166
+ 'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
1167
+ };
1168
+ const vitestConfig = (rootFolder, inlineHandlersNext)=>{
1169
+ const folder = (subpath)=>JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), subpath));
1170
+ const server = inlineHandlersNext ? `,
1171
+ server: {
1172
+ deps: {
1173
+ // Imports \`next/headers\` without an extension, which only a bundler can resolve
1174
+ inline: ['@domain-first/handlers-next']
1175
+ }
1176
+ }` : '';
1177
+ return `import { configDefaults, defineConfig } from 'vitest/config';
1178
+
1179
+ export default defineConfig({
1180
+ resolve: {
1181
+ tsconfigPaths: true
1182
+ },
1183
+ test: {
1184
+ // Playwright runs end-to-end specs, test:integration runs integration ones
1185
+ exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
1186
+ coverage: {
1187
+ provider: 'v8',
1188
+ include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared/**/*.ts')}],
1189
+ exclude: [
1190
+ '**/*.spec.ts',
1191
+ ${folder('shared/infrastructure/**')},
1192
+ ${folder('bounded-contexts/*/infrastructure/**')},
1193
+ ${folder('bounded-contexts/*/presentation/rest/**')},
1194
+ ${folder('shared/wiring/**')},
1195
+ ${folder('bounded-contexts/*/wiring/**')}
1196
+ ],
1197
+ reporter: [['text', { skipFull: true }], 'html']
1198
+ }${server}
1199
+ }
1200
+ });
1201
+ `;
1202
+ };
1203
+ const addVitest = async ()=>{
1204
+ const config = ConfigFile.Instance.data;
1205
+ if (config.testingLibrary && 'vitest' !== config.testingLibrary && !await prompts_confirm({
1206
+ message: `Replace testing library "${config.testingLibrary}" with vitest for generated tests?`,
1207
+ default: false
1208
+ })) return [];
1209
+ const root = new ProjectRoot().path;
1210
+ const manifestFile = new File(node_path.join(root, 'package.json'));
1211
+ const manifest = JSON.parse(manifestFile.data);
1212
+ const dependencies = {
1213
+ ...manifest.dependencies,
1214
+ ...manifest.devDependencies
1215
+ };
1216
+ const selected = await addPackageScripts(manifestFile, vitestScripts);
1217
+ const configFile = new File(node_path.join(root, 'vitest.config.ts'));
1218
+ const content = vitestConfig(config.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
1219
+ if (!configFile.exists || configFile.data !== content) configFile.data = content;
1220
+ if ('vitest' !== config.testingLibrary) ConfigFile.write({
1221
+ ...config,
1222
+ testingLibrary: 'vitest'
1223
+ });
1224
+ addGitignoreEntry(root, '/coverage/');
1225
+ const missing = [
1226
+ 'vitest',
1227
+ '@vitest/coverage-v8'
1228
+ ].filter((name)=>!dependencies[name]);
1229
+ return [
1230
+ ...missing.length ? [
1231
+ `npm install --save-dev ${missing.join(' ')}`
1232
+ ] : [],
1233
+ ...describeScripts(selected, {
1234
+ test: 'run unit tests',
1235
+ 'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
1236
+ })
1237
+ ];
1238
+ };
1239
+ const withHandlersRest = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers-rest');
1240
+ const created = (...segments)=>new File(node_path.join(new ProjectRoot().path, ...segments)).exists;
1241
+ const createdInRoot = (...segments)=>created(ConfigFile.Instance.data.rootFolder, ...segments);
1242
+ const integrations = [
1243
+ {
1244
+ name: 'Storybook (React + Vite)',
1245
+ group: 'frontend',
1246
+ run: addStorybook,
1247
+ applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
1248
+ },
1249
+ {
1250
+ name: 'Prisma 8 (PostgreSQL, RC)',
1251
+ group: 'backend',
1252
+ run: addPrisma,
1253
+ applied: ()=>createdInRoot('shared/infrastructure/prisma/prisma.config.ts')
1254
+ },
1255
+ {
1256
+ name: 'Vitest',
1257
+ group: 'backend',
1258
+ run: addVitest,
1259
+ applied: ()=>created('vitest.config.ts')
1260
+ },
1261
+ {
1262
+ name: 'Playwright',
1263
+ group: 'frontend',
1264
+ run: addPlaywright,
1265
+ applied: ()=>created('playwright.config.ts')
1266
+ },
1267
+ {
1268
+ name: 'Integration tests (Testcontainers, PostgreSQL)',
1269
+ group: 'backend',
1270
+ run: addTestcontainers,
1271
+ applied: ()=>created('specs/integration/vitest.config.ts')
1272
+ },
1273
+ {
1274
+ name: 'OpenAPI',
1275
+ group: 'backend',
1276
+ run: addOpenapi,
1277
+ available: ()=>withHandlersRest(),
1278
+ applied: ()=>created(openapiScriptPath)
1279
+ },
1280
+ {
1281
+ name: 'Orval (API client)',
1282
+ group: 'frontend',
1283
+ run: addOrval,
1284
+ available: ()=>withHandlersRest(),
1285
+ applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
1286
+ },
1287
+ {
1288
+ name: 'Missing domain-first packages',
1289
+ group: 'backend',
1290
+ run: missingDomainFirstPackages,
1291
+ applied: ()=>!missingDomainFirstPackages().length
1292
+ }
1293
+ ];
1294
+ const addIntegration = async ()=>{
1295
+ const available = integrations.filter(({ available })=>available?.() ?? true).map((value)=>({
1296
+ value,
1297
+ applied: value.applied()
1298
+ }));
1299
+ const section = (title, applied)=>{
1300
+ const items = [
1301
+ 'backend',
1302
+ 'frontend'
1303
+ ].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
1304
+ return items.length ? [
1305
+ new Separator(title),
1306
+ ...items.map(({ value })=>({
1307
+ name: `${value.name} · ${value.group}`,
1308
+ value
1309
+ }))
1310
+ ] : [];
1311
+ };
1312
+ const choices = [
1313
+ ...section('New integrations', false),
1314
+ ...section('Already applied (select to reapply)', true)
1315
+ ];
1316
+ const selected = await prompts_checkbox({
1317
+ message: 'Integrations:',
1318
+ choices,
1319
+ pageSize: choices.length
1320
+ });
1321
+ const nextSteps = [];
1322
+ for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
1323
+ if (await savePendingChanges()) printNextSteps(nextSteps);
1324
+ };
1325
+ const inMemoryImplementationType = 'in-memory';
1326
+ const in_memory_db_className = 'InMemoryDbInfrastructureService';
1327
+ const wireName = 'wireInMemoryDbInfrastructureService';
1328
+ const parameterName = 'inMemoryDbInfrastructureService';
1329
+ const inMemoryDbService = `type Entry = {
1330
+ id: unknown;
1331
+ item: any;
1332
+ };
1333
+
1334
+ declare global {
1335
+ var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
1336
+ }
1337
+
1338
+ type Section<T, TId> = {
1339
+ all: (predicate?: (x: T) => boolean) => T[];
1340
+ first: (predicate: (x: T) => boolean) => T | null;
1341
+ withId: (id: TId) => T | null;
1342
+ lastAddedItem: () => T | null;
1343
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
1344
+ deleteById: (id: TId) => void;
1345
+ delete: (predicate: (x: T) => boolean) => void;
1346
+ };
1347
+
1348
+ type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
1349
+
1350
+ const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
1351
+
1352
+ const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
1353
+ if (typeof a !== 'object' || a === null) {
1354
+ return Object.is(a, b);
1355
+ }
1356
+
1357
+ for (const methodName of comparisonMethodNames) {
1358
+ const method: unknown = (a as Record<string, unknown>)[methodName];
1359
+ if (typeof method === 'function') {
1360
+ return Boolean(method.call(a, b));
1361
+ }
1362
+ }
1363
+
1364
+ return Object.is(a, b);
1365
+ };
1366
+
1367
+ const hasId = (x: unknown): x is { id: unknown } =>
1368
+ typeof x === 'object' && x !== null && 'id' in x;
1369
+
1370
+ export class InMemoryDbInfrastructureService {
1371
+ protected section<T extends { id: unknown }>(
1372
+ key: string,
1373
+ idsAreEqual?: IdsAreEqual<T['id']>
1374
+ ): Section<T, T['id']>;
1375
+ protected section<T, TId>(
1376
+ key: string,
1377
+ idsAreEqual?: IdsAreEqual<TId>
1378
+ ): Section<T, TId>;
1379
+ protected section<T, TId>(
1380
+ key: string,
1381
+ idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
1382
+ ): Section<T, TId> {
1383
+ if (!globalThis.___SHARED_IN_MEMORY_DB___) {
1384
+ globalThis.___SHARED_IN_MEMORY_DB___ = {};
1385
+ }
1386
+
1387
+ if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
1388
+ globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
1389
+ }
1390
+
1391
+ const items = (): T[] =>
1392
+ globalThis.___SHARED_IN_MEMORY_DB___![key].map(
1393
+ (entry) => entry.item
1394
+ );
1395
+
1396
+ return {
1397
+ all: (predicate: (x: T) => boolean = () => true): T[] =>
1398
+ items().filter(predicate),
1399
+ first: (predicate: (x: T) => boolean): T | null =>
1400
+ items().find(predicate) ?? null,
1401
+ withId: (id: TId): T | null =>
1402
+ items().find(
1403
+ (x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
1404
+ ) ?? null,
1405
+ lastAddedItem: (): T | null =>
1406
+ globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
1407
+ save: (payload: T extends { id: TId } ? T : [TId, T]) => {
1408
+ const id = Array.isArray(payload) ? payload[0] : payload.id;
1409
+ const item = Array.isArray(payload) ? payload[1] : payload;
1410
+ const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
1411
+ const existing = entries.find((entry) =>
1412
+ idsAreEqual(entry.id as TId, id)
1413
+ );
1414
+ if (existing) {
1415
+ existing.item = item;
1416
+ return;
1417
+ }
1418
+ entries.push({ id, item });
1419
+ },
1420
+ deleteById: (id: TId) => {
1421
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
1422
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
1423
+ (entry) => !idsAreEqual(entry.id as TId, id)
1424
+ );
1425
+ },
1426
+ delete: (predicate: (x: T) => boolean) => {
1427
+ globalThis.___SHARED_IN_MEMORY_DB___![key] =
1428
+ globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
1429
+ (entry) => !predicate(entry.item)
1430
+ );
1431
+ }
1432
+ };
1433
+ }
1434
+ }
1435
+ `;
1436
+ const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
1437
+ import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
1438
+
1439
+ export const wireInMemoryDbInfrastructureService = wireClass(
1440
+ InMemoryDbInfrastructureService,
1441
+ []
1442
+ );
1443
+ `;
1444
+ const inMemoryDbSpec = (testingLibrary, withWiring)=>`
1445
+ import { describe, test, expect, beforeEach } from '${testingLibrary}'
1446
+ ${withWiring ? `import { type InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'
1447
+ import { wireInMemoryDbInfrastructureService } from '../../wiring/infrastructure-services/wire-in-memory-db-infrastructure-service'` : "import { InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'"}
1448
+
1449
+ let inMemoryDbInfrastructureService: InMemoryDbInfrastructureService
1450
+
1451
+ beforeEach(() => {
1452
+ inMemoryDbInfrastructureService = ${withWiring ? 'wireInMemoryDbInfrastructureService()' : 'new InMemoryDbInfrastructureService()'}
1453
+ })
1454
+
1455
+ describe('in memory db', () => {
1456
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
1457
+ expect(inMemoryDbInfrastructureService).toBeDefined()
1458
+ })
1459
+ })
1460
+ `.trim();
1461
+ const in_memory_db_withWiring = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1462
+ const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
1463
+ ConfigFile.Instance.data.rootFolder,
1464
+ 'shared'
1465
+ ]);
1466
+ const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
1467
+ 'infrastructure',
1468
+ 'services',
1469
+ 'in-memory-db-infrastructure-service.ts'
1470
+ ]);
1471
+ const in_memory_db_wireFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
1472
+ 'wiring',
1473
+ 'infrastructure-services',
1474
+ 'wire-in-memory-db-infrastructure-service.ts'
1475
+ ]);
1476
+ const scaffoldInMemoryDb = (shared)=>{
1477
+ const { testingLibrary } = ConfigFile.Instance.data;
1478
+ const servicesFolder = shared.subitem([
1479
+ 'infrastructure',
1480
+ 'services'
1481
+ ]);
1482
+ servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
1483
+ if (testingLibrary) servicesFolder.createFile('in-memory-db-infrastructure-service.spec.ts', inMemoryDbSpec(testingLibrary, in_memory_db_withWiring()));
1484
+ if (in_memory_db_withWiring()) shared.subitem([
1485
+ 'wiring',
1486
+ 'infrastructure-services'
1487
+ ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
1488
+ };
1489
+ const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
1490
+ const plural = (word)=>{
1491
+ if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
1492
+ if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
1493
+ return `${word}s`;
1494
+ };
1495
+ const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
1496
+ const file = serviceFile();
1497
+ const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
1498
+ const field = sectionNaming.variableName;
1499
+ if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
1500
+ const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
1501
+ file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
1502
+ return field;
1503
+ };
1504
+ const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
1505
+ const inMemoryDbSectionMembers = (field, derived)=>`
1506
+ private readonly data: ${in_memory_db_className}['${field}']
1507
+
1508
+ constructor(${parameterName}: ${in_memory_db_className}) {
1509
+ ${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
1510
+ }
1511
+ `.trim();
1512
+ const keepInMemoryDbSection = (classFile, field)=>{
1513
+ classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
1514
+ };
1515
+ const isInMemoryDb = (module)=>module.wireName === wireName;
1516
+ const injectInMemoryDb = (classFile, implementationName)=>{
1517
+ classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
1518
+ `private readonly ${parameterName}: ${in_memory_db_className}`
1519
+ ]));
1520
+ };
1521
+ const wireInMemoryDb = (consumerWireFile, implementationName)=>{
1522
+ consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
1523
+ wireName
1524
+ ]));
1525
+ };
1526
+ const passInMemoryDb = (specFile, implementationName)=>{
1527
+ 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}())`));
1528
+ };
1529
+ const kindTitles = {
1530
+ repositories: 'Repositories',
1531
+ 'domain-services': 'Domain services',
1532
+ 'application-ports': 'Ports',
1533
+ 'application-services': 'Application services',
1534
+ queries: 'Queries',
1535
+ commands: 'Commands',
1536
+ 'use-cases': 'Use cases',
1537
+ 'infrastructure-services': 'Infrastructure services',
1538
+ 'presentation-services': 'Presentation services'
1539
+ };
1540
+ const groupedChoices = (items, suggested = [])=>{
1541
+ const suggestedChoices = suggested.length ? [
1542
+ new Separator('── Suggested'),
1543
+ ...suggested.map((x)=>({
1544
+ name: x.label,
1545
+ value: x,
1546
+ checked: true
1547
+ }))
1548
+ ] : [];
1549
+ const kinds = [
1550
+ ...new Set([
1551
+ ...Object.keys(kindTitles),
1552
+ ...items.map((x)=>x.module.kind)
1553
+ ])
1554
+ ];
1555
+ return [
1556
+ ...suggestedChoices,
1557
+ ...kinds.flatMap((kind)=>{
1558
+ const group = items.filter((x)=>x.module.kind === kind && !suggested.includes(x));
1559
+ return group.length ? [
1560
+ new Separator(`── ${kindTitles[kind] ?? kind}`),
1561
+ ...group.map((x)=>({
1562
+ name: x.label,
1563
+ value: x
1564
+ }))
1565
+ ] : [];
1566
+ })
1567
+ ];
1568
+ };
1569
+ const groupedPageSize = 20;
1570
+ const contextAndSharedModules = (boundedContextFolder)=>{
1571
+ const sharedFolder = new Folder(new ProjectRoot().path).subitem([
1572
+ ConfigFile.Instance.data.rootFolder,
1573
+ 'shared'
1574
+ ]);
1575
+ const isShared = sharedFolder.path === boundedContextFolder.path;
1576
+ return [
1577
+ ...findWiredModules(boundedContextFolder.path).map((x)=>({
1578
+ module: x,
1579
+ label: x.typeName
1580
+ })),
1581
+ ...isShared ? [] : findWiredModules(sharedFolder.path).map((x)=>({
1582
+ module: x,
1583
+ label: `${x.typeName} (shared)`
1584
+ }))
1585
+ ];
1586
+ };
1587
+ const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations, customWiring)=>{
1588
+ const options = contextAndSharedModules(boundedContextFolder);
1589
+ let asked = false;
1590
+ for (const implementation of implementations){
1591
+ const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
1592
+ const candidates = options.filter((x)=>available.includes(x.module));
1593
+ if (!candidates.length) continue;
1594
+ asked = true;
1595
+ const type = wiring_implementationType(consumer, implementation);
1596
+ const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
1597
+ const dependencies = await prompts_checkbox({
1598
+ message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
1599
+ choices: groupedChoices(candidates, suggested),
1600
+ pageSize: groupedPageSize,
1601
+ loop: false
1602
+ });
1603
+ const defaultWired = dependencies.map((x)=>x.module).filter((x)=>!customWiring?.(implementation, x));
1604
+ if (defaultWired.length) wireDependencies(consumer, implementation, defaultWired);
1605
+ }
1606
+ return asked;
1607
+ };
1608
+ const wireNewModuleDependencies = async (boundedContextFolder, wireFile, customWiring)=>{
1609
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
1610
+ if (consumer) await promptDependencies(boundedContextFolder, consumer, consumer.implementations, customWiring);
1611
+ };
1612
+ const wireDependency = async (boundedContextFolder)=>{
1613
+ const modules = findWiredModules(boundedContextFolder.path);
1614
+ if (!modules.length) return void console.log('No wired modules here yet.');
1615
+ const { module: consumer, implementation } = await prompts_select({
1616
+ message: 'Module:',
1617
+ choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
1618
+ const type = wiring_implementationType(x, implementation);
1619
+ return {
1620
+ module: x,
1621
+ label: type ? `${x.typeName} (${type})` : x.typeName,
1622
+ implementation
1623
+ };
1624
+ }))),
1625
+ pageSize: groupedPageSize,
1626
+ loop: false
1627
+ });
1628
+ if (!await promptDependencies(boundedContextFolder, consumer, [
1629
+ implementation
1630
+ ])) console.log('No dependencies available for this module.');
1631
+ };
1632
+ const promptEndpointHandler = async (boundedContextFolder)=>{
1633
+ const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
1634
+ 'queries',
1635
+ 'commands',
1636
+ 'use-cases'
1637
+ ].includes(x.kind)).map((x)=>({
1638
+ module: x,
1639
+ label: x.typeName
1640
+ }));
1641
+ return handlers.length ? (await prompts_select({
1642
+ message: 'Handler:',
1643
+ choices: groupedChoices(handlers),
1644
+ pageSize: groupedPageSize,
1645
+ loop: false
1646
+ })).module : void 0;
1647
+ };
1648
+ const createPresentationService = (boundedContextFolder, name, classFile)=>{
1649
+ const naming = new UnknownFormatNaming(name);
1650
+ const className = `${naming.ClassName}PresentationService`;
1651
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
1652
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1653
+ const wiringFolder = boundedContextFolder.subitem([
1654
+ 'wiring',
1655
+ 'presentation-services'
1656
+ ]);
1657
+ const presentationServicesFolder = boundedContextFolder.subitem([
1658
+ 'presentation',
1659
+ 'services'
1660
+ ]);
1661
+ presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, classFile?.(className) ?? `
1662
+ export class ${className} {
1663
+
1664
+ }
1665
+ `.trim());
1666
+ if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
1667
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
1668
+ ${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
1669
+ import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
1670
+
1671
+ let ${naming.variableName}PresentationService: ${naming.ClassName}PresentationService
1672
+
1673
+ beforeEach(() => {
1674
+ ${naming.variableName}PresentationService = ${withWiring ? `wire${naming.ClassName}PresentationService()` : `new ${naming.ClassName}PresentationService()`}
1675
+ })
1676
+
1677
+ describe('${naming.withSpaces}', () => {
1678
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
1679
+ expect(${naming.variableName}PresentationService).toBeDefined()
1680
+ })
1681
+ })
1682
+ `.trim());
1683
+ if (withWiring) return wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1684
+ import { wireClass } from '@domain-first/wire'
1685
+ import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
1686
+
1687
+ export const wire${naming.ClassName}PresentationService = wireClass(
1688
+ ${naming.ClassName}PresentationService,
1689
+ []
1690
+ )
1691
+ `.trim());
1692
+ };
1693
+ const scaffoldNewPresentationService = async (boundedContextFolder)=>{
1694
+ const name = await input({
1695
+ message: 'Name: '
1696
+ });
1697
+ const wireFile = createPresentationService(boundedContextFolder, name);
1698
+ if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
1699
+ };
1700
+ const rest_endpoint_generator_name = 'rest-endpoint-generator';
1701
+ const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false } = {})=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>{
1702
+ const adapter = withNextAdapter ? 'nextAdapter' : 'adapter';
1703
+ return `
1704
+ import {
1705
+ ${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
1706
+ createEndpoint,
1707
+ invalidRequest
1708
+ } from '@domain-first/handlers-rest'
1709
+ ${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
1710
+ /**
1711
+ * The adapter of your HTTP framework.
1712
+ */
1713
+ const adapter = undefined as unknown as Adapter<any[], any>`}
1714
+
1715
+ export class ${className} {
1716
+ get withoutGuards(): EndpointGenerator {
1717
+ return createEndpoint({
1718
+ errors: [invalidRequest()]
1719
+ })(${adapter}) as EndpointGenerator
1720
+ }
1721
+ }
1722
+ `.trim();
1723
+ });
1724
+ const findRestEndpointGenerator = (sharedFolder)=>{
1725
+ const typeFile = node_path.join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
1726
+ if (!new File(typeFile).exists) return;
1727
+ return {
1728
+ typeName: 'RestEndpointGeneratorPresentationService',
1729
+ typeFile,
1730
+ wireName: 'wireRestEndpointGeneratorPresentationService',
1731
+ wireFile: node_path.join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
1732
+ };
1733
+ };
1734
+ const hasDependency = (root, name)=>{
1735
+ const manifestFile = new File(node_path.join(root, 'package.json'));
1736
+ if (!manifestFile.exists) return false;
1737
+ const manifest = JSON.parse(manifestFile.data);
1738
+ return [
1739
+ manifest.dependencies,
1740
+ manifest.devDependencies,
1741
+ manifest.optionalDependencies
1742
+ ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
1743
+ };
1744
+ const initializeUseCase = async ()=>{
1745
+ const nextSteps = [];
1746
+ const rootFolderName = await input({
1747
+ message: 'Root folder (use "/" for inner folders):',
1748
+ default: 'src'
1749
+ });
1750
+ const domainFirstPackages = await prompts_checkbox({
1751
+ message: '@domain-first packages',
1752
+ choices: [
1753
+ '@domain-first/types',
1754
+ '@domain-first/errors',
1755
+ '@domain-first/handlers',
1756
+ '@domain-first/wire',
1757
+ '@domain-first/handlers-rest'
1758
+ ]
1759
+ });
1760
+ const withNextAdapter = domainFirstPackages.includes('@domain-first/handlers-rest') && hasDependency(new ProjectRoot().path, 'next') && await prompts_confirm({
1761
+ message: 'Use Next adapter for REST endpoints'
1762
+ });
1763
+ const defaultPersistenceLayerImplementation = await input({
1764
+ message: 'Default persistence layer implementation:'
1765
+ });
1766
+ const withInMemoryDb = await prompts_confirm({
1767
+ message: 'Scaffold in-memory DB for test implementations'
1768
+ });
1769
+ const useReact = await prompts_confirm({
1770
+ message: 'Use React'
1771
+ });
1772
+ let storybookFramework;
1773
+ const withStorybook = useReact ? await prompts_confirm({
1774
+ message: 'Use Storybook'
1775
+ }) : false;
1776
+ if (withStorybook) storybookFramework = await input({
1777
+ message: 'Storybook framework package:',
1778
+ default: '@storybook/react-vite'
1779
+ });
1780
+ let testingLibrary;
1781
+ const withTests = await prompts_confirm({
1782
+ message: 'Scaffold unit tests'
1783
+ });
1784
+ if (withTests) testingLibrary = await input({
1785
+ message: 'Unit testing library:',
1786
+ default: 'vitest'
1787
+ });
1788
+ ConfigFile.write({
1789
+ rootFolder: rootFolderName,
1790
+ domainFirstPackages,
1791
+ defaultPersistenceLayerImplementation,
1792
+ withInMemoryDb,
1793
+ useReact,
1794
+ storybookFramework,
1795
+ testingLibrary
1796
+ });
1797
+ const { path } = new ProjectRoot();
1798
+ const rootFolder = new Folder(path);
1799
+ if (domainFirstPackages.includes('@domain-first/wire')) rootFolder.subitem([
1800
+ rootFolderName,
1801
+ 'shared',
1802
+ 'wiring'
1803
+ ]).createFile('env-branched-wire.ts', `
1804
+ import { branchedWire } from '@domain-first/wire'
1805
+
1806
+ export const envBranchedWire = branchedWire(() => {
1807
+ return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1808
+ });
1809
+ `.trim());
1810
+ if (withInMemoryDb) scaffoldInMemoryDb(rootFolder.subitem([
1811
+ rootFolderName,
1812
+ 'shared'
1813
+ ]));
1814
+ if (domainFirstPackages.includes('@domain-first/errors')) rootFolder.subitem([
1815
+ rootFolderName,
1816
+ 'shared'
1817
+ ]).subitem([
1818
+ 'domain',
1819
+ 'errors'
1820
+ ]).createFile('index.ts', `
1821
+ import { errorNamespace } from '@domain-first/errors'
1822
+
1823
+ export const SharedErrors = errorNamespace('shared')
1824
+ `.trim());
1825
+ if (domainFirstPackages.includes('@domain-first/handlers-rest')) {
1826
+ scaffoldRestEndpointGenerator(rootFolder.subitem([
1827
+ rootFolderName,
1828
+ 'shared'
1829
+ ]), {
1830
+ withNextAdapter
1831
+ });
1832
+ if (withNextAdapter && !hasDependency(path, '@domain-first/handlers-next')) nextSteps.push('npm i @domain-first/handlers-next');
1833
+ }
1834
+ return nextSteps;
1835
+ };
1836
+ const ignoredFolders = new Set([
1837
+ 'node_modules',
1838
+ '.git',
1839
+ '.next',
1840
+ 'dist',
1841
+ 'build',
1842
+ 'out',
1843
+ 'coverage',
1844
+ 'storybook-static'
1845
+ ]);
1846
+ const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
1847
+ const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1848
+ const walk = (folder)=>{
1849
+ if (!node_fs.existsSync(folder)) return [];
1850
+ return node_fs.readdirSync(folder, {
1851
+ withFileTypes: true
1852
+ }).flatMap((entry)=>{
1853
+ const entryPath = node_path.join(folder, entry.name);
1854
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : walk(entryPath);
1855
+ return entry.isFile() ? [
1856
+ entryPath
1857
+ ] : [];
1858
+ });
1859
+ };
1860
+ const toPosix = (value)=>value.split(node_path.sep).join('/');
1861
+ const nestedName = (folders, fileBase)=>{
1862
+ const prefix = `${folders.join('-')}-`;
1863
+ const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
1864
+ return [
1865
+ ...folders,
1866
+ last
1867
+ ].join('/');
1868
+ };
1869
+ const declaredClassName = (filePath, suffix, name)=>{
1870
+ const content = node_fs.readFileSync(filePath, 'utf8');
1871
+ const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
1872
+ return declared ?? new NestedName(name).ClassName;
1873
+ };
1874
+ const findReactModules = (reactFolder, kind)=>{
1875
+ const modules = 'page' === kind ? walk(node_path.join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
1876
+ const folders = node_path.relative(node_path.join(reactFolder, 'pages'), node_path.dirname(file)).split(node_path.sep).filter((segment)=>!!segment);
1877
+ const fileBase = node_path.basename(file, '-page.tsx');
1878
+ const name = nestedName(folders, fileBase);
1879
+ return {
1880
+ kind,
1881
+ name,
1882
+ path: file,
1883
+ fileBase,
1884
+ ClassName: declaredClassName(file, 'Page', name)
1885
+ };
1886
+ }) : walk(node_path.join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
1887
+ const folder = node_path.dirname(file);
1888
+ const name = toPosix(node_path.relative(node_path.join(reactFolder, 'widgets'), folder));
1889
+ return {
1890
+ kind,
1891
+ name,
1892
+ path: folder,
1893
+ fileBase: node_path.basename(file, '-widget.tsx'),
1894
+ ClassName: declaredClassName(file, 'Widget', name)
1895
+ };
1896
+ });
1897
+ return modules.sort((a, b)=>a.name.localeCompare(b.name));
1898
+ };
1899
+ const targetPath = (reactFolder, module, rawName)=>{
1900
+ const { folders, folderName, fileName } = new NestedName(rawName);
1901
+ return 'page' === module.kind ? node_path.join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : node_path.join(reactFolder, 'widgets', ...folders, folderName);
1902
+ };
1903
+ const validateMove = (reactFolder, module, rawName)=>{
1904
+ const nameError = NestedName.validate(rawName);
1905
+ if (true !== nameError) return nameError;
1906
+ const target = targetPath(reactFolder, module, rawName);
1907
+ if (target !== module.path && node_fs.existsSync(target)) return `${node_path.relative(reactFolder, target)} already exists`;
1908
+ if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
1909
+ return true;
1910
+ };
1911
+ const readAliases = (projectRoot)=>{
1912
+ const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
1913
+ if (!node_fs.existsSync(tsconfig)) return [];
1914
+ try {
1915
+ const { compilerOptions = {} } = JSON.parse(stripJsonComments(node_fs.readFileSync(tsconfig, 'utf8')));
1916
+ const base = node_path.resolve(projectRoot, compilerOptions.baseUrl ?? '.');
1917
+ return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
1918
+ prefix: pattern.slice(0, -1),
1919
+ target: node_path.resolve(base, target.slice(0, -1))
1920
+ }));
1921
+ } catch {
1922
+ return [];
1923
+ }
1924
+ };
1925
+ const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
1926
+ const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
1927
+ const importPaths = (file)=>{
1928
+ const withoutExtension = file.replace(codeExtension, '');
1929
+ return 'index' === node_path.basename(withoutExtension) ? [
1930
+ withoutExtension,
1931
+ node_path.dirname(withoutExtension)
1932
+ ] : [
1933
+ withoutExtension
1934
+ ];
1935
+ };
1936
+ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
1937
+ const newName = new NestedName(rawName);
1938
+ const target = targetPath(reactFolder, module, rawName);
1939
+ const newClassName = newName.ClassName;
1940
+ const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
1941
+ const oldFolder = 'page' === module.kind ? node_path.dirname(module.path) : module.path;
1942
+ const newFolder = 'page' === module.kind ? node_path.dirname(target) : target;
1943
+ const ownsPath = (candidate)=>'page' === module.kind ? node_path.dirname(candidate) === oldFolder && new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`).test(node_path.basename(candidate)) : candidate === oldFolder || candidate.startsWith(`${oldFolder}${node_path.sep}`);
1944
+ const movedPath = (candidate)=>{
1945
+ if (!ownsPath(candidate)) return;
1946
+ const segments = node_path.relative(oldFolder, candidate).split(node_path.sep);
1947
+ const last = segments.length - 1;
1948
+ segments[last] = renameFile(segments[last]);
1949
+ return node_path.join(newFolder, ...segments);
1950
+ };
1951
+ const moduleFiles = 'page' === module.kind ? node_fs.readdirSync(oldFolder).map((name)=>node_path.join(oldFolder, name)).filter((file)=>node_fs.statSync(file).isFile() && ownsPath(file)) : walk(oldFolder);
1952
+ const moves = new Map(moduleFiles.map((file)=>[
1953
+ file,
1954
+ movedPath(file) ?? file
1955
+ ]));
1956
+ const aliases = readAliases(projectRoot);
1957
+ const resolve = (specifier, fromFile)=>{
1958
+ if (specifier.startsWith('.')) return {
1959
+ resolved: node_path.resolve(node_path.dirname(fromFile), specifier),
1960
+ alias: void 0
1961
+ };
1962
+ const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
1963
+ return alias ? {
1964
+ resolved: node_path.resolve(alias.target, specifier.slice(alias.prefix.length)),
1965
+ alias
1966
+ } : void 0;
1967
+ };
1968
+ const specifierFor = (fromFile, toPath, alias)=>{
1969
+ const aliased = alias && toPosix(node_path.relative(alias.target, toPath));
1970
+ if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
1971
+ const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toPath));
1972
+ return relative.startsWith('.') ? relative : `./${relative}`;
1973
+ };
1974
+ const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
1975
+ const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
1976
+ const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
1977
+ const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
1978
+ const newTitle = [
1979
+ 'Widgets',
1980
+ ...newName.classNameSegments
1981
+ ].join('/');
1982
+ const codeFiles = new Map(walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
1983
+ file,
1984
+ node_fs.readFileSync(file, 'utf8')
1985
+ ]));
1986
+ const barrels = new Set();
1987
+ const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
1988
+ for(let found = true; found;){
1989
+ found = false;
1990
+ for (const [file, content] of codeFiles){
1991
+ if (moves.has(file) || isBarrel(file)) continue;
1992
+ const reExportsModule = [
1993
+ ...content.matchAll(reExportPattern)
1994
+ ].some(([, , specifier])=>{
1995
+ const resolution = resolve(specifier, file);
1996
+ return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
1997
+ });
1998
+ if (reExportsModule) {
1999
+ for (const importPath of importPaths(file))barrels.add(importPath);
2000
+ found = true;
2001
+ }
2002
+ }
2003
+ }
2004
+ const rewrite = (content, oldFile, newFile)=>{
2005
+ let referencesModule = false;
2006
+ const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
2007
+ const resolution = resolve(specifier, oldFile);
2008
+ if (!resolution) return match;
2009
+ const moved = movedPath(resolution.resolved);
2010
+ if (moved || isBarrel(resolution.resolved)) referencesModule = true;
2011
+ if (!moved && oldFile === newFile) return match;
2012
+ const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
2013
+ return `${keyword}${quote}${next}${quote}`;
2014
+ });
2015
+ if (!referencesModule && !moves.has(oldFile)) return content;
2016
+ const renamed = rewritten.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
2017
+ return moves.has(oldFile) && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
2018
+ };
2019
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, reactFolder);
2020
+ const updated = [];
2021
+ for (const [file, content] of codeFiles){
2022
+ const newFile = moves.get(file);
2023
+ const next = rewrite(content, file, newFile ?? file);
2024
+ if (newFile && newFile !== file) {
2025
+ new File(newFile).data = next;
2026
+ new File(file).delete(reactFolder);
2027
+ } else if (next !== content) {
2028
+ new File(file).update(next);
2029
+ if (!newFile) updated.push(file);
2030
+ }
2031
+ }
2032
+ return {
2033
+ moves: [
2034
+ ...moves
2035
+ ].filter(([from, to])=>from !== to),
2036
+ updated
2037
+ };
2038
+ };
2039
+ const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
2040
+ const reactFolder = presentationReactFolder.path;
2041
+ const modules = findReactModules(reactFolder, kind);
2042
+ if (!modules.length) return void console.log(`No ${kind}s generated by df-scaffold were found.`);
2043
+ const module = await prompts_select({
2044
+ message: 'page' === kind ? 'Page:' : 'Widget:',
2045
+ choices: modules.map((value)=>({
2046
+ name: value.name,
2047
+ value,
2048
+ description: node_path.relative(reactFolder, value.path)
2049
+ }))
2050
+ });
2051
+ const name = await input({
2052
+ message: 'New name (folders split by "/"):',
2053
+ default: module.name,
2054
+ validate: (value)=>validateMove(reactFolder, module, value)
2055
+ });
2056
+ const root = new ProjectRoot().path;
2057
+ const { moves, updated } = moveReactModule(root, reactFolder, module, name);
2058
+ if (!moves.length && !updated.length) return void console.log('Nothing to change.');
2059
+ const relative = (file)=>node_path.relative(root, file);
2060
+ console.log([
2061
+ 'Files to move:',
2062
+ ...moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
2063
+ ...updated.length ? [
2064
+ 'Files with updated imports:',
2065
+ ...updated.map((file)=>` ${relative(file)}`)
2066
+ ] : []
2067
+ ].join('\n'));
2068
+ if (!await prompts_confirm({
2069
+ message: 'Apply?',
2070
+ default: true
2071
+ })) {
2072
+ discardPendingChanges();
2073
+ console.log('Cancelled: nothing was written.');
2074
+ }
2075
+ };
2076
+ const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
2077
+ const aggregateName = await input({
2078
+ message: 'Aggregate name:'
2079
+ });
2080
+ const aggregateNaming = new UnknownFormatNaming(aggregateName);
2081
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
2082
+ const withRepository = await prompts_confirm({
2083
+ message: 'With Repository'
2084
+ });
2085
+ const aggregatesFolder = boundedContextFolder.subitem([
2086
+ 'domain',
2087
+ 'aggregates',
2088
+ aggregateName
2089
+ ]);
2090
+ const withTypes = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/types');
2091
+ aggregatesFolder.createFile(`${aggregateNaming.fileName}.aggregate-root.ts`, withTypes ? `
2092
+ import { domainType } from '@domain-first/types'
2093
+
2094
+ export class ${aggregateNaming.ClassName} extends domainType() {
2095
+
2096
+ }`.trim() : `export class ${aggregateNaming.ClassName} {}`);
2097
+ const barrelFile = aggregatesFolder.createFile("index.ts", `export * from './${aggregateNaming.fileName}.aggregate-root'`);
2098
+ if (scaffoldUnitTests) aggregatesFolder.createFile(`${aggregateNaming.fileName}.aggregate-root.spec.ts`, `
2099
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2100
+ import { ${aggregateNaming.ClassName} } from './${aggregateNaming.fileName}.aggregate-root'
2101
+
2102
+ let ${aggregateNaming.variableName}: ${aggregateNaming.ClassName}
2103
+
2104
+ beforeEach(() => {
2105
+ ${aggregateNaming.variableName} = ${withTypes ? `${aggregateNaming.ClassName}.of({})` : `new ${aggregateNaming.ClassName}()`}
2106
+ })
2107
+
2108
+ describe('${aggregateNaming.withSpaces}', () => {
2109
+ test('can be instantiated via ${withTypes ? 'of' : 'constructor'}', () => {
2110
+ expect(${aggregateNaming.variableName}).toBeDefined()
2111
+ })
2112
+ })
2113
+ `.trim());
2114
+ if (withRepository) {
2115
+ aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.ts`, `export abstract class ${aggregateNaming.ClassName}Repository { }`);
2116
+ barrelFile.addLine(`export * from './${aggregateNaming.fileName}-repository'`);
2117
+ const infrastructureImplementationType = await input({
2118
+ message: 'Repository infrastructure implementation type:',
2119
+ default: ConfigFile.Instance.data.defaultPersistenceLayerImplementation
2120
+ });
2121
+ let addTestImplementation = false;
2122
+ let testImplementationType = '';
2123
+ addTestImplementation = await prompts_confirm({
2124
+ message: 'Add a test implementation for Repository'
2125
+ });
2126
+ if (addTestImplementation) testImplementationType = await input({
2127
+ message: 'Test Repository infrastructure implementation type:',
2128
+ default: 'in-memory'
2129
+ });
2130
+ const infrastructureRepositoriesFolder = boundedContextFolder.subitem([
2131
+ 'infrastructure',
2132
+ 'repositories'
2133
+ ]);
2134
+ const implementationTypes = [
2135
+ infrastructureImplementationType,
2136
+ testImplementationType
2137
+ ].filter((x)=>!!x);
2138
+ for (const implementation of implementationTypes){
2139
+ const naming = new UnknownFormatNaming(implementation);
2140
+ const repositoryFolder = infrastructureRepositoriesFolder.subitem([
2141
+ naming.fileName
2142
+ ]);
2143
+ const repositoryFileName = `${naming.fileName}-${aggregateName}-repository.ts`;
2144
+ if (usesInMemoryDb(implementation) && !ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2145
+ const section = addInMemoryDbSection(aggregateNaming, aggregatesFolder.path);
2146
+ repositoryFolder.createFile(repositoryFileName, `
2147
+ ${inMemoryDbTypeImport(repositoryFolder.subitem([
2148
+ repositoryFileName
2149
+ ]).path)}
2150
+ import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2151
+
2152
+ export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
2153
+ ${inMemoryDbSectionMembers(section, false)}
2154
+ }
2155
+ `.trim());
2156
+ continue;
2157
+ }
2158
+ repositoryFolder.createFile(repositoryFileName, `
2159
+ import { ${aggregateNaming.ClassName}Repository } from '../../../domain/aggregates/${aggregateName}'
2160
+
2161
+ export class ${naming.ClassName}${aggregateNaming.ClassName}Repository implements ${aggregateNaming.ClassName}Repository {
2162
+ constructor() {}
2163
+ }
2164
+
2165
+ `.trim());
2166
+ }
2167
+ if (scaffoldUnitTests) {
2168
+ const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
2169
+ const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
2170
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2171
+ ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `import { wire${aggregateNaming.ClassName}Repository } from '../../../wiring/repositories/wire-${aggregateNaming.fileName}-repository'
2172
+ 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'
2173
+
2174
+ type ${aggregateNaming.ClassName}Repository = ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`}
2175
+
2176
+ let ${aggregateNaming.variableName}Repository: ${aggregateNaming.ClassName}Repository
2177
+
2178
+ beforeEach(() => {
2179
+ ${aggregateNaming.variableName}Repository = ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `wire${aggregateNaming.ClassName}Repository()` : `new ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository()`}
2180
+ })
2181
+
2182
+ describe('${aggregateNaming.withSpaces} repository', () => {
2183
+ test('can be ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? 'wired' : 'created via constructor'}', () => {
2184
+ expect(${aggregateNaming.variableName}Repository).toBeDefined()
2185
+ })
2186
+ })
2187
+ `.trim());
2188
+ if (!ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') && usesInMemoryDb(infrastructureImplementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`);
2189
+ }
2190
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2191
+ const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
2192
+ const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
2193
+ const wireFile = boundedContextFolder.subitem([
2194
+ 'wiring',
2195
+ 'repositories'
2196
+ ]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
2197
+ import { wireClass } from '@domain-first/wire'
2198
+ import { envBranchedWire } from '../../../../shared/wiring/env-branched-wire'
2199
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${aggregateNaming.ClassName}Repository } from '../../infrastructure/repositories/${fileName}/${fileName}-${aggregateNaming.fileName}-repository'`).join('\n')}
2200
+
2201
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${aggregateNaming.ClassName}Repository, [])`).join('\n\n')}
2202
+
2203
+ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
2204
+ test: wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation,
2205
+ development: wire${implementationNaming.ClassName}Implementation,
2206
+ production: wire${implementationNaming.ClassName}Implementation
2207
+ })
2208
+ `.trim());
2209
+ await wireNewModuleDependencies(boundedContextFolder, wireFile, (implementation, dependency)=>{
2210
+ if (!isInMemoryDb(dependency)) return false;
2211
+ keepInMemoryDbSection(new File(implementation.file), addInMemoryDbSection(aggregateNaming, aggregatesFolder.path));
2212
+ wireInMemoryDb(wireFile, implementation.className);
2213
+ return true;
2214
+ });
2215
+ }
2216
+ }
2217
+ };
2218
+ const scaffoldNewApplicationPort = async (boundedContextFolder)=>{
2219
+ const name = await input({
2220
+ message: 'Name: '
2221
+ });
2222
+ const naming = new UnknownFormatNaming(name);
2223
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
2224
+ const wiringFolder = boundedContextFolder.subitem([
2225
+ 'wiring',
2226
+ 'application-ports'
2227
+ ]);
2228
+ const applicationPortsFolder = boundedContextFolder.subitem([
2229
+ 'application',
2230
+ 'ports'
2231
+ ]);
2232
+ applicationPortsFolder.createFile(`${naming.fileName}.ts`, `
2233
+ export abstract class ${naming.ClassName} {
2234
+
2235
+ }
2236
+ `.trim());
2237
+ const implementationType = await input({
2238
+ message: 'Adapter implementation type:',
2239
+ default: 'api'
2240
+ });
2241
+ const addTestImplementation = await prompts_confirm({
2242
+ message: 'With test implementation'
2243
+ });
2244
+ let testImplementationType = '';
2245
+ if (addTestImplementation) testImplementationType = await input({
2246
+ message: 'Test adapter implementation type:',
2247
+ default: 'mock'
2248
+ });
2249
+ const infrastructureFolder = boundedContextFolder.subitem([
2250
+ 'infrastructure',
2251
+ 'application-adapters'
2252
+ ]);
2253
+ const implementationTypes = [
2254
+ implementationType,
2255
+ testImplementationType
2256
+ ].filter((x)=>!!x);
2257
+ for (const implementation of implementationTypes){
2258
+ const currentNaming = new UnknownFormatNaming(`${implementation}-${naming.fileName}`);
2259
+ infrastructureFolder.subitem([
2260
+ implementation
2261
+ ]).createFile(`${currentNaming.fileName}.ts`, `
2262
+ import { ${naming.ClassName} } from '../../../application/ports/${naming.fileName}'
2263
+
2264
+ export class ${currentNaming.ClassName} extends ${naming.ClassName} {
2265
+
2266
+ }
2267
+ `.trim());
2268
+ }
2269
+ if (scaffoldUnitTests) {
2270
+ const implementationNaming = new UnknownFormatNaming(implementationType);
2271
+ applicationPortsFolder.createFile(`${naming.fileName}.spec.ts`, `
2272
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2273
+ ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `import { type ${naming.ClassName} } from './${naming.fileName}'
2274
+ 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}'
2275
+
2276
+ type ${naming.ClassName} = ${implementationNaming.ClassName}${naming.ClassName}`}
2277
+
2278
+ let ${naming.variableName}: ${naming.ClassName}
2279
+
2280
+ beforeEach(() => {
2281
+ ${naming.variableName} = ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? `wire${naming.ClassName}()` : `new ${implementationNaming.ClassName}${naming.ClassName}()`}
2282
+ })
2283
+
2284
+ describe('${naming.withSpaces}', () => {
2285
+ test('can be ${ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? 'wired' : 'created via constructor'}', () => {
2286
+ expect(${naming.variableName}).toBeDefined()
2287
+ })
2288
+ })
2289
+ `.trim());
2290
+ }
2291
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2292
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
2293
+ import { wireClass } from '@domain-first/wire'
2294
+ import { envBranchedWire } from '../../../${'shared' === boundedContextFolder.name ? '' : '../'}shared/wiring/env-branched-wire'
2295
+ ${implementationTypes.map((x)=>({
2296
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
2297
+ implementation: x
2298
+ })).map(({ naming: { ClassName, fileName }, implementation })=>`import { ${ClassName} } from '../../infrastructure/application-adapters/${implementation}/${fileName}'`).join('\n')}
2299
+
2300
+ ${implementationTypes.map((x)=>({
2301
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
2302
+ implementation: x
2303
+ })).map(({ naming: { ClassName }, implementation })=>`const wire${new UnknownFormatNaming(implementation).ClassName}Implementation = wireClass(${ClassName}, [])`).join('\n\n')}
2304
+
2305
+ export const wire${naming.ClassName} = envBranchedWire({
2306
+ test: wire${new UnknownFormatNaming(`${implementationTypes.at(-1)}-implementation`).ClassName},
2307
+ development: wire${new UnknownFormatNaming(`${implementationTypes.at(0)}-implementation`).ClassName},
2308
+ production: wire${new UnknownFormatNaming(`${implementationTypes.at(0)}-implementation`).ClassName}
2309
+ })
2310
+
2311
+ `.trim());
2312
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
2313
+ }
2314
+ };
2315
+ const scaffoldNewApplicationService = async (boundedContextFolder)=>{
2316
+ const name = await input({
2317
+ message: 'Name: '
2318
+ });
2319
+ const naming = new UnknownFormatNaming(name);
2320
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
2321
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2322
+ const wiringFolder = boundedContextFolder.subitem([
2323
+ 'wiring',
2324
+ 'application-services'
2325
+ ]);
2326
+ const applicationServicesFolder = boundedContextFolder.subitem([
2327
+ 'application',
2328
+ 'services'
2329
+ ]);
2330
+ applicationServicesFolder.createFile(`${naming.fileName}-application-service.ts`, `
2331
+ export class ${naming.ClassName}ApplicationService {
2332
+
2333
+ }
2334
+ `.trim());
2335
+ if (scaffoldUnitTests) applicationServicesFolder.createFile(`${naming.fileName}-application-service.spec.ts`, `
2336
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2337
+ ${withWiring ? `import { type ${naming.ClassName}ApplicationService } from './${naming.fileName}-application-service'
2338
+ import { wire${naming.ClassName}ApplicationService } from '../../wiring/application-services/wire-${naming.fileName}-application-service'` : `import { ${naming.ClassName}ApplicationService } from './${naming.fileName}-application-service'`}
2339
+
2340
+ let ${naming.variableName}ApplicationService: ${naming.ClassName}ApplicationService
2341
+
2342
+ beforeEach(() => {
2343
+ ${naming.variableName}ApplicationService = ${withWiring ? `wire${naming.ClassName}ApplicationService()` : `new ${naming.ClassName}ApplicationService()`}
2344
+ })
2345
+
2346
+ describe('${naming.withSpaces}', () => {
2347
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
2348
+ expect(${naming.variableName}ApplicationService).toBeDefined()
2349
+ })
2350
+ })
2351
+ `.trim());
2352
+ if (withWiring) {
2353
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-application-service.ts`, `
2354
+ import { wireClass } from '@domain-first/wire'
2355
+ import { ${naming.ClassName}ApplicationService } from '../../application/services/${naming.fileName}-application-service'
2356
+
2357
+ export const wire${naming.ClassName}ApplicationService = wireClass(
2358
+ ${naming.ClassName}ApplicationService,
2359
+ []
2360
+ )
2361
+ `.trim());
2362
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
2363
+ }
2364
+ };
2365
+ const scaffoldNewBoundedContextUseCase = async ()=>{
2366
+ const name = await input({
2367
+ message: 'Name:',
2368
+ validate: (x)=>!!x.length
2369
+ });
2370
+ const { path } = new ProjectRoot();
2371
+ const rootFolder = new Folder(path);
2372
+ const folder = rootFolder.subitem([
2373
+ ConfigFile.Instance.data.rootFolder,
2374
+ 'bounded-contexts',
2375
+ name
2376
+ ]);
2377
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/errors')) folder.subitem([
2378
+ 'domain',
2379
+ 'errors'
2380
+ ]).createFile('index.ts', `
2381
+ import { errorNamespace } from '@domain-first/errors'
2382
+
2383
+ export const ${new UnknownFormatNaming(name).ClassName}Errors = errorNamespace('${name}')
2384
+ `.trim());
2385
+ folder.createIfNotExisted();
2386
+ };
2387
+ const scaffoldNewCommand = async (boundedContextFolder)=>{
2388
+ const commandsFolder = boundedContextFolder.subitem([
2389
+ 'application',
2390
+ 'commands'
2391
+ ]);
2392
+ const infrastructureFolder = boundedContextFolder.subitem([
2393
+ 'infrastructure',
2394
+ 'commands'
2395
+ ]);
2396
+ const commandName = await input({
2397
+ message: 'Name: '
2398
+ });
2399
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
2400
+ const naming = new UnknownFormatNaming(commandName);
2401
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2402
+ const implementationType = await input({
2403
+ message: 'Command infrastructure implementation type:',
2404
+ default: ConfigFile.Instance.data.defaultPersistenceLayerImplementation
2405
+ });
2406
+ let addTestImplementation = false;
2407
+ let testImplementationType = '';
2408
+ addTestImplementation = await prompts_confirm({
2409
+ message: 'Add a test implementation for Command'
2410
+ });
2411
+ if (addTestImplementation) testImplementationType = await input({
2412
+ message: 'Test Command infrastructure implementation type:',
2413
+ default: 'in-memory'
2414
+ });
2415
+ const implementationTypes = [
2416
+ implementationType,
2417
+ testImplementationType
2418
+ ].filter((x)=>!!x);
2419
+ for (const implementation of implementationTypes){
2420
+ const formatNaming = new UnknownFormatNaming(implementation);
2421
+ const implementationFile = infrastructureFolder.subitem([
2422
+ formatNaming.fileName
2423
+ ]).createFile(`${formatNaming.fileName}-${naming.fileName}-command.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2424
+ import { defineHandler } from '@domain-first/handlers'
2425
+ import { ${naming.ClassName}Command } from '../../../application/commands/${naming.fileName}-command'
2426
+
2427
+ export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${naming.ClassName}Command {
2428
+ constructor() {
2429
+ super()
2430
+ }
2431
+
2432
+ handle = defineHandler({
2433
+ inputSchema: ${naming.ClassName}Command.inputSchema,
2434
+ outputSchema: ${naming.ClassName}Command.outputSchema,
2435
+ handler: async (input) => {
2436
+ return {}
2437
+ }
2438
+ })
2439
+ }
2440
+ `.trim() : `
2441
+ import { ${naming.ClassName}Command } from '../../../application/commands/${naming.fileName}-command'
2442
+
2443
+ export class ${formatNaming.ClassName}${naming.ClassName}Command extends ${naming.ClassName}Command {
2444
+ constructor() {
2445
+ super()
2446
+ }
2447
+ }
2448
+ `.trim());
2449
+ if (!withWiring && usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Command`);
2450
+ }
2451
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) commandsFolder.createFile(`${naming.fileName}-command.ts`, `
2452
+ import type { Handler } from '@domain-first/handlers'
2453
+
2454
+ export abstract class ${naming.ClassName}Command {
2455
+ static inputSchema = {}
2456
+ static outputSchema = {}
2457
+
2458
+ abstract handle: Handler<typeof ${naming.ClassName}Command.inputSchema, typeof ${naming.ClassName}Command.outputSchema>
2459
+ }
2460
+ `.trim());
2461
+ else commandsFolder.createFile(`${naming.fileName}-command.ts`, `
2462
+ export abstract class ${naming.ClassName}Command {
2463
+
2464
+ }`.trim());
2465
+ if (scaffoldUnitTests) {
2466
+ const implementationNaming = new UnknownFormatNaming(implementationType);
2467
+ const specFile = commandsFolder.createFile(`${naming.fileName}-command.spec.ts`, `
2468
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2469
+ ${withWiring ? `import { type ${naming.ClassName}Command } from './${naming.fileName}-command'
2470
+ 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'
2471
+
2472
+ type ${naming.ClassName}Command = ${implementationNaming.ClassName}${naming.ClassName}Command`}
2473
+
2474
+ let ${naming.variableName}Command: ${naming.ClassName}Command
2475
+
2476
+ beforeEach(() => {
2477
+ ${naming.variableName}Command = ${withWiring ? `wire${naming.ClassName}Command()` : `new ${implementationNaming.ClassName}${naming.ClassName}Command()`}
2478
+ })
2479
+
2480
+ describe('${naming.withSpaces} command', () => {
2481
+ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
2482
+ expect(${naming.variableName}Command).toBeDefined()
2483
+ })
2484
+ })
2485
+ `.trim());
2486
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Command`);
2487
+ }
2488
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2489
+ const implementationNaming = new UnknownFormatNaming(implementationType);
2490
+ const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
2491
+ const wireFile = boundedContextFolder.subitem([
2492
+ 'wiring',
2493
+ 'commands'
2494
+ ]).createFile(`wire-${naming.fileName}-command.ts`, `
2495
+ import { wireClass } from '@domain-first/wire'
2496
+ import { envBranchedWire } from '../../../../shared/wiring/env-branched-wire'
2497
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Command } from '../../infrastructure/commands/${fileName}/${fileName}-${naming.fileName}-command'`).join('\n')}
2498
+
2499
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Command, [])`).join('\n\n')}
2500
+
2501
+ export const wire${naming.ClassName}Command = envBranchedWire({
2502
+ test: wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation,
2503
+ development: wire${implementationNaming.ClassName}Implementation,
2504
+ production: wire${implementationNaming.ClassName}Implementation
2505
+ })
2506
+ `.trim());
2507
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
2508
+ }
2509
+ };
2510
+ const noAggregate = 'No aggregate';
2511
+ const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
2512
+ const name = await input({
2513
+ message: 'Name: '
2514
+ });
2515
+ const naming = new UnknownFormatNaming(name);
2516
+ const aggregatesFolder = boundedContextFolder.subitem([
2517
+ 'domain',
2518
+ 'aggregates'
2519
+ ]);
2520
+ const aggregateNames = aggregatesFolder.content.subfolderNames;
2521
+ const aggregate = aggregateNames.length ? await prompts_select({
2522
+ message: 'Aggregate:',
2523
+ choices: [
2524
+ ...aggregateNames,
2525
+ noAggregate
2526
+ ]
2527
+ }) : noAggregate;
2528
+ const kindFolderName = 'entity' === kind ? 'entities' : 'value-objects';
2529
+ const folder = aggregate === noAggregate ? boundedContextFolder.subitem([
2530
+ 'domain',
2531
+ kindFolderName
2532
+ ]) : aggregatesFolder.subitem([
2533
+ aggregate,
2534
+ kindFolderName
2535
+ ]);
2536
+ const fileName = `${naming.fileName}.${kind}`;
2537
+ const withTypes = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/types');
2538
+ folder.createFile(`${fileName}.ts`, withTypes ? `
2539
+ import { domainType } from '@domain-first/types'
2540
+
2541
+ export class ${naming.ClassName} extends domainType() {
2542
+
2543
+ }`.trim() : `export class ${naming.ClassName} {}`);
2544
+ if (aggregate !== noAggregate) aggregatesFolder.subitem([
2545
+ aggregate
2546
+ ]).file('index.ts').addLineIfMissing(`export * from './${kindFolderName}/${fileName}'`);
2547
+ const { testingLibrary } = ConfigFile.Instance.data;
2548
+ if (testingLibrary) folder.createFile(`${fileName}.spec.ts`, `
2549
+ import { describe, test, expect, beforeEach } from '${testingLibrary}'
2550
+ import { ${naming.ClassName} } from './${fileName}'
2551
+
2552
+ let ${naming.variableName}: ${naming.ClassName}
2553
+
2554
+ beforeEach(() => {
2555
+ ${naming.variableName} = ${withTypes ? `${naming.ClassName}.of({})` : `new ${naming.ClassName}()`}
2556
+ })
2557
+
2558
+ describe('${naming.withSpaces}', () => {
2559
+ test('can be instantiated via ${withTypes ? 'of' : 'constructor'}', () => {
2560
+ expect(${naming.variableName}).toBeDefined()
2561
+ })
2562
+ })
2563
+ `.trim());
2564
+ };
2565
+ const scaffoldNewDomainService = async (boundedContextFolder)=>{
2566
+ const portName = await input({
2567
+ message: 'Name:'
2568
+ });
2569
+ const naming = new UnknownFormatNaming(portName);
2570
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
2571
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2572
+ const domainServicesFolder = boundedContextFolder.subitem([
2573
+ 'domain',
2574
+ 'services'
2575
+ ]);
2576
+ domainServicesFolder.createFile(`${naming.fileName}-domain-service.ts`, `
2577
+ export class ${naming.ClassName}DomainService {
2578
+
2579
+ }
2580
+ `.trim());
2581
+ if (scaffoldUnitTests) domainServicesFolder.createFile(`${naming.fileName}-domain-service.spec.ts`, `
2582
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2583
+ ${withWiring ? `import { type ${naming.ClassName}DomainService } from './${naming.fileName}-domain-service'
2584
+ import { wire${naming.ClassName}DomainService } from '../../wiring/domain-services/wire-${naming.fileName}-domain-service'` : `import { ${naming.ClassName}DomainService } from './${naming.fileName}-domain-service'`}
2585
+
2586
+ let ${naming.variableName}DomainService: ${naming.ClassName}DomainService
2587
+
2588
+ beforeEach(() => {
2589
+ ${naming.variableName}DomainService = ${withWiring ? `wire${naming.ClassName}DomainService()` : `new ${naming.ClassName}DomainService()`}
2590
+ })
2591
+
2592
+ describe('${naming.withSpaces}', () => {
2593
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
2594
+ expect(${naming.variableName}DomainService).toBeDefined()
2595
+ })
2596
+ })
2597
+ `.trim());
2598
+ if (withWiring) {
2599
+ const wireFile = boundedContextFolder.subitem([
2600
+ 'wiring',
2601
+ 'domain-services'
2602
+ ]).createFile(`wire-${naming.fileName}-domain-service.ts`, `
2603
+ import { wireClass } from '@domain-first/wire'
2604
+ import { ${naming.ClassName}DomainService } from '../../domain/services/${naming.fileName}-domain-service'
2605
+
2606
+ export const wire${naming.ClassName}DomainService = wireClass(
2607
+ ${naming.ClassName}DomainService,
2608
+ []
2609
+ )
2610
+ `.trim());
2611
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
2612
+ }
2613
+ };
2614
+ const errorNames = (boundedContextFolder)=>{
2615
+ const isShared = boundedContextFolder.path === new Folder(new ProjectRoot().path).subitem([
2616
+ ConfigFile.Instance.data.rootFolder,
2617
+ 'shared'
2618
+ ]).path;
2619
+ return {
2620
+ namespace: (namespaceName)=>`${namespaceName}${isShared ? 'Shared' : ''}Errors`,
2621
+ error: (errorName)=>`${errorName}${isShared ? 'SharedError' : ''}`
2622
+ };
2623
+ };
2624
+ const exportedNamespace = (file, fallback)=>/export\s+const\s+(\w+)\s*=\s*errorNamespace\b/.exec(file.data)?.[1] ?? fallback;
2625
+ const errorClass = (className, namespace, code)=>`export class ${className} extends ${namespace}.define('${code}') {}`;
2626
+ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
2627
+ const currentErrorFolder = boundedContextFolder.subitem([
2628
+ 'domain',
2629
+ 'errors'
2630
+ ]);
2631
+ const names = errorNames(boundedContextFolder);
2632
+ const contextNaming = new UnknownFormatNaming(boundedContextFolder.name);
2633
+ const currentErrorNamespaces = currentErrorFolder.content.fileNames.filter((x)=>'index' !== x);
2634
+ const variants = [
2635
+ 'New error without namespace',
2636
+ ...currentErrorNamespaces.map((x)=>`New error in namespace ${x}`),
2637
+ 'New namespace'
2638
+ ];
2639
+ const selectedVariant = await prompts_select({
2640
+ choices: variants,
2641
+ message: 'Action:'
2642
+ });
2643
+ if ('New error without namespace' === selectedVariant) {
2644
+ const errorName = await input({
2645
+ message: 'Error name:'
2646
+ });
2647
+ const naming = new UnknownFormatNaming(errorName);
2648
+ const indexFile = currentErrorFolder.file('index.ts');
2649
+ indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), exportedNamespace(indexFile, `${contextNaming.ClassName}Errors`), naming.fileName), '\n\n');
2650
+ return;
2651
+ }
2652
+ if ('New namespace' === selectedVariant) {
2653
+ const namespaceName = await input({
2654
+ message: 'Namespace name:'
2655
+ });
2656
+ const { ClassName, fileName } = new UnknownFormatNaming(namespaceName);
2657
+ if (!currentErrorFolder.file(`${fileName}.ts`).exists) currentErrorFolder.createFile(`${fileName}.ts`, `
2658
+ import { errorNamespace } from '@domain-first/errors'
2659
+
2660
+ export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
2661
+ `.trim());
2662
+ currentErrorFolder.file('index.ts').addLineIfMissing(`export * from './${fileName}'`, '\n\n');
2663
+ return;
2664
+ }
2665
+ const namespace = selectedVariant.substring(23);
2666
+ const namespaceNaming = new UnknownFormatNaming(namespace);
2667
+ const errorName = await input({
2668
+ message: 'Error name:'
2669
+ });
2670
+ const { ClassName, fileName } = new UnknownFormatNaming(errorName);
2671
+ const namespaceFile = currentErrorFolder.file(`${namespace}.ts`);
2672
+ namespaceFile.addLineIfMissing(errorClass(names.error(`${namespaceNaming.ClassName}${ClassName}`), exportedNamespace(namespaceFile, names.namespace(namespaceNaming.ClassName)), fileName), '\n\n');
2673
+ };
2674
+ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
2675
+ const restPresentationFolder = boundedContextFolder.subitem([
2676
+ 'presentation',
2677
+ 'rest'
2678
+ ]);
2679
+ const controllers = restPresentationFolder.content.subfolderNames;
2680
+ let controller = await prompts_select({
2681
+ message: 'Controller: ',
2682
+ choices: [
2683
+ ...controllers,
2684
+ 'New controller'
2685
+ ]
2686
+ });
2687
+ if ('New controller' === controller) {
2688
+ controller = await input({
2689
+ message: 'Name: '
2690
+ });
2691
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2692
+ boundedContextFolder.subitem([
2693
+ 'wiring',
2694
+ 'presentation',
2695
+ 'rest'
2696
+ ]).file('index.ts').addLine(`export * from './${controller}'`);
2697
+ const sharedRestFolder = boundedContextFolder.subitem([
2698
+ '..',
2699
+ '..',
2700
+ 'presentation',
2701
+ 'rest'
2702
+ ]);
2703
+ sharedRestFolder.file('wires.ts').addLine(`export * from '../../bounded-contexts/${boundedContextFolder.name}/wiring/presentation/rest/${controller}'`);
2704
+ if (!sharedRestFolder.file('index.ts').exists) sharedRestFolder.createFile('index.ts', `
2705
+ import * as wires from './wires'
2706
+
2707
+ const restWires = Object.values(wires)
2708
+
2709
+ export const restHandlers = restWires.map(x => x().handle)
2710
+ `.trim());
2711
+ }
2712
+ }
2713
+ const method = await prompts_select({
2714
+ message: 'Method:',
2715
+ choices: [
2716
+ 'get',
2717
+ 'post',
2718
+ 'patch',
2719
+ 'delete',
2720
+ 'put'
2721
+ ]
2722
+ });
2723
+ const routeSegments = (await input({
2724
+ message: 'Relative path (split by "/"):'
2725
+ })).split('/').filter((x)=>!!x);
2726
+ const pathParameterAsName = (segment)=>segment.startsWith(':') ? `_${segment.slice(1)}_` : segment;
2727
+ const controllerFolder = restPresentationFolder.subitem([
2728
+ controller
2729
+ ]);
2730
+ const endpointFolder = controllerFolder.subitem(routeSegments.map(pathParameterAsName));
2731
+ const nameBase = `${controller}-${routeSegments.length ? `${routeSegments.map(pathParameterAsName).join('-')}-` : ''}${method}-endpoint`;
2732
+ const endpointClassName = [
2733
+ controller,
2734
+ ...routeSegments,
2735
+ method,
2736
+ 'endpoint'
2737
+ ].map((segment)=>segment.startsWith(':') ? pathParameterAsName(segment) : new UnknownFormatNaming(segment).ClassName).join('');
2738
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2739
+ const endpointGenerator = findRestEndpointGenerator(boundedContextFolder.subitem([
2740
+ '..',
2741
+ '..',
2742
+ 'shared'
2743
+ ]));
2744
+ const handler = withWiring ? await promptEndpointHandler(boundedContextFolder) : void 0;
2745
+ const endpointFile = node_path.join(endpointFolder.path, `${method.toUpperCase()}.ts`);
2746
+ endpointFolder.createFile(`${method.toUpperCase()}.ts`, `
2747
+ ${endpointGenerator ? `import type { ${endpointGenerator.typeName} } from '${relativeImport(endpointFile, endpointGenerator.typeFile)}'` : "import { EndpointGenerator } from '@domain-first/handlers-rest'"}${handler ? `
2748
+ import type { ${handler.typeName} } from '${relativeImport(endpointFile, handler.typeFile)}'` : ''}
2749
+
2750
+ export class ${endpointClassName} {
2751
+ constructor(
2752
+ private readonly endpointGenerator: ${endpointGenerator?.typeName ?? 'EndpointGenerator'},
2753
+ private readonly handler: ${handler?.typeName ?? 'never'}
2754
+ ) {}
2755
+
2756
+ get handle() {
2757
+ return this.endpointGenerator(this.handler.handle, {
2758
+ route: { method: '${method}', path: ['${boundedContextFolder.name}', '${controller}'${routeSegments.length ? `, ${routeSegments.map((x)=>`'${x}'`).join(', ')}` : ''}] },
2759
+ tags: ['${boundedContextFolder.name}: ${controller}'],
2760
+ })
2761
+ }
2762
+ }
2763
+ `.trim());
2764
+ if (withWiring) {
2765
+ const wiringFolder = boundedContextFolder.subitem([
2766
+ 'wiring',
2767
+ 'presentation',
2768
+ 'rest',
2769
+ controller
2770
+ ]);
2771
+ const wireNameBase = `wire-${nameBase}`;
2772
+ const wireNaming = new UnknownFormatNaming(wireNameBase);
2773
+ const wireFile = node_path.join(wiringFolder.path, `${wireNaming.fileName}.ts`);
2774
+ const dependencies = endpointGenerator ? [
2775
+ endpointGenerator,
2776
+ handler
2777
+ ].filter((x)=>!!x) : [];
2778
+ wiringFolder.createFile(`${wireNaming.fileName}.ts`, `
2779
+ import { wireClass } from '@domain-first/wire'
2780
+ import { ${endpointClassName} } from '${relativeImport(wireFile, endpointFile)}'
2781
+ ${dependencies.map((x)=>`import { ${x.wireName} } from '${relativeImport(wireFile, x.wireFile)}'`).join('\n')}
2782
+
2783
+ export const wire${endpointClassName} = wireClass(
2784
+ ${endpointClassName},
2785
+ [${dependencies.map((x)=>x.wireName).join(', ')}]
2786
+ )
2787
+ `.trim());
2788
+ wiringFolder.file('index.ts').addLine(`export * from './${wireNaming.fileName}'`);
2789
+ }
2790
+ };
2791
+ const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
2792
+ const name = await input({
2793
+ message: 'Name: '
2794
+ });
2795
+ const naming = new UnknownFormatNaming(name);
2796
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
2797
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2798
+ const wiringFolder = boundedContextFolder.subitem([
2799
+ 'wiring',
2800
+ 'infrastructure-services'
2801
+ ]);
2802
+ const infrastructureServicesFolder = boundedContextFolder.subitem([
2803
+ 'infrastructure',
2804
+ 'services'
2805
+ ]);
2806
+ infrastructureServicesFolder.createFile(`${naming.fileName}-infrastructure-service.ts`, `
2807
+ export class ${naming.ClassName}InfrastructureService {
2808
+
2809
+ }
2810
+ `.trim());
2811
+ if (scaffoldUnitTests) infrastructureServicesFolder.createFile(`${naming.fileName}-infrastructure-service.spec.ts`, `
2812
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2813
+ ${withWiring ? `import { type ${naming.ClassName}InfrastructureService } from './${naming.fileName}-infrastructure-service'
2814
+ import { wire${naming.ClassName}InfrastructureService } from '../../wiring/infrastructure-services/wire-${naming.fileName}-infrastructure-service'` : `import { ${naming.ClassName}InfrastructureService } from './${naming.fileName}-infrastructure-service'`}
2815
+
2816
+ let ${naming.variableName}InfrastructureService: ${naming.ClassName}InfrastructureService
2817
+
2818
+ beforeEach(() => {
2819
+ ${naming.variableName}InfrastructureService = ${withWiring ? `wire${naming.ClassName}InfrastructureService()` : `new ${naming.ClassName}InfrastructureService()`}
2820
+ })
2821
+
2822
+ describe('${naming.withSpaces}', () => {
2823
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
2824
+ expect(${naming.variableName}InfrastructureService).toBeDefined()
2825
+ })
2826
+ })
2827
+ `.trim());
2828
+ if (withWiring) {
2829
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
2830
+ import { wireClass } from '@domain-first/wire'
2831
+ import { ${naming.ClassName}InfrastructureService } from '../../infrastructure/services/${naming.fileName}-infrastructure-service'
2832
+
2833
+ export const wire${naming.ClassName}InfrastructureService = wireClass(
2834
+ ${naming.ClassName}InfrastructureService,
2835
+ []
2836
+ )
2837
+ `.trim());
2838
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
2839
+ }
2840
+ };
2841
+ const scaffoldNewQuery = async (boundedContextFolder)=>{
2842
+ const queriesFolder = boundedContextFolder.subitem([
2843
+ 'application',
2844
+ 'queries'
2845
+ ]);
2846
+ const infrastructureFolder = boundedContextFolder.subitem([
2847
+ 'infrastructure',
2848
+ 'queries'
2849
+ ]);
2850
+ const queryName = await input({
2851
+ message: 'Name: '
2852
+ });
2853
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
2854
+ const naming = new UnknownFormatNaming(queryName);
2855
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2856
+ const implementationType = await input({
2857
+ message: 'Query infrastructure implementation type:',
2858
+ default: ConfigFile.Instance.data.defaultPersistenceLayerImplementation
2859
+ });
2860
+ let addTestImplementation = false;
2861
+ let testImplementationType = '';
2862
+ addTestImplementation = await prompts_confirm({
2863
+ message: 'Add a test implementation for Query'
2864
+ });
2865
+ if (addTestImplementation) testImplementationType = await input({
2866
+ message: 'Test Query infrastructure implementation type:',
2867
+ default: 'in-memory'
2868
+ });
2869
+ const implementationTypes = [
2870
+ implementationType,
2871
+ testImplementationType
2872
+ ].filter((x)=>!!x);
2873
+ for (const implementation of implementationTypes){
2874
+ const formatNaming = new UnknownFormatNaming(implementation);
2875
+ const implementationFile = infrastructureFolder.subitem([
2876
+ formatNaming.fileName
2877
+ ]).createFile(`${formatNaming.fileName}-${naming.fileName}-query.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2878
+ import { defineHandler } from '@domain-first/handlers'
2879
+ import { ${naming.ClassName}Query } from '../../../application/queries/${naming.fileName}-query'
2880
+
2881
+ export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.ClassName}Query {
2882
+ constructor() {
2883
+ super()
2884
+ }
2885
+
2886
+ handle = defineHandler({
2887
+ inputSchema: ${naming.ClassName}Query.inputSchema,
2888
+ outputSchema: ${naming.ClassName}Query.outputSchema,
2889
+ handler: async (input) => {
2890
+ return {}
2891
+ }
2892
+ })
2893
+ }
2894
+ `.trim() : `
2895
+ import { ${naming.ClassName}Query } from '../../../application/queries/${naming.fileName}-query'
2896
+
2897
+ export class ${formatNaming.ClassName}${naming.ClassName}Query extends ${naming.ClassName}Query {
2898
+ constructor() {
2899
+ super()
2900
+ }
2901
+ }
2902
+ `.trim());
2903
+ if (!withWiring && usesInMemoryDb(implementation)) injectInMemoryDb(implementationFile, `${formatNaming.ClassName}${naming.ClassName}Query`);
2904
+ }
2905
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers')) queriesFolder.createFile(`${naming.fileName}-query.ts`, `
2906
+ import type { Handler } from '@domain-first/handlers'
2907
+
2908
+ export abstract class ${naming.ClassName}Query {
2909
+ static inputSchema = {}
2910
+ static outputSchema = {}
2911
+
2912
+ abstract handle: Handler<typeof ${naming.ClassName}Query.inputSchema, typeof ${naming.ClassName}Query.outputSchema>
2913
+ }
2914
+ `.trim());
2915
+ else queriesFolder.createFile(`${naming.fileName}-query.ts`, `
2916
+ export abstract class ${naming.ClassName}Query {
2917
+
2918
+ }`.trim());
2919
+ if (scaffoldUnitTests) {
2920
+ const implementationNaming = new UnknownFormatNaming(implementationType);
2921
+ const specFile = queriesFolder.createFile(`${naming.fileName}-query.spec.ts`, `
2922
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2923
+ ${withWiring ? `import { type ${naming.ClassName}Query } from './${naming.fileName}-query'
2924
+ 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'
2925
+
2926
+ type ${naming.ClassName}Query = ${implementationNaming.ClassName}${naming.ClassName}Query`}
2927
+
2928
+ let ${naming.variableName}Query: ${naming.ClassName}Query
2929
+
2930
+ beforeEach(() => {
2931
+ ${naming.variableName}Query = ${withWiring ? `wire${naming.ClassName}Query()` : `new ${implementationNaming.ClassName}${naming.ClassName}Query()`}
2932
+ })
2933
+
2934
+ describe('${naming.withSpaces} query', () => {
2935
+ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
2936
+ expect(${naming.variableName}Query).toBeDefined()
2937
+ })
2938
+ })
2939
+ `.trim());
2940
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Query`);
2941
+ }
2942
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
2943
+ const implementationNaming = new UnknownFormatNaming(implementationType);
2944
+ const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
2945
+ const wireFile = boundedContextFolder.subitem([
2946
+ 'wiring',
2947
+ 'queries'
2948
+ ]).createFile(`wire-${naming.fileName}-query.ts`, `
2949
+ import { wireClass } from '@domain-first/wire'
2950
+ import { envBranchedWire } from '../../../../shared/wiring/env-branched-wire'
2951
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Query } from '../../infrastructure/queries/${fileName}/${fileName}-${naming.fileName}-query'`).join('\n')}
2952
+
2953
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Query, [])`).join('\n\n')}
2954
+
2955
+ export const wire${naming.ClassName}Query = envBranchedWire({
2956
+ test: wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation,
2957
+ development: wire${implementationNaming.ClassName}Implementation,
2958
+ production: wire${implementationNaming.ClassName}Implementation
2959
+ })
2960
+ `.trim());
2961
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
2962
+ }
2963
+ };
2964
+ const scaffoldNewUseCase = async (boundedContextFolder)=>{
2965
+ const useCasesFolder = boundedContextFolder.subitem([
2966
+ 'application',
2967
+ 'use-cases'
2968
+ ]);
2969
+ const useCaseName = await input({
2970
+ message: 'Name: '
2971
+ });
2972
+ const naming = new UnknownFormatNaming(useCaseName);
2973
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
2974
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2975
+ useCasesFolder.createFile(`${naming.fileName}-use-case.ts`, ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers') ? `
2976
+ import { defineHandler } from '@domain-first/handlers'
2977
+
2978
+ export class ${naming.ClassName}UseCase {
2979
+ constructor() {}
2980
+
2981
+ static inputSchema = {}
2982
+ static outputSchema = {}
2983
+
2984
+ handle = defineHandler({
2985
+ inputSchema: ${naming.ClassName}UseCase.inputSchema,
2986
+ outputSchema: ${naming.ClassName}UseCase.outputSchema,
2987
+ handler: async (input) => {
2988
+ return {}
2989
+ }
2990
+ })
2991
+ }
2992
+ `.trim() : `
2993
+ export class ${naming.ClassName}UseCase {
2994
+
2995
+ }
2996
+ `.trim());
2997
+ if (scaffoldUnitTests) useCasesFolder.createFile(`${naming.fileName}-use-case.spec.ts`, `
2998
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2999
+ ${withWiring ? `import { type ${naming.ClassName}UseCase } from './${naming.fileName}-use-case'
3000
+ import { wire${naming.ClassName}UseCase } from '../../wiring/use-cases/wire-${naming.fileName}-use-case'` : `import { ${naming.ClassName}UseCase } from './${naming.fileName}-use-case'`}
3001
+
3002
+ let ${naming.variableName}UseCase: ${naming.ClassName}UseCase
3003
+
3004
+ beforeEach(() => {
3005
+ ${naming.variableName}UseCase = ${withWiring ? `wire${naming.ClassName}UseCase()` : `new ${naming.ClassName}UseCase()`}
3006
+ })
3007
+
3008
+ describe('${naming.withSpaces} use case', () => {
3009
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
3010
+ expect(${naming.variableName}UseCase).toBeDefined()
3011
+ })
3012
+ })
3013
+ `.trim());
3014
+ if (withWiring) {
3015
+ const wireFile = boundedContextFolder.subitem([
3016
+ 'wiring',
3017
+ 'use-cases'
3018
+ ]).createFile(`wire-${naming.fileName}-use-case.ts`, `
3019
+ import { wireClass } from '@domain-first/wire'
3020
+ import { ${naming.ClassName}UseCase } from '../../application/use-cases/${naming.fileName}-use-case'
3021
+
3022
+ export const wire${naming.ClassName}UseCase = wireClass(
3023
+ ${naming.ClassName}UseCase,
3024
+ []
3025
+ )
3026
+
3027
+ `.trim());
3028
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
3029
+ }
3030
+ };
3031
+ const scaffoldReactSharedHook = async (presentationReactFolder)=>{
3032
+ const name = await input({
3033
+ message: 'Name without "use" (e.g. debounce): '
3034
+ });
3035
+ const { ClassName, fileName } = new UnknownFormatNaming(name.trim().replace(/^use-/, ''));
3036
+ presentationReactFolder.subitem([
3037
+ 'hooks'
3038
+ ]).createFile(`use-${fileName}.ts`, `
3039
+ export const use${ClassName} = () => {
3040
+ return {}
3041
+ }
3042
+ `.trim());
3043
+ };
3044
+ const scaffoldReactUIKitComponent = async (presentationReactFolder)=>{
3045
+ const name = await input({
3046
+ message: 'Name: '
3047
+ });
3048
+ const { ClassName, fileName } = new UnknownFormatNaming(name);
3049
+ const componentFolder = presentationReactFolder.subitem([
3050
+ 'ui-kit',
3051
+ fileName
3052
+ ]);
3053
+ componentFolder.createFile('index.ts', `export * from './${fileName}'`);
3054
+ componentFolder.createFile(`${fileName}.tsx`, `
3055
+ import { type FC } from 'react'
3056
+
3057
+ export type ${ClassName}Props = {}
3058
+
3059
+ export const ${ClassName}: FC<${ClassName}Props> = (props) => {
3060
+ return <></>
3061
+ }
3062
+ `.trim());
3063
+ const { storybookFramework } = ConfigFile.Instance.data;
3064
+ if (storybookFramework) componentFolder.createFile(`${fileName}.stories.tsx`, `
3065
+ import type { Meta, StoryObj } from '${storybookFramework}'
3066
+ import { ${ClassName} } from './${fileName}'
3067
+
3068
+ const meta = {
3069
+ title: 'UI-kit/${ClassName}',
3070
+ component: ${ClassName}
3071
+ } satisfies Meta<typeof ${ClassName}>
3072
+
3073
+ export default meta
3074
+
3075
+ type Story = StoryObj<typeof meta>
3076
+
3077
+ export const Default: Story = {
3078
+ args: {}
3079
+ }
3080
+ `.trim());
3081
+ };
3082
+ const scaffoldReactWidget = async (presentationReactFolder)=>{
3083
+ const widgetName = await input({
3084
+ message: 'Name (folders split by "/"): ',
3085
+ validate: NestedName.validate
3086
+ });
3087
+ const widgetType = await prompts_select({
3088
+ choices: [
3089
+ 'monolithic',
3090
+ 'with separated ui',
3091
+ 'headless'
3092
+ ],
3093
+ message: 'Type: '
3094
+ });
3095
+ const { folders, folderName, ClassName, fileName, classNameSegments } = new NestedName(widgetName);
3096
+ const folder = presentationReactFolder.subitem([
3097
+ 'widgets',
3098
+ ...folders,
3099
+ folderName
3100
+ ]);
3101
+ const storyTitle = [
3102
+ 'Widgets',
3103
+ ...classNameSegments
3104
+ ].join('/');
3105
+ const widgetFileName = `${fileName}-widget`;
3106
+ const uiFileName = `${fileName}-widget-ui`;
3107
+ const uiModelFileName = `use-${fileName}-ui-model`;
3108
+ folder.createFile('index.ts', `export * from './${widgetFileName}'`);
3109
+ switch(widgetType){
3110
+ case 'monolithic':
3111
+ folder.createFile(`${widgetFileName}.tsx`, `
3112
+ import { type FC } from 'react'
3113
+
3114
+ export type ${ClassName}WidgetProps = {}
3115
+
3116
+ export const ${ClassName}Widget: FC<${ClassName}WidgetProps> = (props) => {
3117
+ return <></>
3118
+ }
3119
+ `.trim());
3120
+ break;
3121
+ case 'with separated ui':
3122
+ {
3123
+ folder.createFile('types.ts', `
3124
+ export type ${ClassName}WidgetProps = { }
3125
+
3126
+ export type ${ClassName}WidgetUIProps = { }
3127
+ `.trim());
3128
+ folder.createFile(`${widgetFileName}.tsx`, `
3129
+ import { type FC } from 'react'
3130
+ import type { ${ClassName}WidgetProps } from './types'
3131
+ import { ${ClassName}WidgetUI } from './ui/${uiFileName}'
3132
+ import { use${ClassName}UIModel } from './hooks/${uiModelFileName}'
3133
+
3134
+ export const ${ClassName}Widget: FC<${ClassName}WidgetProps> = (props) => {
3135
+ const uiModel = use${ClassName}UIModel(props)
3136
+ return <${ClassName}WidgetUI {...uiModel} />
3137
+ }
3138
+
3139
+ export type { ${ClassName}WidgetProps }
3140
+ `.trim());
3141
+ folder.subitem([
3142
+ 'ui'
3143
+ ]).createFile(`${uiFileName}.tsx`, `
3144
+ import { FC } from 'react'
3145
+ import type { ${ClassName}WidgetUIProps } from '../types'
3146
+
3147
+ export const ${ClassName}WidgetUI: FC<${ClassName}WidgetUIProps> = (props) => {
3148
+ return <></>
3149
+ }
3150
+ `.trim());
3151
+ const { storybookFramework } = ConfigFile.Instance.data;
3152
+ if (storybookFramework) folder.subitem([
3153
+ 'ui'
3154
+ ]).createFile(`${uiFileName}.stories.tsx`, `
3155
+ import type { Meta, StoryObj } from '${storybookFramework}'
3156
+ import { ${ClassName}WidgetUI } from './${uiFileName}'
3157
+
3158
+ const meta = {
3159
+ title: '${storyTitle}',
3160
+ component: ${ClassName}WidgetUI
3161
+ } satisfies Meta<typeof ${ClassName}WidgetUI>
3162
+
3163
+ export default meta
3164
+
3165
+ type Story = StoryObj<typeof meta>
3166
+
3167
+ export const Default: Story = {
3168
+ args: {}
3169
+ }
3170
+ `.trim());
3171
+ folder.subitem([
3172
+ 'hooks'
3173
+ ]).createFile(`${uiModelFileName}.ts`, `
3174
+ import type { ${ClassName}WidgetProps, ${ClassName}WidgetUIProps } from '../types'
3175
+
3176
+ export const use${ClassName}UIModel = (widgetProps: ${ClassName}WidgetProps): ${ClassName}WidgetUIProps => {
3177
+ return {}
3178
+ }
3179
+ `.trim());
3180
+ break;
3181
+ }
3182
+ case 'headless':
3183
+ folder.createFile('types.ts', `
3184
+ import { type FC } from 'react'
3185
+
3186
+ export type ${ClassName}WidgetUIProps = { }
3187
+
3188
+ export type ${ClassName}WidgetProps = {
3189
+ UI: FC<${ClassName}WidgetUIProps>
3190
+ }
3191
+
3192
+ `.trim());
3193
+ folder.createFile(`${widgetFileName}.tsx`, `
3194
+ import { type FC } from 'react'
3195
+ import type { ${ClassName}WidgetProps } from './types'
3196
+ import { use${ClassName}UIModel } from './hooks/${uiModelFileName}'
3197
+
3198
+ export const ${ClassName}Widget: FC<${ClassName}WidgetProps> = (props) => {
3199
+ const uiModel = use${ClassName}UIModel(props)
3200
+ return <props.UI {...uiModel} />
3201
+ }
3202
+
3203
+ export type { ${ClassName}WidgetProps }
3204
+ `.trim());
3205
+ folder.subitem([
3206
+ 'hooks'
3207
+ ]).createFile(`${uiModelFileName}.ts`, `
3208
+ import type { ${ClassName}WidgetProps, ${ClassName}WidgetUIProps } from '../types'
3209
+
3210
+ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps, 'UI'>): ${ClassName}WidgetUIProps => {
3211
+ return {}
3212
+ }
3213
+ `.trim());
3214
+ break;
3215
+ }
3216
+ };
3217
+ export { addIntegration, initializeUseCase, moveReactModuleUseCase, printNextSteps, savePendingChanges, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, wireDependency };