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