@domain-first/project-structure 6.0.0 → 7.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/README.md +16 -19
- package/dist/201.js +46 -35
- package/dist/287.js +1685 -1612
- package/dist/config-file.d.ts +2 -2
- package/dist/dependency-rules.d.ts +1 -1
- package/dist/file-system.d.ts +5 -0
- package/dist/in-memory-db.d.ts +5 -0
- package/dist/index.cjs +100 -916
- package/dist/index.js +6 -46
- package/dist/init.cjs +868 -0
- package/dist/init.d.ts +2 -0
- package/dist/init.js +36 -0
- package/dist/integration.cjs +412 -33
- package/dist/integration.js +4 -4
- package/dist/integrations/in-memory-db.d.ts +6 -0
- package/dist/integrations/index.d.ts +2 -0
- package/dist/integrations/missing-domain-first-packages.d.ts +8 -0
- package/dist/integrations/rest-endpoint-generator.d.ts +18 -0
- package/dist/integrations/rest-endpoint-generator.spec.d.ts +1 -0
- package/dist/lint.cjs +8 -8
- package/dist/lint.js +7 -7
- package/dist/print-next-steps.d.ts +2 -2
- package/dist/react.cjs +915 -0
- package/dist/react.d.ts +2 -0
- package/dist/react.js +73 -0
- package/dist/use-cases/rest-endpoint-generator.d.ts +1 -1
- package/package.json +3 -1
- package/skills/df-ps-implement/SKILL.md +10 -55
- package/skills/df-ps-plan-feature/SKILL.md +6 -6
- package/skills/df-ps-project-scripts/SKILL.md +1 -1
- package/skills/df-ps-react/SKILL.md +82 -0
- package/skills/df-ps-react/references/generators.md +80 -0
- package/skills/df-ps-scaffold/SKILL.md +38 -20
- package/skills/df-ps-scaffold/references/choosing-components.md +7 -28
- package/skills/df-ps-scaffold/references/generators.md +6 -179
- package/skills/df-ps-scaffold/references/units/aggregate.md +47 -0
- package/skills/df-ps-scaffold/references/units/bounded-context.md +13 -0
- package/skills/df-ps-scaffold/references/units/command-query.md +32 -0
- package/skills/df-ps-scaffold/references/units/endpoint.md +28 -0
- package/skills/df-ps-scaffold/references/units/entity-value-object.md +27 -0
- package/skills/df-ps-scaffold/references/units/errors.md +26 -0
- package/skills/df-ps-scaffold/references/units/port.md +23 -0
- package/skills/df-ps-scaffold/references/units/services.md +28 -0
- package/skills/df-ps-scaffold/references/units/use-case.md +25 -0
- package/skills/df-ps-scaffold/references/units/wire-dependency.md +15 -0
- package/skills/df-ps-scaffold/scripts/drive.mjs +12 -4
package/dist/287.js
CHANGED
|
@@ -1,57 +1,8 @@
|
|
|
1
|
-
import { styleText } from "node:util";
|
|
2
1
|
import node_path from "node:path";
|
|
3
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
4
|
import node_fs from "node:fs";
|
|
5
|
-
import { addImport, availableDependencies, discardPendingChanges, findWiredModules, UnknownFormatNaming, Folder, writePendingChanges,
|
|
6
|
-
const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
|
|
7
|
-
const mergeInstallCommands = (commands)=>{
|
|
8
|
-
const runtime = new Set();
|
|
9
|
-
const development = new Set();
|
|
10
|
-
const rest = [];
|
|
11
|
-
for (const command of commands){
|
|
12
|
-
const match = installCommand.exec(command);
|
|
13
|
-
if (!match) {
|
|
14
|
-
rest.push(command);
|
|
15
|
-
continue;
|
|
16
|
-
}
|
|
17
|
-
for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
|
|
18
|
-
}
|
|
19
|
-
const devOnly = [
|
|
20
|
-
...development
|
|
21
|
-
].filter((name)=>!runtime.has(name));
|
|
22
|
-
return [
|
|
23
|
-
...runtime.size ? [
|
|
24
|
-
`npm install ${[
|
|
25
|
-
...runtime
|
|
26
|
-
].join(' ')}`
|
|
27
|
-
] : [],
|
|
28
|
-
...devOnly.length ? [
|
|
29
|
-
`npm install --save-dev ${devOnly.join(' ')}`
|
|
30
|
-
] : [],
|
|
31
|
-
...rest
|
|
32
|
-
];
|
|
33
|
-
};
|
|
34
|
-
const printNextSteps = (nextSteps)=>{
|
|
35
|
-
const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
|
|
36
|
-
const commands = mergeInstallCommands(nextSteps.filter(isCommand));
|
|
37
|
-
const notes = nextSteps.filter((line)=>!isCommand(line));
|
|
38
|
-
const sections = [];
|
|
39
|
-
if (commands.length) sections.push([
|
|
40
|
-
'Run these commands to install the required dependencies:',
|
|
41
|
-
...commands.map((line)=>styleText([
|
|
42
|
-
'bold',
|
|
43
|
-
'cyan'
|
|
44
|
-
], line))
|
|
45
|
-
].join('\n'));
|
|
46
|
-
if (notes.length) sections.push([
|
|
47
|
-
'Additional information:',
|
|
48
|
-
...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
|
|
49
|
-
'bold',
|
|
50
|
-
'cyan'
|
|
51
|
-
], path)))
|
|
52
|
-
].join('\n'));
|
|
53
|
-
if (sections.length) console.log(sections.join('\n\n'));
|
|
54
|
-
};
|
|
5
|
+
import { addImport, availableDependencies, discardPendingChanges, findWiredModules, UnknownFormatNaming, Folder, writePendingChanges, readWiredModule, stripJsonComments, addClassMember, withoutOverwrites, addWireDependencies, addConstructorParameters, filesToOverwrite, ConfigFile, relativeImport, wireDependencies, File, ProjectRoot, implementationType as wiring_implementationType, isSuggestedFor, compilerOption } from "./201.js";
|
|
55
6
|
const savePendingChanges = async ()=>{
|
|
56
7
|
const overwrittenFiles = filesToOverwrite();
|
|
57
8
|
if (overwrittenFiles.length) {
|
|
@@ -71,1049 +22,542 @@ const savePendingChanges = async ()=>{
|
|
|
71
22
|
writePendingChanges();
|
|
72
23
|
return true;
|
|
73
24
|
};
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
};
|
|
82
|
-
const missing = [
|
|
83
|
-
...new Set(packages)
|
|
84
|
-
].filter((name)=>!Object.hasOwn(dependencies, name));
|
|
85
|
-
return missing.length ? [
|
|
86
|
-
`npm i ${missing.join(' ')}`
|
|
87
|
-
] : [];
|
|
25
|
+
const inMemoryImplementationType = 'in-memory';
|
|
26
|
+
const in_memory_db_className = 'InMemoryDbInfrastructureService';
|
|
27
|
+
const wireName = 'wireInMemoryDbInfrastructureService';
|
|
28
|
+
const parameterName = 'inMemoryDbInfrastructureService';
|
|
29
|
+
const inMemoryDbService = `type Entry = {
|
|
30
|
+
id: unknown;
|
|
31
|
+
item: any;
|
|
88
32
|
};
|
|
89
|
-
const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
|
|
90
|
-
class NestedName {
|
|
91
|
-
folders;
|
|
92
|
-
folderName;
|
|
93
|
-
fileName;
|
|
94
|
-
ClassName;
|
|
95
|
-
classNameSegments;
|
|
96
|
-
constructor(rawSource){
|
|
97
|
-
const segments = splitSegments(rawSource);
|
|
98
|
-
this.folders = segments.slice(0, -1);
|
|
99
|
-
this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
|
|
100
|
-
this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
|
|
101
|
-
this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
|
|
102
|
-
this.ClassName = this.classNameSegments.join('');
|
|
103
|
-
}
|
|
104
|
-
static validate = (rawSource)=>{
|
|
105
|
-
const segments = splitSegments(rawSource);
|
|
106
|
-
if (!segments.length) return 'Name is required';
|
|
107
|
-
if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
|
|
108
|
-
return true;
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
|
-
const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
|
|
112
|
-
${[
|
|
113
|
-
...imports,
|
|
114
|
-
"import { type FC } from 'react'"
|
|
115
|
-
].join('\n')}
|
|
116
33
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
|
|
120
|
-
return ${body}
|
|
34
|
+
declare global {
|
|
35
|
+
var ___SHARED_IN_MEMORY_DB___: Record<string, Array<Entry>> | undefined;
|
|
121
36
|
}
|
|
122
|
-
`.trim();
|
|
123
|
-
const scaffoldReactPage = async (presentationReactFolder)=>{
|
|
124
|
-
const name = await input({
|
|
125
|
-
message: 'Provide name (folders split by "/"):',
|
|
126
|
-
validate: NestedName.validate
|
|
127
|
-
});
|
|
128
|
-
const { folders, ClassName, fileName } = new NestedName(name);
|
|
129
|
-
presentationReactFolder.subitem([
|
|
130
|
-
'pages',
|
|
131
|
-
...folders
|
|
132
|
-
]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
|
|
133
|
-
};
|
|
134
|
-
const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
|
|
135
|
-
const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
|
|
136
|
-
const openapiExtractor = (rootFolder)=>`import path from 'node:path';
|
|
137
|
-
import {
|
|
138
|
-
type DocNode,
|
|
139
|
-
DocPlainText,
|
|
140
|
-
TSDocConfiguration,
|
|
141
|
-
TSDocParser,
|
|
142
|
-
TSDocTagDefinition,
|
|
143
|
-
TSDocTagSyntaxKind
|
|
144
|
-
} from '@microsoft/tsdoc';
|
|
145
|
-
import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
|
|
146
|
-
|
|
147
|
-
type BlockTag = \`@\${string}\`;
|
|
148
37
|
|
|
149
|
-
type
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
38
|
+
type Section<T, TId> = {
|
|
39
|
+
all: (predicate?: (x: T) => boolean) => T[];
|
|
40
|
+
first: (predicate: (x: T) => boolean) => T | null;
|
|
41
|
+
withId: (id: TId) => T | null;
|
|
42
|
+
lastAddedItem: () => T | null;
|
|
43
|
+
save: (payload: T extends { id: TId } ? T : [TId, T]) => void;
|
|
44
|
+
deleteById: (id: TId) => void;
|
|
45
|
+
delete: (predicate: (x: T) => boolean) => void;
|
|
153
46
|
};
|
|
154
47
|
|
|
155
|
-
type
|
|
156
|
-
summary: string;
|
|
157
|
-
description: string;
|
|
158
|
-
operationId: string;
|
|
159
|
-
}>;
|
|
160
|
-
|
|
161
|
-
const project = new Project({
|
|
162
|
-
tsConfigFilePath: 'tsconfig.json'
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
const getText = (node: DocNode): string =>
|
|
166
|
-
node
|
|
167
|
-
.getChildNodes()
|
|
168
|
-
.map((child) => {
|
|
169
|
-
if (child instanceof DocPlainText) {
|
|
170
|
-
return child.text;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
return getText(child);
|
|
174
|
-
})
|
|
175
|
-
.join('');
|
|
48
|
+
type IdsAreEqual<TId> = (a: TId, b: TId) => boolean;
|
|
176
49
|
|
|
177
|
-
const
|
|
178
|
-
comment
|
|
179
|
-
.replace(/^\\/\\*\\*/, '')
|
|
180
|
-
.replace(/\\*\\/$/, '')
|
|
181
|
-
.split(/\\r?\\n/)
|
|
182
|
-
.map((line) => line.replace(/^\\s*\\*\\s?/, ''))
|
|
183
|
-
.join('\\n');
|
|
50
|
+
const comparisonMethodNames = ['equals', 'same', 'isSame', 'isEqual'] as const;
|
|
184
51
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
|
|
52
|
+
const defaultIdsAreEqual = (a: unknown, b: unknown): boolean => {
|
|
53
|
+
if (typeof a !== 'object' || a === null) {
|
|
54
|
+
return Object.is(a, b);
|
|
55
|
+
}
|
|
190
56
|
|
|
191
|
-
for (const
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
tagName,
|
|
196
|
-
syntaxKind: TSDocTagSyntaxKind.BlockTag
|
|
197
|
-
})
|
|
198
|
-
);
|
|
57
|
+
for (const methodName of comparisonMethodNames) {
|
|
58
|
+
const method: unknown = (a as Record<string, unknown>)[methodName];
|
|
59
|
+
if (typeof method === 'function') {
|
|
60
|
+
return Boolean(method.call(a, b));
|
|
199
61
|
}
|
|
200
62
|
}
|
|
201
63
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
return getText(docComment.summarySection).trim() || undefined;
|
|
205
|
-
};
|
|
206
|
-
|
|
207
|
-
// Parsed by hand rather than through TSDoc, which drops the line breaks.
|
|
208
|
-
const getTagText = (comment: string, tag: BlockTag): string | undefined => {
|
|
209
|
-
const tagMatch = getRawCommentText(comment).match(
|
|
210
|
-
new RegExp(
|
|
211
|
-
\`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
|
|
212
|
-
)
|
|
213
|
-
);
|
|
214
|
-
|
|
215
|
-
return tagMatch?.[1].trim() || undefined;
|
|
64
|
+
return Object.is(a, b);
|
|
216
65
|
};
|
|
217
66
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
// queries only serve as helpers, e.g. guest checks.
|
|
221
|
-
const findHandlerClass = (endpointFile: SourceFile) =>
|
|
222
|
-
endpointFile
|
|
223
|
-
.getDescendantsOfKind(SyntaxKind.CallExpression)
|
|
224
|
-
.map((call) => call.getArguments()[0])
|
|
225
|
-
.filter(Node.isPropertyAccessExpression)
|
|
226
|
-
.find((argument) => argument.getName() === 'handle')
|
|
227
|
-
?.getExpression()
|
|
228
|
-
.getType()
|
|
229
|
-
.getSymbol()
|
|
230
|
-
?.getDeclarations()
|
|
231
|
-
.find(Node.isClassDeclaration);
|
|
67
|
+
const hasId = (x: unknown): x is { id: unknown } =>
|
|
68
|
+
typeof x === 'object' && x !== null && 'id' in x;
|
|
232
69
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
70
|
+
export class InMemoryDbInfrastructureService {
|
|
71
|
+
protected section<T extends { id: unknown }>(
|
|
72
|
+
key: string,
|
|
73
|
+
idsAreEqual?: IdsAreEqual<T['id']>
|
|
74
|
+
): Section<T, T['id']>;
|
|
75
|
+
protected section<T, TId>(
|
|
76
|
+
key: string,
|
|
77
|
+
idsAreEqual?: IdsAreEqual<TId>
|
|
78
|
+
): Section<T, TId>;
|
|
79
|
+
protected section<T, TId>(
|
|
80
|
+
key: string,
|
|
81
|
+
idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
|
|
82
|
+
): Section<T, TId> {
|
|
83
|
+
if (!globalThis.___SHARED_IN_MEMORY_DB___) {
|
|
84
|
+
globalThis.___SHARED_IN_MEMORY_DB___ = {};
|
|
85
|
+
}
|
|
237
86
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
}: OpenApiDataTags = {}) => {
|
|
242
|
-
return (routeMetadata: {
|
|
243
|
-
method: string;
|
|
244
|
-
path: readonly string[];
|
|
245
|
-
}): OpenApiData | undefined => {
|
|
246
|
-
try {
|
|
247
|
-
const [currentBoundedContext, controller, ...relativePath] =
|
|
248
|
-
routeMetadata.path;
|
|
87
|
+
if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
|
|
88
|
+
globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
|
|
89
|
+
}
|
|
249
90
|
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
91
|
+
const items = (): T[] =>
|
|
92
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key].map(
|
|
93
|
+
(entry) => entry.item
|
|
94
|
+
);
|
|
253
95
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
96
|
+
return {
|
|
97
|
+
all: (predicate: (x: T) => boolean = () => true): T[] =>
|
|
98
|
+
items().filter(predicate),
|
|
99
|
+
first: (predicate: (x: T) => boolean): T | null =>
|
|
100
|
+
items().find(predicate) ?? null,
|
|
101
|
+
withId: (id: TId): T | null =>
|
|
102
|
+
items().find(
|
|
103
|
+
(x: T) => hasId(x) && idsAreEqual(x.id as TId, id)
|
|
104
|
+
) ?? null,
|
|
105
|
+
lastAddedItem: (): T | null =>
|
|
106
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key].at(-1)?.item ?? null,
|
|
107
|
+
save: (payload: T extends { id: TId } ? T : [TId, T]) => {
|
|
108
|
+
const id = Array.isArray(payload) ? payload[0] : payload.id;
|
|
109
|
+
const item = Array.isArray(payload) ? payload[1] : payload;
|
|
110
|
+
const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
|
|
111
|
+
const existing = entries.find((entry) =>
|
|
112
|
+
idsAreEqual(entry.id as TId, id)
|
|
113
|
+
);
|
|
114
|
+
if (existing) {
|
|
115
|
+
existing.item = item;
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
entries.push({ id, item });
|
|
119
|
+
},
|
|
120
|
+
deleteById: (id: TId) => {
|
|
121
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key] =
|
|
122
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
|
|
123
|
+
(entry) => !idsAreEqual(entry.id as TId, id)
|
|
124
|
+
);
|
|
125
|
+
},
|
|
126
|
+
delete: (predicate: (x: T) => boolean) => {
|
|
127
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key] =
|
|
128
|
+
globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
|
|
129
|
+
(entry) => !predicate(entry.item)
|
|
130
|
+
);
|
|
268
131
|
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
`;
|
|
136
|
+
const inMemoryDbWiring = `import { wireClass } from '@domain-first/wire';
|
|
137
|
+
import { InMemoryDbInfrastructureService } from '../../infrastructure/services/in-memory-db-infrastructure-service';
|
|
269
138
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
139
|
+
export const wireInMemoryDbInfrastructureService = wireClass(
|
|
140
|
+
InMemoryDbInfrastructureService,
|
|
141
|
+
[]
|
|
142
|
+
);
|
|
143
|
+
`;
|
|
144
|
+
const inMemoryDbSpec = (testingLibrary, withWiring)=>`
|
|
145
|
+
import { describe, test, expect, beforeEach } from '${testingLibrary}'
|
|
146
|
+
${withWiring ? `import { type InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'
|
|
147
|
+
import { wireInMemoryDbInfrastructureService } from '../../wiring/infrastructure-services/wire-in-memory-db-infrastructure-service'` : "import { InMemoryDbInfrastructureService } from './in-memory-db-infrastructure-service'"}
|
|
273
148
|
|
|
274
|
-
|
|
275
|
-
return { operationId };
|
|
276
|
-
}
|
|
149
|
+
let inMemoryDbInfrastructureService: InMemoryDbInfrastructureService
|
|
277
150
|
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
151
|
+
beforeEach(() => {
|
|
152
|
+
inMemoryDbInfrastructureService = ${withWiring ? 'wireInMemoryDbInfrastructureService()' : 'new InMemoryDbInfrastructureService()'}
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
describe('in memory db', () => {
|
|
156
|
+
test('can be ${withWiring ? 'wired' : 'created'}', () => {
|
|
157
|
+
expect(inMemoryDbInfrastructureService).toBeDefined()
|
|
158
|
+
})
|
|
159
|
+
})
|
|
160
|
+
`.trim();
|
|
161
|
+
const in_memory_db_withWiring = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
162
|
+
const in_memory_db_sharedFolder = ()=>new Folder(new ProjectRoot().path).subitem([
|
|
163
|
+
ConfigFile.Instance.data.rootFolder,
|
|
164
|
+
'shared-kernel'
|
|
165
|
+
]);
|
|
166
|
+
const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
|
|
167
|
+
'infrastructure',
|
|
168
|
+
'services',
|
|
169
|
+
'in-memory-db-infrastructure-service.ts'
|
|
170
|
+
]);
|
|
171
|
+
const in_memory_db_wireFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
|
|
172
|
+
'wiring',
|
|
173
|
+
'infrastructure-services',
|
|
174
|
+
'wire-in-memory-db-infrastructure-service.ts'
|
|
175
|
+
]);
|
|
176
|
+
const scaffoldInMemoryDb = (shared)=>{
|
|
177
|
+
const { testingLibrary } = ConfigFile.Instance.data;
|
|
178
|
+
const servicesFolder = shared.subitem([
|
|
179
|
+
'infrastructure',
|
|
180
|
+
'services'
|
|
181
|
+
]);
|
|
182
|
+
servicesFolder.createFile('in-memory-db-infrastructure-service.ts', inMemoryDbService);
|
|
183
|
+
if (testingLibrary) servicesFolder.createFile('in-memory-db-infrastructure-service.spec.ts', inMemoryDbSpec(testingLibrary, in_memory_db_withWiring()));
|
|
184
|
+
if (in_memory_db_withWiring()) shared.subitem([
|
|
185
|
+
'wiring',
|
|
186
|
+
'infrastructure-services'
|
|
187
|
+
]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
|
|
290
188
|
};
|
|
291
|
-
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
|
-
scripts[target] = command;
|
|
317
|
-
selected[name] = target;
|
|
318
|
-
}
|
|
319
|
-
if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
|
|
320
|
-
manifest.scripts = scripts;
|
|
321
|
-
const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
|
|
322
|
-
file.update(`${JSON.stringify(manifest, null, indent)}\n`);
|
|
189
|
+
const inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
|
|
190
|
+
const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
|
|
191
|
+
const plural = (word)=>{
|
|
192
|
+
if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
|
|
193
|
+
if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
|
|
194
|
+
return `${word}s`;
|
|
195
|
+
};
|
|
196
|
+
const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
|
|
197
|
+
const file = serviceFile();
|
|
198
|
+
const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
|
|
199
|
+
const field = sectionNaming.variableName;
|
|
200
|
+
if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
|
|
201
|
+
const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
|
|
202
|
+
file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
|
|
203
|
+
return field;
|
|
204
|
+
};
|
|
205
|
+
const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
|
|
206
|
+
const inMemoryDbSectionMembers = (field, derived)=>`
|
|
207
|
+
private readonly data: ${in_memory_db_className}['${field}']
|
|
208
|
+
|
|
209
|
+
constructor(${parameterName}: ${in_memory_db_className}) {
|
|
210
|
+
${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
|
|
323
211
|
}
|
|
324
|
-
|
|
212
|
+
`.trim();
|
|
213
|
+
const keepInMemoryDbSection = (classFile, field)=>{
|
|
214
|
+
classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
|
|
325
215
|
};
|
|
326
|
-
const
|
|
327
|
-
const
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
'@microsoft/tsdoc'
|
|
332
|
-
];
|
|
333
|
-
const swaggerPagePath = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
|
|
334
|
-
const swaggerPage = (rootFolder, outputPath)=>{
|
|
335
|
-
const specImport = node_path.posix.relative(node_path.posix.dirname(swaggerPagePath(rootFolder)), outputPath);
|
|
336
|
-
return reactPageContent('Swagger', {
|
|
337
|
-
imports: [
|
|
338
|
-
"import 'swagger-ui-react/swagger-ui.css'",
|
|
339
|
-
"import SwaggerUI from 'swagger-ui-react'",
|
|
340
|
-
`import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
|
|
341
|
-
],
|
|
342
|
-
body: '<SwaggerUI displayOperationId spec={spec} />'
|
|
343
|
-
});
|
|
216
|
+
const isInMemoryDb = (module)=>module.wireName === wireName;
|
|
217
|
+
const injectInMemoryDb = (classFile, implementationName)=>{
|
|
218
|
+
classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
|
|
219
|
+
`private readonly ${parameterName}: ${in_memory_db_className}`
|
|
220
|
+
]));
|
|
344
221
|
};
|
|
345
|
-
const
|
|
346
|
-
|
|
222
|
+
const wireInMemoryDb = (consumerWireFile, implementationName)=>{
|
|
223
|
+
consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
|
|
224
|
+
wireName
|
|
225
|
+
]));
|
|
347
226
|
};
|
|
348
|
-
const
|
|
349
|
-
|
|
350
|
-
|
|
227
|
+
const passInMemoryDb = (specFile, implementationName)=>{
|
|
228
|
+
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}())`));
|
|
229
|
+
};
|
|
230
|
+
const addInMemoryDb = ()=>{
|
|
231
|
+
const config = ConfigFile.Instance.data;
|
|
232
|
+
if (!config.withInMemoryDb) ConfigFile.write({
|
|
233
|
+
...config,
|
|
234
|
+
withInMemoryDb: true
|
|
235
|
+
});
|
|
236
|
+
withoutOverwrites(()=>scaffoldInMemoryDb(new Folder(new ProjectRoot().path).subitem([
|
|
237
|
+
config.rootFolder,
|
|
238
|
+
'shared-kernel'
|
|
239
|
+
])));
|
|
240
|
+
return [];
|
|
241
|
+
};
|
|
242
|
+
const inMemoryDbApplied = ()=>Boolean(ConfigFile.Instance.data.withInMemoryDb) && inMemoryDbScaffolded();
|
|
243
|
+
const hasDependency = (name)=>{
|
|
244
|
+
const manifestFile = new File(node_path.join(new ProjectRoot().path, 'package.json'));
|
|
245
|
+
if (!manifestFile.exists) return false;
|
|
246
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
351
247
|
return [
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
248
|
+
manifest.dependencies,
|
|
249
|
+
manifest.devDependencies,
|
|
250
|
+
manifest.optionalDependencies
|
|
251
|
+
].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
|
|
355
252
|
};
|
|
356
|
-
const
|
|
357
|
-
const
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
const extractOpenApiDataFromEndpointLogic =
|
|
364
|
-
createOpenApiDataFromEndpointLogicExtractor();
|
|
365
|
-
|
|
366
|
-
const handlers = restHandlers.map((x) => ({
|
|
367
|
-
...x,
|
|
368
|
-
metadata: {
|
|
369
|
-
...x.metadata,
|
|
370
|
-
openApiMetadata: {
|
|
371
|
-
...extractOpenApiDataFromEndpointLogic(x.metadata.route),
|
|
372
|
-
...(x.metadata.openApiMetadata ?? {})
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
}));
|
|
376
|
-
` : '';
|
|
377
|
-
return `import { generateOpenAPI } from '@domain-first/handlers-rest';
|
|
378
|
-
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
|
|
379
|
-
${handlers}
|
|
380
|
-
generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
|
|
381
|
-
document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
|
|
382
|
-
outputFile: { path: '${outputPath}' }
|
|
383
|
-
});
|
|
384
|
-
`;
|
|
253
|
+
const missingPackages = (packages)=>{
|
|
254
|
+
const missing = [
|
|
255
|
+
...new Set(packages)
|
|
256
|
+
].filter((name)=>!hasDependency(name));
|
|
257
|
+
return missing.length ? [
|
|
258
|
+
`npm i ${missing.join(' ')}`
|
|
259
|
+
] : [];
|
|
385
260
|
};
|
|
386
|
-
const
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
261
|
+
const missingDomainFirstPackages = ()=>missingPackages(ConfigFile.Instance.data.domainFirstPackages);
|
|
262
|
+
const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
|
|
263
|
+
class NestedName {
|
|
264
|
+
folders;
|
|
265
|
+
folderName;
|
|
266
|
+
fileName;
|
|
267
|
+
ClassName;
|
|
268
|
+
classNameSegments;
|
|
269
|
+
constructor(rawSource){
|
|
270
|
+
const segments = splitSegments(rawSource);
|
|
271
|
+
this.folders = segments.slice(0, -1);
|
|
272
|
+
this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
|
|
273
|
+
this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
|
|
274
|
+
this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
|
|
275
|
+
this.ClassName = this.classNameSegments.join('');
|
|
276
|
+
}
|
|
277
|
+
static validate = (rawSource)=>{
|
|
278
|
+
const segments = splitSegments(rawSource);
|
|
279
|
+
if (!segments.length) return 'Name is required';
|
|
280
|
+
if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
|
|
281
|
+
return true;
|
|
394
282
|
};
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
283
|
+
}
|
|
284
|
+
const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
|
|
285
|
+
${[
|
|
286
|
+
...imports,
|
|
287
|
+
"import { type FC } from 'react'"
|
|
288
|
+
].join('\n')}
|
|
289
|
+
|
|
290
|
+
export type ${ClassName}PageProps = {}
|
|
291
|
+
|
|
292
|
+
export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
|
|
293
|
+
return ${body}
|
|
294
|
+
}
|
|
295
|
+
`.trim();
|
|
296
|
+
const scaffoldReactPage = async (presentationReactFolder)=>{
|
|
297
|
+
const name = await input({
|
|
298
|
+
message: 'Provide name (folders split by "/"):',
|
|
299
|
+
validate: NestedName.validate
|
|
411
300
|
});
|
|
412
|
-
const
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
}
|
|
418
|
-
const generatorFile = new File(node_path.join(root, openapiScriptPath));
|
|
419
|
-
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
|
|
420
|
-
if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
|
|
421
|
-
if (withSwaggerPage) {
|
|
422
|
-
const pageFile = new File(node_path.join(root, swaggerPagePath(rootFolder)));
|
|
423
|
-
const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
|
|
424
|
-
if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
|
|
425
|
-
}
|
|
426
|
-
const resolveJsonModule = withSwaggerPage ? compilerOption(node_path.join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
|
|
427
|
-
const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
|
|
428
|
-
const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
|
|
429
|
-
return [
|
|
430
|
-
...dependencies['@domain-first/handlers-rest'] ? [] : [
|
|
431
|
-
'npm install @domain-first/handlers-rest'
|
|
432
|
-
],
|
|
433
|
-
...dependencies.tsx ? [] : [
|
|
434
|
-
'npm install --save-dev tsx'
|
|
435
|
-
],
|
|
436
|
-
...missingExtractorPackages.length ? [
|
|
437
|
-
`npm install --save-dev ${missingExtractorPackages.join(' ')}`
|
|
438
|
-
] : [],
|
|
439
|
-
...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
|
|
440
|
-
'npm install swagger-ui-react'
|
|
441
|
-
] : [],
|
|
442
|
-
...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
|
|
443
|
-
'npm install --save-dev @types/swagger-ui-react'
|
|
444
|
-
] : [],
|
|
445
|
-
...true === resolveJsonModule || null === resolveJsonModule ? [] : [
|
|
446
|
-
'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
|
|
447
|
-
],
|
|
448
|
-
...describeScripts(selected, {
|
|
449
|
-
openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
|
|
450
|
-
}),
|
|
451
|
-
...withSwaggerPage ? [
|
|
452
|
-
`SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
|
|
453
|
-
] : [],
|
|
454
|
-
...hasRestHandlers ? [] : [
|
|
455
|
-
`restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
|
|
456
|
-
]
|
|
457
|
-
];
|
|
301
|
+
const { folders, ClassName, fileName } = new NestedName(name);
|
|
302
|
+
presentationReactFolder.subitem([
|
|
303
|
+
'pages',
|
|
304
|
+
...folders
|
|
305
|
+
]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
|
|
458
306
|
};
|
|
459
|
-
const
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
307
|
+
const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
|
|
308
|
+
const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
|
|
309
|
+
const openapiExtractor = (rootFolder)=>`import path from 'node:path';
|
|
310
|
+
import {
|
|
311
|
+
type DocNode,
|
|
312
|
+
DocPlainText,
|
|
313
|
+
TSDocConfiguration,
|
|
314
|
+
TSDocParser,
|
|
315
|
+
TSDocTagDefinition,
|
|
316
|
+
TSDocTagSyntaxKind
|
|
317
|
+
} from '@microsoft/tsdoc';
|
|
318
|
+
import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
|
|
319
|
+
|
|
320
|
+
type BlockTag = \`@\${string}\`;
|
|
321
|
+
|
|
322
|
+
type OpenApiDataTags = {
|
|
323
|
+
/** Omit to take the summary from the comment text before the first tag. */
|
|
324
|
+
summary?: BlockTag;
|
|
325
|
+
description?: BlockTag;
|
|
465
326
|
};
|
|
466
|
-
const dataLayerFolder = (rootFolder, target)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'hooks' === target ? 'presentation/react/data-layer' : 'presentation/data-layer');
|
|
467
|
-
const orvalScripts = (rootFolder, targets)=>({
|
|
468
|
-
'client:orval': targets.map((target)=>`orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder, target)}/orval.config.ts`)}`).join(' && ')
|
|
469
|
-
});
|
|
470
|
-
const orvalConfig = (rootFolder, openapiPath, withNext, target = 'hooks', mutatorPath = './api-client/mutator.ts')=>{
|
|
471
|
-
const inputPath = node_path.posix.relative(dataLayerFolder(rootFolder, target), openapiPath);
|
|
472
|
-
const baseUrl = withNext ? `
|
|
473
|
-
baseUrl: {
|
|
474
|
-
runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
|
|
475
|
-
},` : '';
|
|
476
|
-
const client = 'hooks' === target ? `
|
|
477
|
-
client: 'react-query',
|
|
478
|
-
httpClient: 'fetch',` : `
|
|
479
|
-
client: 'fetch',`;
|
|
480
|
-
const query = 'hooks' === target ? `,
|
|
481
|
-
query: {
|
|
482
|
-
version: 5
|
|
483
|
-
}` : '';
|
|
484
|
-
return `import { defineConfig } from 'orval';
|
|
485
327
|
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
override: {
|
|
495
|
-
mutator: {
|
|
496
|
-
path: '${mutatorPath}',
|
|
497
|
-
name: 'customInstance'
|
|
498
|
-
},
|
|
499
|
-
fetch: {
|
|
500
|
-
includeHttpResponseReturnType: false
|
|
501
|
-
}${query}
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
}
|
|
328
|
+
type OpenApiData = Partial<{
|
|
329
|
+
summary: string;
|
|
330
|
+
description: string;
|
|
331
|
+
operationId: string;
|
|
332
|
+
}>;
|
|
333
|
+
|
|
334
|
+
const project = new Project({
|
|
335
|
+
tsConfigFilePath: 'tsconfig.json'
|
|
505
336
|
});
|
|
506
|
-
`;
|
|
507
|
-
};
|
|
508
|
-
const orvalMutator = `/** Error of the generated requests, with the parsed response body. */
|
|
509
|
-
export class ApiError<Body = unknown> extends Error {
|
|
510
|
-
constructor(
|
|
511
|
-
public readonly status: number,
|
|
512
|
-
public readonly body: Body
|
|
513
|
-
) {
|
|
514
|
-
super(\`API error \${status}\`);
|
|
515
|
-
this.name = 'ApiError';
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
337
|
|
|
519
|
-
|
|
520
|
-
|
|
338
|
+
const getText = (node: DocNode): string =>
|
|
339
|
+
node
|
|
340
|
+
.getChildNodes()
|
|
341
|
+
.map((child) => {
|
|
342
|
+
if (child instanceof DocPlainText) {
|
|
343
|
+
return child.text;
|
|
344
|
+
}
|
|
521
345
|
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
init?: RequestInit
|
|
526
|
-
): Promise<T> => {
|
|
527
|
-
const response = await fetch(url, init);
|
|
528
|
-
const text = await response.text();
|
|
529
|
-
const body = text ? JSON.parse(text) : undefined;
|
|
346
|
+
return getText(child);
|
|
347
|
+
})
|
|
348
|
+
.join('');
|
|
530
349
|
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
350
|
+
const getRawCommentText = (comment: string): string =>
|
|
351
|
+
comment
|
|
352
|
+
.replace(/^\\/\\*\\*/, '')
|
|
353
|
+
.replace(/\\*\\/$/, '')
|
|
354
|
+
.split(/\\r?\\n/)
|
|
355
|
+
.map((line) => line.replace(/^\\s*\\*\\s?/, ''))
|
|
356
|
+
.join('\\n');
|
|
534
357
|
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
const
|
|
358
|
+
// TSDoc treats an unknown tag as summary content, so every block tag of the
|
|
359
|
+
// comment has to be registered for the summary section to end before it.
|
|
360
|
+
const parseSummary = (comment: string): string | undefined => {
|
|
361
|
+
const configuration = new TSDocConfiguration();
|
|
362
|
+
const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
|
|
539
363
|
|
|
540
|
-
|
|
541
|
-
|
|
364
|
+
for (const [, tagName] of tagNames) {
|
|
365
|
+
if (!configuration.tryGetTagDefinition(tagName)) {
|
|
366
|
+
configuration.addTagDefinition(
|
|
367
|
+
new TSDocTagDefinition({
|
|
368
|
+
tagName,
|
|
369
|
+
syntaxKind: TSDocTagSyntaxKind.BlockTag
|
|
370
|
+
})
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
542
374
|
|
|
543
|
-
|
|
544
|
-
// One client per browser session; a module-level client would be shared between requests on the server
|
|
545
|
-
const [queryClient] = useState(() => new QueryClient());
|
|
375
|
+
const { docComment } = new TSDocParser(configuration).parseString(comment);
|
|
546
376
|
|
|
547
|
-
return (
|
|
548
|
-
<QueryClientProvider client={queryClient}>
|
|
549
|
-
{children}
|
|
550
|
-
</QueryClientProvider>
|
|
551
|
-
);
|
|
377
|
+
return getText(docComment.summarySection).trim() || undefined;
|
|
552
378
|
};
|
|
553
|
-
`;
|
|
554
|
-
const openapiOutputPath = (root)=>{
|
|
555
|
-
const generator = new File(node_path.join(root, openapiScriptPath));
|
|
556
|
-
if (!generator.exists) return;
|
|
557
|
-
return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
|
|
558
|
-
};
|
|
559
|
-
const addOrval = async ()=>{
|
|
560
|
-
const { rootFolder, useReact } = ConfigFile.Instance.data;
|
|
561
|
-
const root = new ProjectRoot().path;
|
|
562
|
-
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
563
|
-
const manifest = JSON.parse(manifestFile.data);
|
|
564
|
-
const dependencies = {
|
|
565
|
-
...manifest.dependencies,
|
|
566
|
-
...manifest.devDependencies
|
|
567
|
-
};
|
|
568
|
-
const withNext = Boolean(dependencies.next);
|
|
569
|
-
const generatedOpenapiPath = openapiOutputPath(root);
|
|
570
|
-
const openapiPath = await input({
|
|
571
|
-
message: 'OpenAPI document path:',
|
|
572
|
-
default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
|
|
573
|
-
validate: (value)=>value.trim() ? true : 'Path is required'
|
|
574
|
-
});
|
|
575
|
-
const targets = useReact ? await prompts_checkbox({
|
|
576
|
-
message: 'Generate:',
|
|
577
|
-
choices: [
|
|
578
|
-
{
|
|
579
|
-
name: 'React Query hooks',
|
|
580
|
-
value: 'hooks',
|
|
581
|
-
checked: true
|
|
582
|
-
},
|
|
583
|
-
{
|
|
584
|
-
name: 'Typed API client',
|
|
585
|
-
value: 'client'
|
|
586
|
-
}
|
|
587
|
-
],
|
|
588
|
-
required: true
|
|
589
|
-
}) : [
|
|
590
|
-
'client'
|
|
591
|
-
];
|
|
592
|
-
const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder, targets));
|
|
593
|
-
const document = node_path.posix.normalize(openapiPath.trim().replaceAll('\\', '/'));
|
|
594
|
-
const withClient = targets.includes('client');
|
|
595
|
-
for (const target of targets){
|
|
596
|
-
const dataLayer = dataLayerFolder(rootFolder, target);
|
|
597
|
-
const sharedMutator = 'hooks' === target && withClient;
|
|
598
|
-
const mutatorPath = sharedMutator ? `${node_path.posix.relative(dataLayer, dataLayerFolder(rootFolder, 'client'))}/api-client/mutator.ts` : void 0;
|
|
599
|
-
const configFile = new File(node_path.join(root, dataLayer, 'orval.config.ts'));
|
|
600
|
-
const content = orvalConfig(rootFolder, document, withNext, target, mutatorPath);
|
|
601
|
-
if (!configFile.exists || configFile.data !== content) configFile.data = content;
|
|
602
|
-
for (const [name, fileContent] of [
|
|
603
|
-
...sharedMutator ? [] : [
|
|
604
|
-
[
|
|
605
|
-
'api-client/mutator.ts',
|
|
606
|
-
orvalMutator
|
|
607
|
-
]
|
|
608
|
-
],
|
|
609
|
-
...'hooks' === target ? [
|
|
610
|
-
[
|
|
611
|
-
'query-provider.tsx',
|
|
612
|
-
queryProvider
|
|
613
|
-
]
|
|
614
|
-
] : []
|
|
615
|
-
]){
|
|
616
|
-
const file = new File(node_path.join(root, dataLayer, name));
|
|
617
|
-
if (!file.exists) file.data = fileContent;
|
|
618
|
-
}
|
|
619
|
-
addGitignoreEntry(root, `/${dataLayer}/orval/`);
|
|
620
|
-
}
|
|
621
|
-
const generated = targets.map((target)=>'hooks' === target ? `React Query hooks in ${dataLayerFolder(rootFolder, 'hooks')}/orval` : `a typed API client in ${dataLayerFolder(rootFolder, 'client')}/orval`);
|
|
622
|
-
const missing = (names)=>names.filter((name)=>!dependencies[name]);
|
|
623
|
-
const runtime = missing(targets.includes('hooks') ? [
|
|
624
|
-
'@tanstack/react-query'
|
|
625
|
-
] : []);
|
|
626
|
-
const development = missing([
|
|
627
|
-
'orval'
|
|
628
|
-
]);
|
|
629
|
-
return [
|
|
630
|
-
...runtime.length ? [
|
|
631
|
-
`npm install ${runtime.join(' ')}`
|
|
632
|
-
] : [],
|
|
633
|
-
...development.length ? [
|
|
634
|
-
`npm install --save-dev ${development.join(' ')}`
|
|
635
|
-
] : [],
|
|
636
|
-
...describeScripts(selected, {
|
|
637
|
-
'client:orval': `generate ${generated.join(' and ')} from ${openapiPath.trim()}`
|
|
638
|
-
}),
|
|
639
|
-
...targets.includes('hooks') ? [
|
|
640
|
-
`Wrap your app in QueryProvider from ${dataLayerFolder(rootFolder, 'hooks')}/query-provider.tsx`
|
|
641
|
-
] : [],
|
|
642
|
-
...generatedOpenapiPath ? [] : [
|
|
643
|
-
'npx df-integration → OpenAPI generates the OpenAPI document the client is built from'
|
|
644
|
-
]
|
|
645
|
-
];
|
|
646
|
-
};
|
|
647
|
-
const playwrightScripts = {
|
|
648
|
-
'test:e2e': 'playwright test'
|
|
649
|
-
};
|
|
650
|
-
const playwrightConfig = `import { defineConfig, devices } from '@playwright/test';
|
|
651
|
-
|
|
652
|
-
export default defineConfig({
|
|
653
|
-
testDir: './specs/e2e',
|
|
654
|
-
fullyParallel: true,
|
|
655
|
-
forbidOnly: !!process.env.CI,
|
|
656
|
-
retries: process.env.CI ? 2 : 0,
|
|
657
|
-
workers: process.env.CI ? 1 : undefined,
|
|
658
|
-
reporter: 'html',
|
|
659
|
-
use: {
|
|
660
|
-
baseURL: 'http://localhost:3000',
|
|
661
|
-
trace: 'on-first-retry',
|
|
662
|
-
screenshot: 'only-on-failure',
|
|
663
|
-
video: 'retain-on-failure'
|
|
664
|
-
},
|
|
665
|
-
|
|
666
|
-
projects: [
|
|
667
|
-
{
|
|
668
|
-
name: 'chromium',
|
|
669
|
-
use: { ...devices['Desktop Chrome'] }
|
|
670
|
-
},
|
|
671
|
-
{
|
|
672
|
-
name: 'firefox',
|
|
673
|
-
use: { ...devices['Desktop Firefox'] }
|
|
674
|
-
},
|
|
675
|
-
{
|
|
676
|
-
name: 'webkit',
|
|
677
|
-
use: { ...devices['Desktop Safari'] }
|
|
678
|
-
},
|
|
679
|
-
{
|
|
680
|
-
name: 'Mobile Chrome',
|
|
681
|
-
use: { ...devices['Pixel 5'] }
|
|
682
|
-
},
|
|
683
|
-
{
|
|
684
|
-
name: 'Mobile Safari',
|
|
685
|
-
use: { ...devices['iPhone 12'] }
|
|
686
|
-
}
|
|
687
|
-
],
|
|
688
|
-
|
|
689
|
-
webServer: {
|
|
690
|
-
// Playwright only stops the dev server on a clean shutdown. If its process dies any other
|
|
691
|
-
// way (SIGHUP, SIGKILL), the dev server lives on in its own process group, so it is killed
|
|
692
|
-
// as soon as Playwright is gone.
|
|
693
|
-
command:
|
|
694
|
-
process.platform === 'win32'
|
|
695
|
-
? 'npm run dev'
|
|
696
|
-
: \`npm run dev & while kill -0 \${process.pid} 2>/dev/null && kill -0 $! 2>/dev/null; do sleep 1; done; kill 0\`,
|
|
697
|
-
url: 'http://localhost:3000',
|
|
698
|
-
timeout: 120000,
|
|
699
|
-
reuseExistingServer: !process.env.CI
|
|
700
|
-
}
|
|
701
|
-
});
|
|
702
|
-
`;
|
|
703
|
-
const exampleSpec = `import { expect, test } from '@playwright/test';
|
|
704
|
-
|
|
705
|
-
test.describe('home page', () => {
|
|
706
|
-
test('opens the home page', async ({ page, baseURL }) => {
|
|
707
|
-
await page.goto('/');
|
|
708
|
-
await expect(page).toHaveURL(\`\${baseURL}/\`);
|
|
709
|
-
});
|
|
710
|
-
});
|
|
711
|
-
`;
|
|
712
|
-
const exampleReadme = `# Home page e2e cases
|
|
713
|
-
|
|
714
|
-
## User Stories
|
|
715
|
-
|
|
716
|
-
1. Guest opens \`/\` and stays on the home page.
|
|
717
|
-
`;
|
|
718
|
-
const gitignoreEntries = [
|
|
719
|
-
'/test-results/',
|
|
720
|
-
'/playwright-report/',
|
|
721
|
-
'/blob-report/',
|
|
722
|
-
'/playwright/.cache/',
|
|
723
|
-
'/playwright/.auth/'
|
|
724
|
-
];
|
|
725
|
-
const addPlaywright = async ()=>{
|
|
726
|
-
const root = new ProjectRoot().path;
|
|
727
|
-
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
728
|
-
const manifest = JSON.parse(manifestFile.data);
|
|
729
|
-
const dependencies = {
|
|
730
|
-
...manifest.dependencies,
|
|
731
|
-
...manifest.devDependencies
|
|
732
|
-
};
|
|
733
|
-
const selected = await addPackageScripts(manifestFile, playwrightScripts);
|
|
734
|
-
const configFile = new File(node_path.join(root, 'playwright.config.ts'));
|
|
735
|
-
if (!configFile.exists || configFile.data !== playwrightConfig) configFile.data = playwrightConfig;
|
|
736
|
-
const exampleFolder = node_path.join(root, 'specs/e2e/home');
|
|
737
|
-
for (const [name, content] of [
|
|
738
|
-
[
|
|
739
|
-
'home.e2e.spec.ts',
|
|
740
|
-
exampleSpec
|
|
741
|
-
],
|
|
742
|
-
[
|
|
743
|
-
'README.MD',
|
|
744
|
-
exampleReadme
|
|
745
|
-
]
|
|
746
|
-
]){
|
|
747
|
-
const file = new File(node_path.join(exampleFolder, name));
|
|
748
|
-
if (!file.exists) file.data = content;
|
|
749
|
-
}
|
|
750
|
-
for (const entry of gitignoreEntries)addGitignoreEntry(root, entry);
|
|
751
|
-
return [
|
|
752
|
-
...dependencies['@playwright/test'] ? [] : [
|
|
753
|
-
'npm install --save-dev @playwright/test'
|
|
754
|
-
],
|
|
755
|
-
'npx playwright install --with-deps',
|
|
756
|
-
...describeScripts(selected, {
|
|
757
|
-
'test:e2e': 'start the dev server and run end-to-end specs from specs/e2e'
|
|
758
|
-
})
|
|
759
|
-
];
|
|
760
|
-
};
|
|
761
|
-
const runtimePackages = [
|
|
762
|
-
'@prisma/orm-postgres',
|
|
763
|
-
'temporal-polyfill',
|
|
764
|
-
'dotenv'
|
|
765
|
-
];
|
|
766
|
-
const developmentPackages = [
|
|
767
|
-
'prisma',
|
|
768
|
-
'@prisma/cli-engine'
|
|
769
|
-
];
|
|
770
|
-
const prismaScripts = (rootFolder)=>{
|
|
771
|
-
const config = JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared/infrastructure/prisma/prisma.config.ts'));
|
|
772
|
-
const emit = `prisma contract emit --config ${config}`;
|
|
773
|
-
return {
|
|
774
|
-
'prisma:emit': emit,
|
|
775
|
-
'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
|
|
776
|
-
'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
|
|
777
|
-
};
|
|
778
|
-
};
|
|
779
|
-
const prismaConfig = `import 'dotenv/config';
|
|
780
|
-
import { definePrismaConfig } from '@prisma/cli-engine';
|
|
781
|
-
import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
|
|
782
|
-
|
|
783
|
-
export default definePrismaConfig({
|
|
784
|
-
orm: ormConfig({
|
|
785
|
-
contract: './contract.prisma',
|
|
786
|
-
migrations: { dir: './migrations' },
|
|
787
|
-
db: {
|
|
788
|
-
connection: process.env.DATABASE_URL
|
|
789
|
-
}
|
|
790
|
-
})
|
|
791
|
-
});
|
|
792
|
-
`;
|
|
793
|
-
const prismaService = `import 'temporal-polyfill/global';
|
|
794
|
-
import postgres from '@prisma/orm-postgres/runtime';
|
|
795
|
-
import type {} from 'temporal-polyfill/types/global';
|
|
796
|
-
import type { Contract } from '../prisma/contract.d';
|
|
797
|
-
import contractJson from '../prisma/contract.json' with { type: 'json' };
|
|
798
|
-
|
|
799
|
-
type PrismaClient = ReturnType<typeof postgres<Contract>>;
|
|
800
|
-
|
|
801
|
-
const globalForPrisma = globalThis as typeof globalThis & {
|
|
802
|
-
prismaClient?: PrismaClient;
|
|
803
|
-
};
|
|
804
|
-
|
|
805
|
-
// Reuse the client across development hot reloads.
|
|
806
|
-
const prismaClient = globalForPrisma.prismaClient ??
|
|
807
|
-
postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
|
|
808
|
-
|
|
809
|
-
if (process.env.NODE_ENV !== 'production') {
|
|
810
|
-
globalForPrisma.prismaClient = prismaClient;
|
|
811
|
-
}
|
|
812
|
-
|
|
813
|
-
export class PrismaInfrastructureService {
|
|
814
|
-
readonly orm = prismaClient.orm.public;
|
|
815
|
-
}
|
|
816
|
-
`;
|
|
817
|
-
const prismaWiring = `import { wireClass } from '@domain-first/wire';
|
|
818
|
-
import { PrismaInfrastructureService } from '../../infrastructure/services/prisma-infrastructure-service';
|
|
819
|
-
|
|
820
|
-
export const wirePrismaInfrastructureService = wireClass(
|
|
821
|
-
PrismaInfrastructureService,
|
|
822
|
-
[]
|
|
823
|
-
);
|
|
824
|
-
`;
|
|
825
|
-
const stageFile = (filePath, content)=>{
|
|
826
|
-
const file = new File(filePath);
|
|
827
|
-
if (!file.exists || file.data !== content) file.data = content;
|
|
828
|
-
};
|
|
829
|
-
const addPrisma = async ()=>{
|
|
830
|
-
const config = ConfigFile.Instance.data;
|
|
831
|
-
const root = new ProjectRoot().path;
|
|
832
|
-
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
833
|
-
const manifest = JSON.parse(manifestFile.data);
|
|
834
|
-
const dependencies = {
|
|
835
|
-
...manifest.dependencies,
|
|
836
|
-
...manifest.devDependencies
|
|
837
|
-
};
|
|
838
|
-
const shared = node_path.resolve(root, config.rootFolder, 'shared');
|
|
839
|
-
const prismaFolder = node_path.join(shared, 'infrastructure/prisma');
|
|
840
|
-
if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
|
|
841
|
-
node_path.join(root, 'prisma/schema.prisma'),
|
|
842
|
-
node_path.join(prismaFolder, 'schema.prisma')
|
|
843
|
-
].some((filePath)=>new File(filePath).exists)) throw new Error('This preset adds Prisma 8 for PostgreSQL. Migrate the existing Prisma setup separately before using it.');
|
|
844
|
-
const withService = await prompts_confirm({
|
|
845
|
-
message: 'Create shared Prisma infrastructure service?',
|
|
846
|
-
default: true
|
|
847
|
-
});
|
|
848
|
-
const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await prompts_confirm({
|
|
849
|
-
message: 'Use prisma as the default persistence implementation?',
|
|
850
|
-
default: false
|
|
851
|
-
});
|
|
852
|
-
const selected = await addPackageScripts(manifestFile, prismaScripts(config.rootFolder));
|
|
853
|
-
stageFile(node_path.join(prismaFolder, 'prisma.config.ts'), prismaConfig);
|
|
854
|
-
const contract = new File(node_path.join(prismaFolder, 'contract.prisma'));
|
|
855
|
-
if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
|
|
856
|
-
if (withService) {
|
|
857
|
-
stageFile(node_path.join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
|
|
858
|
-
if (config.domainFirstPackages.includes('@domain-first/wire')) stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
|
|
859
|
-
}
|
|
860
|
-
if (useByDefault) ConfigFile.write({
|
|
861
|
-
...config,
|
|
862
|
-
defaultPersistenceLayerImplementation: 'prisma'
|
|
863
|
-
});
|
|
864
|
-
const install = (packages, dev)=>{
|
|
865
|
-
const missing = packages.filter((name)=>!dependencies[name]);
|
|
866
|
-
return missing.length ? [
|
|
867
|
-
`npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
|
|
868
|
-
] : [];
|
|
869
|
-
};
|
|
870
|
-
const relativeFolder = node_path.relative(root, prismaFolder).split(node_path.sep).join('/');
|
|
871
|
-
return [
|
|
872
|
-
...install(runtimePackages, false),
|
|
873
|
-
...install(developmentPackages, true),
|
|
874
|
-
`Add !${relativeFolder} in your linter, to ignore prisma files.`,
|
|
875
|
-
...describeScripts(selected, {
|
|
876
|
-
'prisma:emit': 'emit contract.json and contract.d.ts from contract.prisma',
|
|
877
|
-
'prisma:migration:plan': 'emit the contract and plan a migration',
|
|
878
|
-
'prisma:migration:apply': 'apply planned migrations to the database in DATABASE_URL'
|
|
879
|
-
})
|
|
880
|
-
];
|
|
881
|
-
};
|
|
882
|
-
const storybookFiles = (relativeProjectRoot)=>({
|
|
883
|
-
'main.ts': `import { resolve } from 'node:path';
|
|
884
|
-
import react from '@vitejs/plugin-react';
|
|
885
|
-
import type { StorybookConfig } from '@storybook/react-vite';
|
|
886
379
|
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
const
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
},
|
|
895
|
-
core: {
|
|
896
|
-
disableTelemetry: true
|
|
897
|
-
},
|
|
898
|
-
async viteFinal(viteConfig) {
|
|
899
|
-
const { mergeConfig } = await import('vite');
|
|
380
|
+
// Parsed by hand rather than through TSDoc, which drops the line breaks.
|
|
381
|
+
const getTagText = (comment: string, tag: BlockTag): string | undefined => {
|
|
382
|
+
const tagMatch = getRawCommentText(comment).match(
|
|
383
|
+
new RegExp(
|
|
384
|
+
\`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
|
|
385
|
+
)
|
|
386
|
+
);
|
|
900
387
|
|
|
901
|
-
|
|
902
|
-
plugins: [react()],
|
|
903
|
-
resolve: {
|
|
904
|
-
alias: {
|
|
905
|
-
'@': projectRoot
|
|
906
|
-
}
|
|
907
|
-
}
|
|
908
|
-
});
|
|
909
|
-
}
|
|
388
|
+
return tagMatch?.[1].trim() || undefined;
|
|
910
389
|
};
|
|
911
390
|
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
391
|
+
// Endpoints pass their logic as the generator's first argument
|
|
392
|
+
// (\`this.endpointGenerator(this.handler.handle, ...)\`), while other injected
|
|
393
|
+
// queries only serve as helpers, e.g. guest checks.
|
|
394
|
+
const findHandlerClass = (endpointFile: SourceFile) =>
|
|
395
|
+
endpointFile
|
|
396
|
+
.getDescendantsOfKind(SyntaxKind.CallExpression)
|
|
397
|
+
.map((call) => call.getArguments()[0])
|
|
398
|
+
.filter(Node.isPropertyAccessExpression)
|
|
399
|
+
.find((argument) => argument.getName() === 'handle')
|
|
400
|
+
?.getExpression()
|
|
401
|
+
.getType()
|
|
402
|
+
.getSymbol()
|
|
403
|
+
?.getDeclarations()
|
|
404
|
+
.find(Node.isClassDeclaration);
|
|
915
405
|
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
color: /(background|color)$/i,
|
|
921
|
-
date: /Date$/i
|
|
922
|
-
}
|
|
923
|
-
}
|
|
924
|
-
}
|
|
925
|
-
};
|
|
406
|
+
// Path parameters (\`:id\`) can't be part of file and folder names
|
|
407
|
+
// everywhere (Windows), so endpoints name them \`_id_\` there.
|
|
408
|
+
const pathParameterAsName = (segment: string) =>
|
|
409
|
+
segment.startsWith(':') ? \`_\${segment.slice(1)}_\` : segment;
|
|
926
410
|
|
|
927
|
-
export
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
const addStorybook = async ()=>{
|
|
939
|
-
const config = ConfigFile.Instance.data;
|
|
940
|
-
if ((!config.useReact || config.storybookFramework && '@storybook/react-vite' !== config.storybookFramework) && !await prompts_confirm({
|
|
941
|
-
message: 'Configure React scaffolding with @storybook/react-vite?',
|
|
942
|
-
default: false
|
|
943
|
-
})) return [];
|
|
944
|
-
const root = new ProjectRoot().path;
|
|
945
|
-
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
946
|
-
const manifest = JSON.parse(manifestFile.data);
|
|
947
|
-
const selected = await addPackageScripts(manifestFile, storybookScripts(config.rootFolder));
|
|
948
|
-
const folder = new Folder(root).subitem([
|
|
949
|
-
config.rootFolder,
|
|
950
|
-
'presentation',
|
|
951
|
-
'react',
|
|
952
|
-
'.storybook'
|
|
953
|
-
]);
|
|
954
|
-
for (const [name, content] of Object.entries(storybookFiles(node_path.relative(folder.path, root).split(node_path.sep).join('/')))){
|
|
955
|
-
const file = new File(node_path.join(folder.path, name));
|
|
956
|
-
if (!file.exists || file.data !== content) file.data = content;
|
|
957
|
-
}
|
|
958
|
-
if (!config.useReact || '@storybook/react-vite' !== config.storybookFramework) ConfigFile.write({
|
|
959
|
-
...config,
|
|
960
|
-
useReact: true,
|
|
961
|
-
storybookFramework: '@storybook/react-vite'
|
|
962
|
-
});
|
|
963
|
-
const buildFolder = node_path.posix.join(config.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
|
|
964
|
-
addGitignoreEntry(root, `/${buildFolder}/`);
|
|
965
|
-
const dependencies = {
|
|
966
|
-
...manifest.dependencies,
|
|
967
|
-
...manifest.devDependencies
|
|
968
|
-
};
|
|
969
|
-
const missing = [
|
|
970
|
-
'storybook',
|
|
971
|
-
'@storybook/react-vite',
|
|
972
|
-
'vite',
|
|
973
|
-
'@vitejs/plugin-react'
|
|
974
|
-
].filter((name)=>!dependencies[name]);
|
|
975
|
-
const missingReact = [
|
|
976
|
-
'react',
|
|
977
|
-
'react-dom'
|
|
978
|
-
].filter((name)=>!dependencies[name]);
|
|
979
|
-
return [
|
|
980
|
-
...missing.length ? [
|
|
981
|
-
`npm install --save-dev ${missing.join(' ')}`
|
|
982
|
-
] : [],
|
|
983
|
-
...missingReact.length ? [
|
|
984
|
-
`npm install ${missingReact.join(' ')}`
|
|
985
|
-
] : [],
|
|
986
|
-
...describeScripts(selected, {
|
|
987
|
-
storybook: 'start Storybook on http://localhost:6006',
|
|
988
|
-
'build-storybook': `build static Storybook into ${buildFolder}`
|
|
989
|
-
})
|
|
990
|
-
];
|
|
991
|
-
};
|
|
992
|
-
const integrationFolder = 'specs/integration';
|
|
993
|
-
const testcontainersScripts = {
|
|
994
|
-
'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
|
|
995
|
-
};
|
|
996
|
-
const testcontainersVitestConfig = (inlineHandlersNext)=>{
|
|
997
|
-
const server = inlineHandlersNext ? `,
|
|
998
|
-
server: {
|
|
999
|
-
deps: {
|
|
1000
|
-
// Imports \`next/headers\` without an extension, which only a bundler can resolve
|
|
1001
|
-
inline: ['@domain-first/handlers-next']
|
|
1002
|
-
}
|
|
1003
|
-
}` : '';
|
|
1004
|
-
return `import { fileURLToPath } from 'node:url';
|
|
1005
|
-
import { defineConfig } from 'vitest/config';
|
|
411
|
+
export const createOpenApiDataFromEndpointLogicExtractor = ({
|
|
412
|
+
summary: summaryTag,
|
|
413
|
+
description: descriptionTag = '@description'
|
|
414
|
+
}: OpenApiDataTags = {}) => {
|
|
415
|
+
return (routeMetadata: {
|
|
416
|
+
method: string;
|
|
417
|
+
path: readonly string[];
|
|
418
|
+
}): OpenApiData | undefined => {
|
|
419
|
+
try {
|
|
420
|
+
const [currentBoundedContext, controller, ...relativePath] =
|
|
421
|
+
routeMetadata.path;
|
|
1006
422
|
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
root: fileURLToPath(new URL('../..', import.meta.url)),
|
|
1011
|
-
resolve: {
|
|
1012
|
-
tsconfigPaths: true
|
|
1013
|
-
},
|
|
1014
|
-
test: {
|
|
1015
|
-
include: ['${integrationFolder}/**/*.spec.ts'],
|
|
1016
|
-
// Development implementations work with the real database
|
|
1017
|
-
env: { NODE_ENV: 'development' },
|
|
1018
|
-
globalSetup: ['${integrationFolder}/global-setup.ts'],
|
|
1019
|
-
setupFiles: ['${integrationFolder}/setup-env.ts'],
|
|
1020
|
-
// Pulling the image on the first run takes a while
|
|
1021
|
-
hookTimeout: 120_000${server}
|
|
1022
|
-
}
|
|
1023
|
-
});
|
|
1024
|
-
`;
|
|
1025
|
-
};
|
|
1026
|
-
const testcontainersGlobalSetup = (migrationCommand)=>{
|
|
1027
|
-
const migrations = migrationCommand ? `
|
|
1028
|
-
// dotenv in the Prisma config does not override an already set variable
|
|
1029
|
-
execSync(${JSON.stringify(migrationCommand)}, {
|
|
1030
|
-
cwd: project.config.root,
|
|
1031
|
-
env: { ...process.env, DATABASE_URL: databaseUrl },
|
|
1032
|
-
// On failure the error carries the command's output
|
|
1033
|
-
stdio: 'pipe'
|
|
1034
|
-
});
|
|
1035
|
-
` : `
|
|
1036
|
-
// Apply your migrations to databaseUrl here.
|
|
1037
|
-
`;
|
|
1038
|
-
return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
|
|
1039
|
-
import type { TestProject } from 'vitest/node';
|
|
423
|
+
if (!currentBoundedContext || !controller) {
|
|
424
|
+
return undefined;
|
|
425
|
+
}
|
|
1040
426
|
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
427
|
+
const endpointFile = project.getSourceFile(
|
|
428
|
+
path.join(
|
|
429
|
+
${rootFolderSegments(rootFolder)}'bounded-contexts',
|
|
430
|
+
currentBoundedContext,
|
|
431
|
+
'presentation',
|
|
432
|
+
'rest',
|
|
433
|
+
controller,
|
|
434
|
+
...relativePath.map(pathParameterAsName),
|
|
435
|
+
\`\${routeMetadata.method.toUpperCase()}.ts\`
|
|
436
|
+
)
|
|
437
|
+
);
|
|
1046
438
|
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
const POSTGRES_PASSWORD = 'test';
|
|
1051
|
-
const POSTGRES_DB = 'test';
|
|
439
|
+
if (!endpointFile) {
|
|
440
|
+
return undefined;
|
|
441
|
+
}
|
|
1052
442
|
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
.withExposedPorts(POSTGRES_PORT)
|
|
1057
|
-
// During init PostgreSQL listens on a unix socket only and restarts,
|
|
1058
|
-
// so checking over TCP passes once the final server is up
|
|
1059
|
-
.withHealthCheck({
|
|
1060
|
-
test: [
|
|
1061
|
-
'CMD-SHELL',
|
|
1062
|
-
\`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
|
|
1063
|
-
],
|
|
1064
|
-
interval: 250,
|
|
1065
|
-
timeout: 1000,
|
|
1066
|
-
retries: 1000
|
|
1067
|
-
})
|
|
1068
|
-
.withWaitStrategy(Wait.forHealthCheck())
|
|
1069
|
-
.withStartupTimeout(120_000)
|
|
1070
|
-
.start();
|
|
443
|
+
const declaration = findHandlerClass(endpointFile);
|
|
444
|
+
const operationId = declaration?.getName();
|
|
445
|
+
const comment = declaration?.getJsDocs().at(-1)?.getText();
|
|
1071
446
|
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
447
|
+
if (!comment) {
|
|
448
|
+
return { operationId };
|
|
449
|
+
}
|
|
1075
450
|
|
|
1076
|
-
|
|
1077
|
-
|
|
451
|
+
return {
|
|
452
|
+
summary: summaryTag
|
|
453
|
+
? getTagText(comment, summaryTag)
|
|
454
|
+
: parseSummary(comment),
|
|
455
|
+
description: getTagText(comment, descriptionTag),
|
|
456
|
+
operationId
|
|
457
|
+
};
|
|
458
|
+
} catch (e: unknown) {
|
|
459
|
+
console.error(e);
|
|
460
|
+
return undefined;
|
|
461
|
+
}
|
|
1078
462
|
};
|
|
1079
|
-
}
|
|
1080
|
-
`;
|
|
1081
463
|
};
|
|
1082
|
-
const testcontainersSetupEnv = `import 'dotenv/config';
|
|
1083
|
-
import { inject } from 'vitest';
|
|
1084
|
-
|
|
1085
|
-
// Runs before each spec's imports: development implementations get the .env
|
|
1086
|
-
// config, and DATABASE_URL points to the container instead of the one from .env.
|
|
1087
|
-
if (process.env.NODE_ENV !== 'development') {
|
|
1088
|
-
throw new Error(
|
|
1089
|
-
\`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
|
|
1090
|
-
);
|
|
1091
|
-
}
|
|
1092
|
-
|
|
1093
|
-
process.env.DATABASE_URL = inject('databaseUrl');
|
|
1094
464
|
`;
|
|
1095
|
-
const
|
|
465
|
+
const addPackageScripts = async (file, additions)=>{
|
|
466
|
+
const original = file.data;
|
|
467
|
+
const manifest = JSON.parse(original);
|
|
468
|
+
const scripts = {
|
|
469
|
+
...manifest.scripts
|
|
470
|
+
};
|
|
471
|
+
const selected = {};
|
|
472
|
+
for (const [name, command] of Object.entries(additions)){
|
|
473
|
+
let target = name;
|
|
474
|
+
if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
|
|
475
|
+
const action = await prompts_select({
|
|
476
|
+
message: `Script "${name}" already exists: ${scripts[name]}`,
|
|
477
|
+
choices: [
|
|
478
|
+
'Keep existing',
|
|
479
|
+
'Replace',
|
|
480
|
+
'Use another name'
|
|
481
|
+
]
|
|
482
|
+
});
|
|
483
|
+
if ('Keep existing' === action) continue;
|
|
484
|
+
if ('Use another name' === action) target = await input({
|
|
485
|
+
message: "New script name:",
|
|
486
|
+
validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
scripts[target] = command;
|
|
490
|
+
selected[name] = target;
|
|
491
|
+
}
|
|
492
|
+
if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
|
|
493
|
+
manifest.scripts = scripts;
|
|
494
|
+
const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
|
|
495
|
+
file.update(`${JSON.stringify(manifest, null, indent)}\n`);
|
|
496
|
+
}
|
|
497
|
+
return selected;
|
|
498
|
+
};
|
|
499
|
+
const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
|
|
500
|
+
const openapiScriptPath = "scripts/generate-openapi.ts";
|
|
501
|
+
const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
|
|
502
|
+
const extractorPackages = [
|
|
503
|
+
'ts-morph',
|
|
504
|
+
'@microsoft/tsdoc'
|
|
505
|
+
];
|
|
506
|
+
const swaggerPagePath = (rootFolder)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
|
|
507
|
+
const swaggerPage = (rootFolder, outputPath)=>{
|
|
508
|
+
const specImport = node_path.posix.relative(node_path.posix.dirname(swaggerPagePath(rootFolder)), outputPath);
|
|
509
|
+
return reactPageContent('Swagger', {
|
|
510
|
+
imports: [
|
|
511
|
+
"import 'swagger-ui-react/swagger-ui.css'",
|
|
512
|
+
"import SwaggerUI from 'swagger-ui-react'",
|
|
513
|
+
`import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
|
|
514
|
+
],
|
|
515
|
+
body: '<SwaggerUI displayOperationId spec={spec} />'
|
|
516
|
+
});
|
|
517
|
+
};
|
|
518
|
+
const openapiScripts = {
|
|
519
|
+
openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
|
|
520
|
+
};
|
|
521
|
+
const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
|
|
522
|
+
const apiTitle = (packageName)=>{
|
|
523
|
+
const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
|
|
524
|
+
return [
|
|
525
|
+
...words,
|
|
526
|
+
'API'
|
|
527
|
+
].join(' ');
|
|
528
|
+
};
|
|
529
|
+
const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
|
|
530
|
+
const restFolder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
|
|
531
|
+
const restImport = node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), restFolder);
|
|
532
|
+
const prefixSegments = splitPath(routePrefix);
|
|
533
|
+
const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
|
|
534
|
+
const extractorImport = `./${node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
|
|
535
|
+
const handlers = withExtractor ? `
|
|
536
|
+
const extractOpenApiDataFromEndpointLogic =
|
|
537
|
+
createOpenApiDataFromEndpointLogicExtractor();
|
|
1096
538
|
|
|
1097
|
-
|
|
1098
|
-
|
|
539
|
+
const handlers = restHandlers.map((x) => ({
|
|
540
|
+
...x,
|
|
541
|
+
metadata: {
|
|
542
|
+
...x.metadata,
|
|
543
|
+
openApiMetadata: {
|
|
544
|
+
...extractOpenApiDataFromEndpointLogic(x.metadata.route),
|
|
545
|
+
...(x.metadata.openApiMetadata ?? {})
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}));
|
|
549
|
+
` : '';
|
|
550
|
+
return `import { generateOpenAPI } from '@domain-first/handlers-rest';
|
|
551
|
+
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
|
|
552
|
+
${handlers}
|
|
553
|
+
generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
|
|
554
|
+
document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
|
|
555
|
+
outputFile: { path: '${outputPath}' }
|
|
1099
556
|
});
|
|
1100
557
|
`;
|
|
1101
|
-
const excludeFromUnitTests = (content)=>{
|
|
1102
|
-
const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
|
|
1103
|
-
if (!exclude.test(content)) return;
|
|
1104
|
-
const entry = `'${integrationFolder}/**'`;
|
|
1105
|
-
return content.replace(exclude, (_, items, comma, whitespace)=>{
|
|
1106
|
-
const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
|
|
1107
|
-
const separator = void 0 === indent ? ', ' : `,\n${indent}`;
|
|
1108
|
-
return `${items}${separator}${entry}${comma}${whitespace}]`;
|
|
1109
|
-
}).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
|
|
1110
|
-
};
|
|
1111
|
-
const testcontainers_stageFile = (filePath, content)=>{
|
|
1112
|
-
const file = new File(filePath);
|
|
1113
|
-
if (!file.exists || file.data !== content) file.data = content;
|
|
1114
558
|
};
|
|
1115
|
-
const
|
|
1116
|
-
const
|
|
559
|
+
const addOpenapi = async ()=>{
|
|
560
|
+
const { rootFolder } = ConfigFile.Instance.data;
|
|
1117
561
|
const root = new ProjectRoot().path;
|
|
1118
562
|
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1119
563
|
const manifest = JSON.parse(manifestFile.data);
|
|
@@ -1121,91 +565,172 @@ const addTestcontainers = async ()=>{
|
|
|
1121
565
|
...manifest.dependencies,
|
|
1122
566
|
...manifest.devDependencies
|
|
1123
567
|
};
|
|
1124
|
-
const
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
const
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
568
|
+
const routePrefix = await input({
|
|
569
|
+
message: 'Route prefix the REST handlers are served under:',
|
|
570
|
+
default: '/api'
|
|
571
|
+
});
|
|
572
|
+
const outputPath = await input({
|
|
573
|
+
message: 'OpenAPI document path:',
|
|
574
|
+
default: defaultOpenapiPath(Boolean(dependencies.next)),
|
|
575
|
+
validate: (value)=>splitPath(value).length ? true : 'Path is required'
|
|
576
|
+
});
|
|
577
|
+
const withExtractor = await prompts_confirm({
|
|
578
|
+
message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
|
|
579
|
+
default: true
|
|
580
|
+
});
|
|
581
|
+
const withSwaggerPage = ConfigFile.Instance.data.useReact && await prompts_confirm({
|
|
582
|
+
message: 'Add a Swagger UI page?',
|
|
583
|
+
default: true
|
|
584
|
+
});
|
|
585
|
+
const selected = await addPackageScripts(manifestFile, openapiScripts);
|
|
586
|
+
if (withExtractor) {
|
|
587
|
+
const extractorFile = new File(node_path.join(root, openapiExtractorPath));
|
|
588
|
+
const extractor = openapiExtractor(rootFolder);
|
|
589
|
+
if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
|
|
1141
590
|
}
|
|
1142
|
-
const
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
591
|
+
const generatorFile = new File(node_path.join(root, openapiScriptPath));
|
|
592
|
+
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
|
|
593
|
+
if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
|
|
594
|
+
if (withSwaggerPage) {
|
|
595
|
+
const pageFile = new File(node_path.join(root, swaggerPagePath(rootFolder)));
|
|
596
|
+
const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
|
|
597
|
+
if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
|
|
598
|
+
}
|
|
599
|
+
const resolveJsonModule = withSwaggerPage ? compilerOption(node_path.join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
|
|
600
|
+
const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
|
|
601
|
+
const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
|
|
1147
602
|
return [
|
|
1148
|
-
...
|
|
1149
|
-
|
|
1150
|
-
] : [],
|
|
1151
|
-
`Integration specs run against postgres:15 and get its address in DATABASE_URL. Change the image, credentials and connection string in ${integrationFolder}/global-setup.ts, and the variable name in ${integrationFolder}/setup-env.ts.`,
|
|
1152
|
-
...migrationCommand ? [] : [
|
|
1153
|
-
`Apply your migrations in ${integrationFolder}/global-setup.ts.`
|
|
603
|
+
...dependencies['@domain-first/handlers-rest'] ? [] : [
|
|
604
|
+
'npm install @domain-first/handlers-rest'
|
|
1154
605
|
],
|
|
1155
|
-
...
|
|
1156
|
-
|
|
606
|
+
...dependencies.tsx ? [] : [
|
|
607
|
+
'npm install --save-dev tsx'
|
|
608
|
+
],
|
|
609
|
+
...missingExtractorPackages.length ? [
|
|
610
|
+
`npm install --save-dev ${missingExtractorPackages.join(' ')}`
|
|
611
|
+
] : [],
|
|
612
|
+
...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
|
|
613
|
+
'npm install swagger-ui-react'
|
|
614
|
+
] : [],
|
|
615
|
+
...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
|
|
616
|
+
'npm install --save-dev @types/swagger-ui-react'
|
|
617
|
+
] : [],
|
|
618
|
+
...true === resolveJsonModule || null === resolveJsonModule ? [] : [
|
|
619
|
+
'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
|
|
1157
620
|
],
|
|
1158
|
-
'Docker must be running for integration specs.',
|
|
1159
621
|
...describeScripts(selected, {
|
|
1160
|
-
|
|
1161
|
-
})
|
|
622
|
+
openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
|
|
623
|
+
}),
|
|
624
|
+
...withSwaggerPage ? [
|
|
625
|
+
`SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
|
|
626
|
+
] : [],
|
|
627
|
+
...hasRestHandlers ? [] : [
|
|
628
|
+
`restHandlers appear in ${node_path.posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
|
|
629
|
+
]
|
|
1162
630
|
];
|
|
1163
631
|
};
|
|
1164
|
-
const
|
|
1165
|
-
|
|
1166
|
-
|
|
632
|
+
const addGitignoreEntry = (root, entry)=>{
|
|
633
|
+
const gitignore = new File(node_path.join(root, '.gitignore'));
|
|
634
|
+
const ignored = gitignore.exists ? gitignore.data : '';
|
|
635
|
+
if (ignored.split(/\r?\n/).includes(entry)) return;
|
|
636
|
+
const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
|
|
637
|
+
gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${entry}${newline}`);
|
|
1167
638
|
};
|
|
1168
|
-
const
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
639
|
+
const dataLayerFolder = (rootFolder, target)=>node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'hooks' === target ? 'presentation/react/data-layer' : 'presentation/data-layer');
|
|
640
|
+
const orvalScripts = (rootFolder, targets)=>({
|
|
641
|
+
'client:orval': targets.map((target)=>`orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder, target)}/orval.config.ts`)}`).join(' && ')
|
|
642
|
+
});
|
|
643
|
+
const orvalConfig = (rootFolder, openapiPath, withNext, target = 'hooks', mutatorPath = './api-client/mutator.ts')=>{
|
|
644
|
+
const inputPath = node_path.posix.relative(dataLayerFolder(rootFolder, target), openapiPath);
|
|
645
|
+
const baseUrl = withNext ? `
|
|
646
|
+
baseUrl: {
|
|
647
|
+
runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
|
|
648
|
+
},` : '';
|
|
649
|
+
const client = 'hooks' === target ? `
|
|
650
|
+
client: 'react-query',
|
|
651
|
+
httpClient: 'fetch',` : `
|
|
652
|
+
client: 'fetch',`;
|
|
653
|
+
const query = 'hooks' === target ? `,
|
|
654
|
+
query: {
|
|
655
|
+
version: 5
|
|
656
|
+
}` : '';
|
|
657
|
+
return `import { defineConfig } from 'orval';
|
|
1178
658
|
|
|
1179
659
|
export default defineConfig({
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
${
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
reporter: [['text', { skipFull: true }], 'html']
|
|
1198
|
-
}${server}
|
|
660
|
+
api: {
|
|
661
|
+
input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
|
|
662
|
+
output: {
|
|
663
|
+
mode: 'tags-split',
|
|
664
|
+
target: './orval',
|
|
665
|
+
schemas: './orval/model',${client}${baseUrl}
|
|
666
|
+
clean: true,
|
|
667
|
+
override: {
|
|
668
|
+
mutator: {
|
|
669
|
+
path: '${mutatorPath}',
|
|
670
|
+
name: 'customInstance'
|
|
671
|
+
},
|
|
672
|
+
fetch: {
|
|
673
|
+
includeHttpResponseReturnType: false
|
|
674
|
+
}${query}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
1199
677
|
}
|
|
1200
678
|
});
|
|
1201
679
|
`;
|
|
1202
680
|
};
|
|
1203
|
-
const
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
681
|
+
const orvalMutator = `/** Error of the generated requests, with the parsed response body. */
|
|
682
|
+
export class ApiError<Body = unknown> extends Error {
|
|
683
|
+
constructor(
|
|
684
|
+
public readonly status: number,
|
|
685
|
+
public readonly body: Body
|
|
686
|
+
) {
|
|
687
|
+
super(\`API error \${status}\`);
|
|
688
|
+
this.name = 'ApiError';
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/** Error type of the generated requests, typed per endpoint by Orval. */
|
|
693
|
+
export type ErrorType<Body> = ApiError<Body>;
|
|
694
|
+
|
|
695
|
+
/** Every generated request goes through here: add auth headers, token refresh, logging. */
|
|
696
|
+
export const customInstance = async <T>(
|
|
697
|
+
url: string,
|
|
698
|
+
init?: RequestInit
|
|
699
|
+
): Promise<T> => {
|
|
700
|
+
const response = await fetch(url, init);
|
|
701
|
+
const text = await response.text();
|
|
702
|
+
const body = text ? JSON.parse(text) : undefined;
|
|
703
|
+
|
|
704
|
+
if (!response.ok) {
|
|
705
|
+
throw new ApiError(response.status, body);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
return body as T;
|
|
709
|
+
};
|
|
710
|
+
`;
|
|
711
|
+
const queryProvider = `'use client';
|
|
712
|
+
|
|
713
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
714
|
+
import { type FC, type ReactNode, useState } from 'react';
|
|
715
|
+
|
|
716
|
+
export const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {
|
|
717
|
+
// One client per browser session; a module-level client would be shared between requests on the server
|
|
718
|
+
const [queryClient] = useState(() => new QueryClient());
|
|
719
|
+
|
|
720
|
+
return (
|
|
721
|
+
<QueryClientProvider client={queryClient}>
|
|
722
|
+
{children}
|
|
723
|
+
</QueryClientProvider>
|
|
724
|
+
);
|
|
725
|
+
};
|
|
726
|
+
`;
|
|
727
|
+
const openapiOutputPath = (root)=>{
|
|
728
|
+
const generator = new File(node_path.join(root, openapiScriptPath));
|
|
729
|
+
if (!generator.exists) return;
|
|
730
|
+
return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
|
|
731
|
+
};
|
|
732
|
+
const addOrval = async ()=>{
|
|
733
|
+
const { rootFolder, useReact } = ConfigFile.Instance.data;
|
|
1209
734
|
const root = new ProjectRoot().path;
|
|
1210
735
|
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1211
736
|
const manifest = JSON.parse(manifestFile.data);
|
|
@@ -1213,536 +738,1098 @@ const addVitest = async ()=>{
|
|
|
1213
738
|
...manifest.dependencies,
|
|
1214
739
|
...manifest.devDependencies
|
|
1215
740
|
};
|
|
1216
|
-
const
|
|
1217
|
-
const
|
|
1218
|
-
const
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
testingLibrary: 'vitest'
|
|
741
|
+
const withNext = Boolean(dependencies.next);
|
|
742
|
+
const generatedOpenapiPath = openapiOutputPath(root);
|
|
743
|
+
const openapiPath = await input({
|
|
744
|
+
message: 'OpenAPI document path:',
|
|
745
|
+
default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
|
|
746
|
+
validate: (value)=>value.trim() ? true : 'Path is required'
|
|
1223
747
|
});
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
748
|
+
const targets = useReact ? await prompts_checkbox({
|
|
749
|
+
message: 'Generate:',
|
|
750
|
+
choices: [
|
|
751
|
+
{
|
|
752
|
+
name: 'React Query hooks',
|
|
753
|
+
value: 'hooks',
|
|
754
|
+
checked: true
|
|
755
|
+
},
|
|
756
|
+
{
|
|
757
|
+
name: 'Typed API client',
|
|
758
|
+
value: 'client'
|
|
759
|
+
}
|
|
760
|
+
],
|
|
761
|
+
required: true
|
|
762
|
+
}) : [
|
|
763
|
+
'client'
|
|
1237
764
|
];
|
|
1238
|
-
|
|
1239
|
-
const
|
|
1240
|
-
const
|
|
1241
|
-
const
|
|
1242
|
-
const
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
},
|
|
1267
|
-
{
|
|
1268
|
-
name: 'Integration tests (Testcontainers, PostgreSQL)',
|
|
1269
|
-
group: 'backend',
|
|
1270
|
-
run: addTestcontainers,
|
|
1271
|
-
applied: ()=>created('specs/integration/vitest.config.ts')
|
|
1272
|
-
},
|
|
1273
|
-
{
|
|
1274
|
-
name: 'OpenAPI',
|
|
1275
|
-
group: 'backend',
|
|
1276
|
-
run: addOpenapi,
|
|
1277
|
-
available: ()=>withHandlersRest(),
|
|
1278
|
-
applied: ()=>created(openapiScriptPath)
|
|
1279
|
-
},
|
|
1280
|
-
{
|
|
1281
|
-
name: 'Orval (API client)',
|
|
1282
|
-
group: 'frontend',
|
|
1283
|
-
run: addOrval,
|
|
1284
|
-
available: ()=>withHandlersRest(),
|
|
1285
|
-
applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
|
|
1286
|
-
},
|
|
1287
|
-
{
|
|
1288
|
-
name: 'Missing domain-first packages',
|
|
1289
|
-
group: 'backend',
|
|
1290
|
-
run: missingDomainFirstPackages,
|
|
1291
|
-
applied: ()=>!missingDomainFirstPackages().length
|
|
765
|
+
const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder, targets));
|
|
766
|
+
const document = node_path.posix.normalize(openapiPath.trim().replaceAll('\\', '/'));
|
|
767
|
+
const withClient = targets.includes('client');
|
|
768
|
+
for (const target of targets){
|
|
769
|
+
const dataLayer = dataLayerFolder(rootFolder, target);
|
|
770
|
+
const sharedMutator = 'hooks' === target && withClient;
|
|
771
|
+
const mutatorPath = sharedMutator ? `${node_path.posix.relative(dataLayer, dataLayerFolder(rootFolder, 'client'))}/api-client/mutator.ts` : void 0;
|
|
772
|
+
const configFile = new File(node_path.join(root, dataLayer, 'orval.config.ts'));
|
|
773
|
+
const content = orvalConfig(rootFolder, document, withNext, target, mutatorPath);
|
|
774
|
+
if (!configFile.exists || configFile.data !== content) configFile.data = content;
|
|
775
|
+
for (const [name, fileContent] of [
|
|
776
|
+
...sharedMutator ? [] : [
|
|
777
|
+
[
|
|
778
|
+
'api-client/mutator.ts',
|
|
779
|
+
orvalMutator
|
|
780
|
+
]
|
|
781
|
+
],
|
|
782
|
+
...'hooks' === target ? [
|
|
783
|
+
[
|
|
784
|
+
'query-provider.tsx',
|
|
785
|
+
queryProvider
|
|
786
|
+
]
|
|
787
|
+
] : []
|
|
788
|
+
]){
|
|
789
|
+
const file = new File(node_path.join(root, dataLayer, name));
|
|
790
|
+
if (!file.exists) file.data = fileContent;
|
|
791
|
+
}
|
|
792
|
+
addGitignoreEntry(root, `/${dataLayer}/orval/`);
|
|
1292
793
|
}
|
|
1293
|
-
|
|
1294
|
-
const
|
|
1295
|
-
const
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
...
|
|
794
|
+
const generated = targets.map((target)=>'hooks' === target ? `React Query hooks in ${dataLayerFolder(rootFolder, 'hooks')}/orval` : `a typed API client in ${dataLayerFolder(rootFolder, 'client')}/orval`);
|
|
795
|
+
const missing = (names)=>names.filter((name)=>!dependencies[name]);
|
|
796
|
+
const runtime = missing(targets.includes('hooks') ? [
|
|
797
|
+
'@tanstack/react-query'
|
|
798
|
+
] : []);
|
|
799
|
+
const development = missing([
|
|
800
|
+
'orval'
|
|
801
|
+
]);
|
|
802
|
+
return [
|
|
803
|
+
...runtime.length ? [
|
|
804
|
+
`npm install ${runtime.join(' ')}`
|
|
805
|
+
] : [],
|
|
806
|
+
...development.length ? [
|
|
807
|
+
`npm install --save-dev ${development.join(' ')}`
|
|
808
|
+
] : [],
|
|
809
|
+
...describeScripts(selected, {
|
|
810
|
+
'client:orval': `generate ${generated.join(' and ')} from ${openapiPath.trim()}`
|
|
811
|
+
}),
|
|
812
|
+
...targets.includes('hooks') ? [
|
|
813
|
+
`Wrap your app in QueryProvider from ${dataLayerFolder(rootFolder, 'hooks')}/query-provider.tsx`
|
|
814
|
+
] : [],
|
|
815
|
+
...generatedOpenapiPath ? [] : [
|
|
816
|
+
'npx df-integration → OpenAPI generates the OpenAPI document the client is built from'
|
|
817
|
+
]
|
|
1315
818
|
];
|
|
1316
|
-
const selected = await prompts_checkbox({
|
|
1317
|
-
message: 'Integrations:',
|
|
1318
|
-
choices,
|
|
1319
|
-
pageSize: choices.length
|
|
1320
|
-
});
|
|
1321
|
-
const nextSteps = [];
|
|
1322
|
-
for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
|
|
1323
|
-
if (await savePendingChanges()) printNextSteps(nextSteps);
|
|
1324
819
|
};
|
|
1325
|
-
const
|
|
1326
|
-
|
|
1327
|
-
const wireName = 'wireInMemoryDbInfrastructureService';
|
|
1328
|
-
const parameterName = 'inMemoryDbInfrastructureService';
|
|
1329
|
-
const inMemoryDbService = `type Entry = {
|
|
1330
|
-
id: unknown;
|
|
1331
|
-
item: any;
|
|
820
|
+
const playwrightScripts = {
|
|
821
|
+
'test:e2e': 'playwright test'
|
|
1332
822
|
};
|
|
823
|
+
const playwrightConfig = `import { defineConfig, devices } from '@playwright/test';
|
|
1333
824
|
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
825
|
+
export default defineConfig({
|
|
826
|
+
testDir: './specs/e2e',
|
|
827
|
+
fullyParallel: true,
|
|
828
|
+
forbidOnly: !!process.env.CI,
|
|
829
|
+
retries: process.env.CI ? 2 : 0,
|
|
830
|
+
workers: process.env.CI ? 1 : undefined,
|
|
831
|
+
reporter: 'html',
|
|
832
|
+
use: {
|
|
833
|
+
baseURL: 'http://localhost:3000',
|
|
834
|
+
trace: 'on-first-retry',
|
|
835
|
+
screenshot: 'only-on-failure',
|
|
836
|
+
video: 'retain-on-failure'
|
|
837
|
+
},
|
|
1337
838
|
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
}
|
|
839
|
+
projects: [
|
|
840
|
+
{
|
|
841
|
+
name: 'chromium',
|
|
842
|
+
use: { ...devices['Desktop Chrome'] }
|
|
843
|
+
},
|
|
844
|
+
{
|
|
845
|
+
name: 'firefox',
|
|
846
|
+
use: { ...devices['Desktop Firefox'] }
|
|
847
|
+
},
|
|
848
|
+
{
|
|
849
|
+
name: 'webkit',
|
|
850
|
+
use: { ...devices['Desktop Safari'] }
|
|
851
|
+
},
|
|
852
|
+
{
|
|
853
|
+
name: 'Mobile Chrome',
|
|
854
|
+
use: { ...devices['Pixel 5'] }
|
|
855
|
+
},
|
|
856
|
+
{
|
|
857
|
+
name: 'Mobile Safari',
|
|
858
|
+
use: { ...devices['iPhone 12'] }
|
|
859
|
+
}
|
|
860
|
+
],
|
|
1347
861
|
|
|
1348
|
-
|
|
862
|
+
webServer: {
|
|
863
|
+
// Playwright only stops the dev server on a clean shutdown. If its process dies any other
|
|
864
|
+
// way (SIGHUP, SIGKILL), the dev server lives on in its own process group, so it is killed
|
|
865
|
+
// as soon as Playwright is gone.
|
|
866
|
+
command:
|
|
867
|
+
process.platform === 'win32'
|
|
868
|
+
? 'npm run dev'
|
|
869
|
+
: \`npm run dev & while kill -0 \${process.pid} 2>/dev/null && kill -0 $! 2>/dev/null; do sleep 1; done; kill 0\`,
|
|
870
|
+
url: 'http://localhost:3000',
|
|
871
|
+
timeout: 120000,
|
|
872
|
+
reuseExistingServer: !process.env.CI
|
|
873
|
+
}
|
|
874
|
+
});
|
|
875
|
+
`;
|
|
876
|
+
const exampleSpec = `import { expect, test } from '@playwright/test';
|
|
1349
877
|
|
|
1350
|
-
|
|
878
|
+
test.describe('home page', () => {
|
|
879
|
+
test('opens the home page', async ({ page, baseURL }) => {
|
|
880
|
+
await page.goto('/');
|
|
881
|
+
await expect(page).toHaveURL(\`\${baseURL}/\`);
|
|
882
|
+
});
|
|
883
|
+
});
|
|
884
|
+
`;
|
|
885
|
+
const exampleReadme = `# Home page e2e cases
|
|
1351
886
|
|
|
1352
|
-
|
|
1353
|
-
if (typeof a !== 'object' || a === null) {
|
|
1354
|
-
return Object.is(a, b);
|
|
1355
|
-
}
|
|
887
|
+
## User Stories
|
|
1356
888
|
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
889
|
+
1. Guest opens \`/\` and stays on the home page.
|
|
890
|
+
`;
|
|
891
|
+
const gitignoreEntries = [
|
|
892
|
+
'/test-results/',
|
|
893
|
+
'/playwright-report/',
|
|
894
|
+
'/blob-report/',
|
|
895
|
+
'/playwright/.cache/',
|
|
896
|
+
'/playwright/.auth/'
|
|
897
|
+
];
|
|
898
|
+
const addPlaywright = async ()=>{
|
|
899
|
+
const root = new ProjectRoot().path;
|
|
900
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
901
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
902
|
+
const dependencies = {
|
|
903
|
+
...manifest.dependencies,
|
|
904
|
+
...manifest.devDependencies
|
|
905
|
+
};
|
|
906
|
+
const selected = await addPackageScripts(manifestFile, playwrightScripts);
|
|
907
|
+
const configFile = new File(node_path.join(root, 'playwright.config.ts'));
|
|
908
|
+
if (!configFile.exists || configFile.data !== playwrightConfig) configFile.data = playwrightConfig;
|
|
909
|
+
const exampleFolder = node_path.join(root, 'specs/e2e/home');
|
|
910
|
+
for (const [name, content] of [
|
|
911
|
+
[
|
|
912
|
+
'home.e2e.spec.ts',
|
|
913
|
+
exampleSpec
|
|
914
|
+
],
|
|
915
|
+
[
|
|
916
|
+
'README.MD',
|
|
917
|
+
exampleReadme
|
|
918
|
+
]
|
|
919
|
+
]){
|
|
920
|
+
const file = new File(node_path.join(exampleFolder, name));
|
|
921
|
+
if (!file.exists) file.data = content;
|
|
1362
922
|
}
|
|
1363
|
-
|
|
1364
|
-
return
|
|
923
|
+
for (const entry of gitignoreEntries)addGitignoreEntry(root, entry);
|
|
924
|
+
return [
|
|
925
|
+
...dependencies['@playwright/test'] ? [] : [
|
|
926
|
+
'npm install --save-dev @playwright/test'
|
|
927
|
+
],
|
|
928
|
+
'npx playwright install --with-deps',
|
|
929
|
+
...describeScripts(selected, {
|
|
930
|
+
'test:e2e': 'start the dev server and run end-to-end specs from specs/e2e'
|
|
931
|
+
})
|
|
932
|
+
];
|
|
1365
933
|
};
|
|
934
|
+
const runtimePackages = [
|
|
935
|
+
'@prisma/orm-postgres',
|
|
936
|
+
'temporal-polyfill',
|
|
937
|
+
'dotenv'
|
|
938
|
+
];
|
|
939
|
+
const developmentPackages = [
|
|
940
|
+
'prisma',
|
|
941
|
+
'@prisma/cli-engine'
|
|
942
|
+
];
|
|
943
|
+
const prismaScripts = (rootFolder)=>{
|
|
944
|
+
const config = JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared-kernel/infrastructure/prisma/prisma.config.ts'));
|
|
945
|
+
const emit = `prisma contract emit --config ${config}`;
|
|
946
|
+
return {
|
|
947
|
+
'prisma:emit': emit,
|
|
948
|
+
'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
|
|
949
|
+
'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
|
|
950
|
+
};
|
|
951
|
+
};
|
|
952
|
+
const prismaConfig = `import 'dotenv/config';
|
|
953
|
+
import { definePrismaConfig } from '@prisma/cli-engine';
|
|
954
|
+
import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
|
|
1366
955
|
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
idsAreEqual?: IdsAreEqual<T['id']>
|
|
1374
|
-
): Section<T, T['id']>;
|
|
1375
|
-
protected section<T, TId>(
|
|
1376
|
-
key: string,
|
|
1377
|
-
idsAreEqual?: IdsAreEqual<TId>
|
|
1378
|
-
): Section<T, TId>;
|
|
1379
|
-
protected section<T, TId>(
|
|
1380
|
-
key: string,
|
|
1381
|
-
idsAreEqual: IdsAreEqual<TId> = defaultIdsAreEqual
|
|
1382
|
-
): Section<T, TId> {
|
|
1383
|
-
if (!globalThis.___SHARED_IN_MEMORY_DB___) {
|
|
1384
|
-
globalThis.___SHARED_IN_MEMORY_DB___ = {};
|
|
1385
|
-
}
|
|
1386
|
-
|
|
1387
|
-
if (!globalThis.___SHARED_IN_MEMORY_DB___[key]) {
|
|
1388
|
-
globalThis.___SHARED_IN_MEMORY_DB___[key] = [];
|
|
956
|
+
export default definePrismaConfig({
|
|
957
|
+
orm: ormConfig({
|
|
958
|
+
contract: './contract.prisma',
|
|
959
|
+
migrations: { dir: './migrations' },
|
|
960
|
+
db: {
|
|
961
|
+
connection: process.env.DATABASE_URL
|
|
1389
962
|
}
|
|
963
|
+
})
|
|
964
|
+
});
|
|
965
|
+
`;
|
|
966
|
+
const prismaService = `import 'temporal-polyfill/global';
|
|
967
|
+
import postgres from '@prisma/orm-postgres/runtime';
|
|
968
|
+
import type {} from 'temporal-polyfill/types/global';
|
|
969
|
+
import type { Contract } from '../prisma/contract.d';
|
|
970
|
+
import contractJson from '../prisma/contract.json' with { type: 'json' };
|
|
1390
971
|
|
|
1391
|
-
|
|
1392
|
-
globalThis.___SHARED_IN_MEMORY_DB___![key].map(
|
|
1393
|
-
(entry) => entry.item
|
|
1394
|
-
);
|
|
972
|
+
type PrismaClient = ReturnType<typeof postgres<Contract>>;
|
|
1395
973
|
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
const entries = globalThis.___SHARED_IN_MEMORY_DB___![key];
|
|
1411
|
-
const existing = entries.find((entry) =>
|
|
1412
|
-
idsAreEqual(entry.id as TId, id)
|
|
1413
|
-
);
|
|
1414
|
-
if (existing) {
|
|
1415
|
-
existing.item = item;
|
|
1416
|
-
return;
|
|
1417
|
-
}
|
|
1418
|
-
entries.push({ id, item });
|
|
1419
|
-
},
|
|
1420
|
-
deleteById: (id: TId) => {
|
|
1421
|
-
globalThis.___SHARED_IN_MEMORY_DB___![key] =
|
|
1422
|
-
globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
|
|
1423
|
-
(entry) => !idsAreEqual(entry.id as TId, id)
|
|
1424
|
-
);
|
|
1425
|
-
},
|
|
1426
|
-
delete: (predicate: (x: T) => boolean) => {
|
|
1427
|
-
globalThis.___SHARED_IN_MEMORY_DB___![key] =
|
|
1428
|
-
globalThis.___SHARED_IN_MEMORY_DB___![key].filter(
|
|
1429
|
-
(entry) => !predicate(entry.item)
|
|
1430
|
-
);
|
|
1431
|
-
}
|
|
1432
|
-
};
|
|
1433
|
-
}
|
|
974
|
+
const globalForPrisma = globalThis as typeof globalThis & {
|
|
975
|
+
prismaClient?: PrismaClient;
|
|
976
|
+
};
|
|
977
|
+
|
|
978
|
+
// Reuse the client across development hot reloads.
|
|
979
|
+
const prismaClient = globalForPrisma.prismaClient ??
|
|
980
|
+
postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
|
|
981
|
+
|
|
982
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
983
|
+
globalForPrisma.prismaClient = prismaClient;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
export class PrismaInfrastructureService {
|
|
987
|
+
readonly orm = prismaClient.orm.public;
|
|
1434
988
|
}
|
|
1435
989
|
`;
|
|
1436
|
-
const
|
|
1437
|
-
import {
|
|
990
|
+
const prismaWiring = `import { wireClass } from '@domain-first/wire';
|
|
991
|
+
import { PrismaInfrastructureService } from '../../infrastructure/services/prisma-infrastructure-service';
|
|
1438
992
|
|
|
1439
|
-
export const
|
|
1440
|
-
|
|
993
|
+
export const wirePrismaInfrastructureService = wireClass(
|
|
994
|
+
PrismaInfrastructureService,
|
|
1441
995
|
[]
|
|
1442
996
|
);
|
|
1443
997
|
`;
|
|
1444
|
-
const
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
998
|
+
const stageFile = (filePath, content)=>{
|
|
999
|
+
const file = new File(filePath);
|
|
1000
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
1001
|
+
};
|
|
1002
|
+
const addPrisma = async ()=>{
|
|
1003
|
+
const config = ConfigFile.Instance.data;
|
|
1004
|
+
const root = new ProjectRoot().path;
|
|
1005
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1006
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1007
|
+
const dependencies = {
|
|
1008
|
+
...manifest.dependencies,
|
|
1009
|
+
...manifest.devDependencies
|
|
1010
|
+
};
|
|
1011
|
+
const shared = node_path.resolve(root, config.rootFolder, 'shared-kernel');
|
|
1012
|
+
const prismaFolder = node_path.join(shared, 'infrastructure/prisma');
|
|
1013
|
+
if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
|
|
1014
|
+
node_path.join(root, 'prisma/schema.prisma'),
|
|
1015
|
+
node_path.join(prismaFolder, 'schema.prisma')
|
|
1016
|
+
].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.');
|
|
1017
|
+
const withService = await prompts_confirm({
|
|
1018
|
+
message: 'Create the Prisma infrastructure service in the Shared Kernel?',
|
|
1019
|
+
default: true
|
|
1020
|
+
});
|
|
1021
|
+
const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await prompts_confirm({
|
|
1022
|
+
message: 'Use prisma as the default persistence implementation?',
|
|
1023
|
+
default: false
|
|
1024
|
+
});
|
|
1025
|
+
const selected = await addPackageScripts(manifestFile, prismaScripts(config.rootFolder));
|
|
1026
|
+
stageFile(node_path.join(prismaFolder, 'prisma.config.ts'), prismaConfig);
|
|
1027
|
+
const contract = new File(node_path.join(prismaFolder, 'contract.prisma'));
|
|
1028
|
+
if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
|
|
1029
|
+
if (withService) {
|
|
1030
|
+
stageFile(node_path.join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
|
|
1031
|
+
if (config.domainFirstPackages.includes('@domain-first/wire')) stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
|
|
1032
|
+
}
|
|
1033
|
+
if (useByDefault) ConfigFile.write({
|
|
1034
|
+
...config,
|
|
1035
|
+
defaultPersistenceLayerImplementation: 'prisma'
|
|
1036
|
+
});
|
|
1037
|
+
const install = (packages, dev)=>{
|
|
1038
|
+
const missing = packages.filter((name)=>!dependencies[name]);
|
|
1039
|
+
return missing.length ? [
|
|
1040
|
+
`npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
|
|
1041
|
+
] : [];
|
|
1042
|
+
};
|
|
1043
|
+
const relativeFolder = node_path.relative(root, prismaFolder).split(node_path.sep).join('/');
|
|
1044
|
+
return [
|
|
1045
|
+
...install(runtimePackages, false),
|
|
1046
|
+
...install(developmentPackages, true),
|
|
1047
|
+
`Add !${relativeFolder} in your linter, to ignore prisma files.`,
|
|
1048
|
+
...describeScripts(selected, {
|
|
1049
|
+
'prisma:emit': 'emit contract.json and contract.d.ts from contract.prisma',
|
|
1050
|
+
'prisma:migration:plan': 'emit the contract and plan a migration',
|
|
1051
|
+
'prisma:migration:apply': 'apply planned migrations to the database in DATABASE_URL'
|
|
1052
|
+
})
|
|
1053
|
+
];
|
|
1054
|
+
};
|
|
1055
|
+
const kindTitles = {
|
|
1056
|
+
repositories: 'Repositories',
|
|
1057
|
+
'domain-services': 'Domain services',
|
|
1058
|
+
'application-ports': 'Ports',
|
|
1059
|
+
'application-services': 'Application services',
|
|
1060
|
+
queries: 'Queries',
|
|
1061
|
+
commands: 'Commands',
|
|
1062
|
+
'use-cases': 'Use cases',
|
|
1063
|
+
'infrastructure-services': 'Infrastructure services',
|
|
1064
|
+
'presentation-services': 'Presentation services'
|
|
1065
|
+
};
|
|
1066
|
+
const groupedChoices = (items, suggested = [])=>{
|
|
1067
|
+
const suggestedChoices = suggested.length ? [
|
|
1068
|
+
new Separator('── Suggested'),
|
|
1069
|
+
...suggested.map((x)=>({
|
|
1070
|
+
name: x.label,
|
|
1071
|
+
value: x,
|
|
1072
|
+
checked: true
|
|
1073
|
+
}))
|
|
1074
|
+
] : [];
|
|
1075
|
+
const kinds = [
|
|
1076
|
+
...new Set([
|
|
1077
|
+
...Object.keys(kindTitles),
|
|
1078
|
+
...items.map((x)=>x.module.kind)
|
|
1079
|
+
])
|
|
1080
|
+
];
|
|
1081
|
+
return [
|
|
1082
|
+
...suggestedChoices,
|
|
1083
|
+
...kinds.flatMap((kind)=>{
|
|
1084
|
+
const group = items.filter((x)=>x.module.kind === kind && !suggested.includes(x));
|
|
1085
|
+
return group.length ? [
|
|
1086
|
+
new Separator(`── ${kindTitles[kind] ?? kind}`),
|
|
1087
|
+
...group.map((x)=>({
|
|
1088
|
+
name: x.label,
|
|
1089
|
+
value: x
|
|
1090
|
+
}))
|
|
1091
|
+
] : [];
|
|
1092
|
+
})
|
|
1093
|
+
];
|
|
1094
|
+
};
|
|
1095
|
+
const groupedPageSize = 20;
|
|
1096
|
+
const contextAndSharedModules = (boundedContextFolder)=>{
|
|
1097
|
+
const sharedFolder = new Folder(new ProjectRoot().path).subitem([
|
|
1463
1098
|
ConfigFile.Instance.data.rootFolder,
|
|
1464
|
-
'shared'
|
|
1465
|
-
]);
|
|
1466
|
-
const serviceFile = ()=>new File(in_memory_db_sharedFolder().path).subitem([
|
|
1467
|
-
'infrastructure',
|
|
1468
|
-
'services',
|
|
1469
|
-
'in-memory-db-infrastructure-service.ts'
|
|
1099
|
+
'shared-kernel'
|
|
1470
1100
|
]);
|
|
1471
|
-
const
|
|
1101
|
+
const isShared = sharedFolder.path === boundedContextFolder.path;
|
|
1102
|
+
return [
|
|
1103
|
+
...findWiredModules(boundedContextFolder.path).map((x)=>({
|
|
1104
|
+
module: x,
|
|
1105
|
+
label: x.typeName
|
|
1106
|
+
})),
|
|
1107
|
+
...isShared ? [] : findWiredModules(sharedFolder.path).map((x)=>({
|
|
1108
|
+
module: x,
|
|
1109
|
+
label: `${x.typeName} (shared-kernel)`
|
|
1110
|
+
}))
|
|
1111
|
+
];
|
|
1112
|
+
};
|
|
1113
|
+
const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations, customWiring)=>{
|
|
1114
|
+
const options = contextAndSharedModules(boundedContextFolder);
|
|
1115
|
+
let asked = false;
|
|
1116
|
+
for (const implementation of implementations){
|
|
1117
|
+
const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
|
|
1118
|
+
const candidates = options.filter((x)=>available.includes(x.module));
|
|
1119
|
+
if (!candidates.length) continue;
|
|
1120
|
+
asked = true;
|
|
1121
|
+
const type = wiring_implementationType(consumer, implementation);
|
|
1122
|
+
const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
|
|
1123
|
+
const dependencies = await prompts_checkbox({
|
|
1124
|
+
message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
|
|
1125
|
+
choices: groupedChoices(candidates, suggested),
|
|
1126
|
+
pageSize: groupedPageSize,
|
|
1127
|
+
loop: false
|
|
1128
|
+
});
|
|
1129
|
+
const defaultWired = dependencies.map((x)=>x.module).filter((x)=>!customWiring?.(implementation, x));
|
|
1130
|
+
if (defaultWired.length) wireDependencies(consumer, implementation, defaultWired);
|
|
1131
|
+
}
|
|
1132
|
+
return asked;
|
|
1133
|
+
};
|
|
1134
|
+
const wireNewModuleDependencies = async (boundedContextFolder, wireFile, customWiring)=>{
|
|
1135
|
+
const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
|
|
1136
|
+
if (consumer) await promptDependencies(boundedContextFolder, consumer, consumer.implementations, customWiring);
|
|
1137
|
+
};
|
|
1138
|
+
const wireDependency = async (boundedContextFolder)=>{
|
|
1139
|
+
const modules = findWiredModules(boundedContextFolder.path);
|
|
1140
|
+
if (!modules.length) return void console.log('No wired modules here yet.');
|
|
1141
|
+
const { module: consumer, implementation } = await prompts_select({
|
|
1142
|
+
message: 'Module:',
|
|
1143
|
+
choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
|
|
1144
|
+
const type = wiring_implementationType(x, implementation);
|
|
1145
|
+
return {
|
|
1146
|
+
module: x,
|
|
1147
|
+
label: type ? `${x.typeName} (${type})` : x.typeName,
|
|
1148
|
+
implementation
|
|
1149
|
+
};
|
|
1150
|
+
}))),
|
|
1151
|
+
pageSize: groupedPageSize,
|
|
1152
|
+
loop: false
|
|
1153
|
+
});
|
|
1154
|
+
if (!await promptDependencies(boundedContextFolder, consumer, [
|
|
1155
|
+
implementation
|
|
1156
|
+
])) console.log('No dependencies available for this module.');
|
|
1157
|
+
};
|
|
1158
|
+
const promptEndpointHandler = async (boundedContextFolder)=>{
|
|
1159
|
+
const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
|
|
1160
|
+
'queries',
|
|
1161
|
+
'commands',
|
|
1162
|
+
'use-cases'
|
|
1163
|
+
].includes(x.kind)).map((x)=>({
|
|
1164
|
+
module: x,
|
|
1165
|
+
label: x.typeName
|
|
1166
|
+
}));
|
|
1167
|
+
return handlers.length ? (await prompts_select({
|
|
1168
|
+
message: 'Handler:',
|
|
1169
|
+
choices: groupedChoices(handlers),
|
|
1170
|
+
pageSize: groupedPageSize,
|
|
1171
|
+
loop: false
|
|
1172
|
+
})).module : void 0;
|
|
1173
|
+
};
|
|
1174
|
+
const createPresentationService = (boundedContextFolder, name, classFile)=>{
|
|
1175
|
+
const naming = new UnknownFormatNaming(name);
|
|
1176
|
+
const className = `${naming.ClassName}PresentationService`;
|
|
1177
|
+
const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
|
|
1178
|
+
const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
1179
|
+
const wiringFolder = boundedContextFolder.subitem([
|
|
1472
1180
|
'wiring',
|
|
1473
|
-
'
|
|
1474
|
-
'wire-in-memory-db-infrastructure-service.ts'
|
|
1181
|
+
'presentation-services'
|
|
1475
1182
|
]);
|
|
1476
|
-
const
|
|
1477
|
-
|
|
1478
|
-
const servicesFolder = shared.subitem([
|
|
1479
|
-
'infrastructure',
|
|
1183
|
+
const presentationServicesFolder = boundedContextFolder.subitem([
|
|
1184
|
+
'presentation',
|
|
1480
1185
|
'services'
|
|
1481
1186
|
]);
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
}
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1187
|
+
presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, classFile?.(className) ?? `
|
|
1188
|
+
export class ${className} {
|
|
1189
|
+
|
|
1190
|
+
}
|
|
1191
|
+
`.trim());
|
|
1192
|
+
if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
|
|
1193
|
+
import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
|
|
1194
|
+
${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
|
|
1195
|
+
import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
|
|
1196
|
+
|
|
1197
|
+
let ${naming.variableName}PresentationService: ${naming.ClassName}PresentationService
|
|
1198
|
+
|
|
1199
|
+
beforeEach(() => {
|
|
1200
|
+
${naming.variableName}PresentationService = ${withWiring ? `wire${naming.ClassName}PresentationService()` : `new ${naming.ClassName}PresentationService()`}
|
|
1201
|
+
})
|
|
1202
|
+
|
|
1203
|
+
describe('${naming.withSpaces}', () => {
|
|
1204
|
+
test('can be ${withWiring ? 'wired' : 'created'}', () => {
|
|
1205
|
+
expect(${naming.variableName}PresentationService).toBeDefined()
|
|
1206
|
+
})
|
|
1207
|
+
})
|
|
1208
|
+
`.trim());
|
|
1209
|
+
if (withWiring) return wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
|
|
1210
|
+
import { wireClass } from '@domain-first/wire'
|
|
1211
|
+
import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
|
|
1212
|
+
|
|
1213
|
+
export const wire${naming.ClassName}PresentationService = wireClass(
|
|
1214
|
+
${naming.ClassName}PresentationService,
|
|
1215
|
+
[]
|
|
1216
|
+
)
|
|
1217
|
+
`.trim());
|
|
1494
1218
|
};
|
|
1495
|
-
const
|
|
1496
|
-
const
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
|
|
1502
|
-
return field;
|
|
1219
|
+
const scaffoldNewPresentationService = async (boundedContextFolder)=>{
|
|
1220
|
+
const name = await input({
|
|
1221
|
+
message: 'Name: '
|
|
1222
|
+
});
|
|
1223
|
+
const wireFile = createPresentationService(boundedContextFolder, name);
|
|
1224
|
+
if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
1503
1225
|
};
|
|
1504
|
-
const
|
|
1505
|
-
const
|
|
1506
|
-
|
|
1226
|
+
const rest_endpoint_generator_name = 'rest-endpoint-generator';
|
|
1227
|
+
const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false } = {})=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>{
|
|
1228
|
+
const adapter = withNextAdapter ? 'nextAdapter' : 'adapter';
|
|
1229
|
+
return `
|
|
1230
|
+
import {
|
|
1231
|
+
${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
|
|
1232
|
+
createEndpoint,
|
|
1233
|
+
invalidRequest
|
|
1234
|
+
} from '@domain-first/handlers-rest'
|
|
1235
|
+
${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
|
|
1236
|
+
/**
|
|
1237
|
+
* The adapter of your HTTP framework.
|
|
1238
|
+
*/
|
|
1239
|
+
const adapter = undefined as unknown as Adapter<any[], any>`}
|
|
1507
1240
|
|
|
1508
|
-
|
|
1509
|
-
|
|
1241
|
+
export class ${className} {
|
|
1242
|
+
get withoutGuards(): EndpointGenerator {
|
|
1243
|
+
return createEndpoint({
|
|
1244
|
+
errors: [invalidRequest()]
|
|
1245
|
+
})(${adapter}) as EndpointGenerator
|
|
1510
1246
|
}
|
|
1247
|
+
}
|
|
1511
1248
|
`.trim();
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
};
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
}
|
|
1521
|
-
|
|
1522
|
-
consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
|
|
1523
|
-
wireName
|
|
1524
|
-
]));
|
|
1525
|
-
};
|
|
1526
|
-
const passInMemoryDb = (specFile, implementationName)=>{
|
|
1527
|
-
specFile.update(addImport(specFile.data, `import { ${in_memory_db_className} } from '${relativeImport(specFile.path, serviceFile().path)}'`).replace(`new ${implementationName}()`, `new ${implementationName}(new ${in_memory_db_className}())`));
|
|
1528
|
-
};
|
|
1529
|
-
const kindTitles = {
|
|
1530
|
-
repositories: 'Repositories',
|
|
1531
|
-
'domain-services': 'Domain services',
|
|
1532
|
-
'application-ports': 'Ports',
|
|
1533
|
-
'application-services': 'Application services',
|
|
1534
|
-
queries: 'Queries',
|
|
1535
|
-
commands: 'Commands',
|
|
1536
|
-
'use-cases': 'Use cases',
|
|
1537
|
-
'infrastructure-services': 'Infrastructure services',
|
|
1538
|
-
'presentation-services': 'Presentation services'
|
|
1249
|
+
});
|
|
1250
|
+
const findRestEndpointGenerator = (sharedFolder)=>{
|
|
1251
|
+
const typeFile = node_path.join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
|
|
1252
|
+
if (!new File(typeFile).exists) return;
|
|
1253
|
+
return {
|
|
1254
|
+
typeName: 'RestEndpointGeneratorPresentationService',
|
|
1255
|
+
typeFile,
|
|
1256
|
+
wireName: 'wireRestEndpointGeneratorPresentationService',
|
|
1257
|
+
wireFile: node_path.join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
|
|
1258
|
+
};
|
|
1539
1259
|
};
|
|
1540
|
-
const
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1260
|
+
const nextAppFolder = (root)=>[
|
|
1261
|
+
'app',
|
|
1262
|
+
'src/app'
|
|
1263
|
+
].find((folder)=>new Folder(node_path.join(root, folder)).exists) ?? 'app';
|
|
1264
|
+
const nextRoutePath = (root)=>node_path.posix.join(nextAppFolder(root), 'api/[...path]/route.ts');
|
|
1265
|
+
const nextRoute = (restHandlersImport)=>`
|
|
1266
|
+
import { nextEndpoints } from '@domain-first/handlers-next'
|
|
1267
|
+
${restHandlersImport ? `import { restHandlers } from '${restHandlersImport}'
|
|
1268
|
+
|
|
1269
|
+
const handler = nextEndpoints(restHandlers)` : `
|
|
1270
|
+
/**
|
|
1271
|
+
* Pass the endpoints' handle here; their paths are relative to this route's folder.
|
|
1272
|
+
*/
|
|
1273
|
+
const handler = nextEndpoints([])`}
|
|
1274
|
+
|
|
1275
|
+
export const GET = handler
|
|
1276
|
+
export const POST = handler
|
|
1277
|
+
export const PUT = handler
|
|
1278
|
+
export const PATCH = handler
|
|
1279
|
+
export const DELETE = handler
|
|
1280
|
+
`.trim();
|
|
1281
|
+
const scaffoldNextRoute = (root)=>{
|
|
1282
|
+
const { rootFolder, domainFirstPackages } = ConfigFile.Instance.data;
|
|
1283
|
+
const routePath = nextRoutePath(root);
|
|
1284
|
+
const routeFile = node_path.join(root, routePath);
|
|
1285
|
+
if (new File(routeFile).exists) return [];
|
|
1286
|
+
if (!domainFirstPackages.includes('@domain-first/wire')) {
|
|
1287
|
+
new File(routeFile).data = nextRoute(void 0);
|
|
1288
|
+
return [];
|
|
1289
|
+
}
|
|
1290
|
+
const restFolder = new Folder(root).subitem([
|
|
1291
|
+
rootFolder,
|
|
1292
|
+
'presentation',
|
|
1293
|
+
'rest'
|
|
1294
|
+
]);
|
|
1295
|
+
new File(routeFile).data = nextRoute(relativeImport(routeFile, restFolder.path));
|
|
1296
|
+
return new File(node_path.join(restFolder.path, 'index.ts')).exists ? [] : [
|
|
1297
|
+
`${routePath} serves restHandlers from ${node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest/index.ts')}, which appears with the first REST endpoint — generate one with df-scaffold (Presentation → New Handlers-REST Endpoint) and the route compiles`
|
|
1554
1298
|
];
|
|
1299
|
+
};
|
|
1300
|
+
const askNextAdapter = async ()=>hasDependency('next') && await prompts_confirm({
|
|
1301
|
+
message: 'Use Next adapter for REST endpoints'
|
|
1302
|
+
});
|
|
1303
|
+
const scaffoldRestEndpointGeneratorFiles = ({ withNextAdapter })=>{
|
|
1304
|
+
const root = new ProjectRoot().path;
|
|
1305
|
+
const generatorExisted = restEndpointGeneratorApplied();
|
|
1306
|
+
const routeNotes = withoutOverwrites(()=>{
|
|
1307
|
+
scaffoldRestEndpointGenerator(new Folder(root).subitem([
|
|
1308
|
+
ConfigFile.Instance.data.rootFolder,
|
|
1309
|
+
'shared-kernel'
|
|
1310
|
+
]), {
|
|
1311
|
+
withNextAdapter
|
|
1312
|
+
});
|
|
1313
|
+
return withNextAdapter ? scaffoldNextRoute(root) : [];
|
|
1314
|
+
});
|
|
1315
|
+
if (!withNextAdapter) return [];
|
|
1555
1316
|
return [
|
|
1556
|
-
...
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
value: x
|
|
1564
|
-
}))
|
|
1565
|
-
] : [];
|
|
1566
|
-
})
|
|
1317
|
+
...missingPackages([
|
|
1318
|
+
'@domain-first/handlers-next'
|
|
1319
|
+
]),
|
|
1320
|
+
...routeNotes,
|
|
1321
|
+
...generatorExisted ? [
|
|
1322
|
+
'the existing endpoint generator was kept — pass nextAdapter from @domain-first/handlers-next to its createEndpoint calls'
|
|
1323
|
+
] : []
|
|
1567
1324
|
];
|
|
1568
1325
|
};
|
|
1569
|
-
const
|
|
1570
|
-
|
|
1571
|
-
|
|
1326
|
+
const addRestEndpointGenerator = async ()=>scaffoldRestEndpointGeneratorFiles({
|
|
1327
|
+
withNextAdapter: await askNextAdapter()
|
|
1328
|
+
});
|
|
1329
|
+
const restEndpointGeneratorApplied = ()=>Boolean(findRestEndpointGenerator(new Folder(new ProjectRoot().path).subitem([
|
|
1572
1330
|
ConfigFile.Instance.data.rootFolder,
|
|
1573
|
-
'shared'
|
|
1331
|
+
'shared-kernel'
|
|
1332
|
+
])));
|
|
1333
|
+
const storybookFiles = (relativeProjectRoot)=>({
|
|
1334
|
+
'main.ts': `import { resolve } from 'node:path';
|
|
1335
|
+
import react from '@vitejs/plugin-react';
|
|
1336
|
+
import type { StorybookConfig } from '@storybook/react-vite';
|
|
1337
|
+
|
|
1338
|
+
const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
|
|
1339
|
+
|
|
1340
|
+
const config: StorybookConfig = {
|
|
1341
|
+
stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
|
|
1342
|
+
framework: {
|
|
1343
|
+
name: '@storybook/react-vite',
|
|
1344
|
+
options: {}
|
|
1345
|
+
},
|
|
1346
|
+
core: {
|
|
1347
|
+
disableTelemetry: true
|
|
1348
|
+
},
|
|
1349
|
+
async viteFinal(viteConfig) {
|
|
1350
|
+
const { mergeConfig } = await import('vite');
|
|
1351
|
+
|
|
1352
|
+
return mergeConfig(viteConfig, {
|
|
1353
|
+
plugins: [react()],
|
|
1354
|
+
resolve: {
|
|
1355
|
+
alias: {
|
|
1356
|
+
'@': projectRoot
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
};
|
|
1362
|
+
|
|
1363
|
+
export default config;
|
|
1364
|
+
`,
|
|
1365
|
+
'preview.ts': `import type { Preview } from '@storybook/react-vite';
|
|
1366
|
+
|
|
1367
|
+
const preview: Preview = {
|
|
1368
|
+
parameters: {
|
|
1369
|
+
controls: {
|
|
1370
|
+
matchers: {
|
|
1371
|
+
color: /(background|color)$/i,
|
|
1372
|
+
date: /Date$/i
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
};
|
|
1377
|
+
|
|
1378
|
+
export default preview;
|
|
1379
|
+
`
|
|
1380
|
+
});
|
|
1381
|
+
const storybookScripts = (rootFolder)=>{
|
|
1382
|
+
const folder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
|
|
1383
|
+
const quote = (value)=>JSON.stringify(value);
|
|
1384
|
+
return {
|
|
1385
|
+
storybook: `storybook dev -p 6006 -c ${quote(`${folder}/.storybook`)}`,
|
|
1386
|
+
'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
|
|
1387
|
+
};
|
|
1388
|
+
};
|
|
1389
|
+
const addStorybook = async ()=>{
|
|
1390
|
+
const config = ConfigFile.Instance.data;
|
|
1391
|
+
if ((!config.useReact || config.storybookFramework && '@storybook/react-vite' !== config.storybookFramework) && !await prompts_confirm({
|
|
1392
|
+
message: 'Configure React scaffolding with @storybook/react-vite?',
|
|
1393
|
+
default: false
|
|
1394
|
+
})) return [];
|
|
1395
|
+
const root = new ProjectRoot().path;
|
|
1396
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1397
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1398
|
+
const selected = await addPackageScripts(manifestFile, storybookScripts(config.rootFolder));
|
|
1399
|
+
const folder = new Folder(root).subitem([
|
|
1400
|
+
config.rootFolder,
|
|
1401
|
+
'presentation',
|
|
1402
|
+
'react',
|
|
1403
|
+
'.storybook'
|
|
1574
1404
|
]);
|
|
1575
|
-
const
|
|
1405
|
+
for (const [name, content] of Object.entries(storybookFiles(node_path.relative(folder.path, root).split(node_path.sep).join('/')))){
|
|
1406
|
+
const file = new File(node_path.join(folder.path, name));
|
|
1407
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
1408
|
+
}
|
|
1409
|
+
if (!config.useReact || '@storybook/react-vite' !== config.storybookFramework) ConfigFile.write({
|
|
1410
|
+
...config,
|
|
1411
|
+
useReact: true,
|
|
1412
|
+
storybookFramework: '@storybook/react-vite'
|
|
1413
|
+
});
|
|
1414
|
+
const buildFolder = node_path.posix.join(config.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
|
|
1415
|
+
addGitignoreEntry(root, `/${buildFolder}/`);
|
|
1416
|
+
const dependencies = {
|
|
1417
|
+
...manifest.dependencies,
|
|
1418
|
+
...manifest.devDependencies
|
|
1419
|
+
};
|
|
1420
|
+
const missing = [
|
|
1421
|
+
'storybook',
|
|
1422
|
+
'@storybook/react-vite',
|
|
1423
|
+
'vite',
|
|
1424
|
+
'@vitejs/plugin-react'
|
|
1425
|
+
].filter((name)=>!dependencies[name]);
|
|
1426
|
+
const missingReact = [
|
|
1427
|
+
'react',
|
|
1428
|
+
'react-dom'
|
|
1429
|
+
].filter((name)=>!dependencies[name]);
|
|
1576
1430
|
return [
|
|
1577
|
-
...
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1431
|
+
...missing.length ? [
|
|
1432
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
1433
|
+
] : [],
|
|
1434
|
+
...missingReact.length ? [
|
|
1435
|
+
`npm install ${missingReact.join(' ')}`
|
|
1436
|
+
] : [],
|
|
1437
|
+
...describeScripts(selected, {
|
|
1438
|
+
storybook: 'start Storybook on http://localhost:6006',
|
|
1439
|
+
'build-storybook': `build static Storybook into ${buildFolder}`
|
|
1440
|
+
})
|
|
1585
1441
|
];
|
|
1586
1442
|
};
|
|
1587
|
-
const
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
for (const implementation of implementations){
|
|
1591
|
-
const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
|
|
1592
|
-
const candidates = options.filter((x)=>available.includes(x.module));
|
|
1593
|
-
if (!candidates.length) continue;
|
|
1594
|
-
asked = true;
|
|
1595
|
-
const type = wiring_implementationType(consumer, implementation);
|
|
1596
|
-
const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
|
|
1597
|
-
const dependencies = await prompts_checkbox({
|
|
1598
|
-
message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
|
|
1599
|
-
choices: groupedChoices(candidates, suggested),
|
|
1600
|
-
pageSize: groupedPageSize,
|
|
1601
|
-
loop: false
|
|
1602
|
-
});
|
|
1603
|
-
const defaultWired = dependencies.map((x)=>x.module).filter((x)=>!customWiring?.(implementation, x));
|
|
1604
|
-
if (defaultWired.length) wireDependencies(consumer, implementation, defaultWired);
|
|
1605
|
-
}
|
|
1606
|
-
return asked;
|
|
1443
|
+
const integrationFolder = 'specs/integration';
|
|
1444
|
+
const testcontainersScripts = {
|
|
1445
|
+
'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
|
|
1607
1446
|
};
|
|
1608
|
-
const
|
|
1609
|
-
const
|
|
1610
|
-
|
|
1447
|
+
const testcontainersVitestConfig = (inlineHandlersNext)=>{
|
|
1448
|
+
const server = inlineHandlersNext ? `,
|
|
1449
|
+
server: {
|
|
1450
|
+
deps: {
|
|
1451
|
+
// Imports \`next/headers\` without an extension, which only a bundler can resolve
|
|
1452
|
+
inline: ['@domain-first/handlers-next']
|
|
1453
|
+
}
|
|
1454
|
+
}` : '';
|
|
1455
|
+
return `import { fileURLToPath } from 'node:url';
|
|
1456
|
+
import { defineConfig } from 'vitest/config';
|
|
1457
|
+
|
|
1458
|
+
// Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
|
|
1459
|
+
export default defineConfig({
|
|
1460
|
+
// Paths below are relative to the project root, not this folder
|
|
1461
|
+
root: fileURLToPath(new URL('../..', import.meta.url)),
|
|
1462
|
+
resolve: {
|
|
1463
|
+
tsconfigPaths: true
|
|
1464
|
+
},
|
|
1465
|
+
test: {
|
|
1466
|
+
include: ['${integrationFolder}/**/*.spec.ts'],
|
|
1467
|
+
// Development implementations work with the real database
|
|
1468
|
+
env: { NODE_ENV: 'development' },
|
|
1469
|
+
globalSetup: ['${integrationFolder}/global-setup.ts'],
|
|
1470
|
+
setupFiles: ['${integrationFolder}/setup-env.ts'],
|
|
1471
|
+
// Pulling the image on the first run takes a while
|
|
1472
|
+
hookTimeout: 120_000${server}
|
|
1473
|
+
}
|
|
1474
|
+
});
|
|
1475
|
+
`;
|
|
1611
1476
|
};
|
|
1612
|
-
const
|
|
1613
|
-
const
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
module: x,
|
|
1621
|
-
label: type ? `${x.typeName} (${type})` : x.typeName,
|
|
1622
|
-
implementation
|
|
1623
|
-
};
|
|
1624
|
-
}))),
|
|
1625
|
-
pageSize: groupedPageSize,
|
|
1626
|
-
loop: false
|
|
1477
|
+
const testcontainersGlobalSetup = (migrationCommand)=>{
|
|
1478
|
+
const migrations = migrationCommand ? `
|
|
1479
|
+
// dotenv in the Prisma config does not override an already set variable
|
|
1480
|
+
execSync(${JSON.stringify(migrationCommand)}, {
|
|
1481
|
+
cwd: project.config.root,
|
|
1482
|
+
env: { ...process.env, DATABASE_URL: databaseUrl },
|
|
1483
|
+
// On failure the error carries the command's output
|
|
1484
|
+
stdio: 'pipe'
|
|
1627
1485
|
});
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
};
|
|
1632
|
-
|
|
1633
|
-
const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
|
|
1634
|
-
'queries',
|
|
1635
|
-
'commands',
|
|
1636
|
-
'use-cases'
|
|
1637
|
-
].includes(x.kind)).map((x)=>({
|
|
1638
|
-
module: x,
|
|
1639
|
-
label: x.typeName
|
|
1640
|
-
}));
|
|
1641
|
-
return handlers.length ? (await prompts_select({
|
|
1642
|
-
message: 'Handler:',
|
|
1643
|
-
choices: groupedChoices(handlers),
|
|
1644
|
-
pageSize: groupedPageSize,
|
|
1645
|
-
loop: false
|
|
1646
|
-
})).module : void 0;
|
|
1647
|
-
};
|
|
1648
|
-
const createPresentationService = (boundedContextFolder, name, classFile)=>{
|
|
1649
|
-
const naming = new UnknownFormatNaming(name);
|
|
1650
|
-
const className = `${naming.ClassName}PresentationService`;
|
|
1651
|
-
const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
|
|
1652
|
-
const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
1653
|
-
const wiringFolder = boundedContextFolder.subitem([
|
|
1654
|
-
'wiring',
|
|
1655
|
-
'presentation-services'
|
|
1656
|
-
]);
|
|
1657
|
-
const presentationServicesFolder = boundedContextFolder.subitem([
|
|
1658
|
-
'presentation',
|
|
1659
|
-
'services'
|
|
1660
|
-
]);
|
|
1661
|
-
presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, classFile?.(className) ?? `
|
|
1662
|
-
export class ${className} {
|
|
1486
|
+
` : `
|
|
1487
|
+
// Apply your migrations to databaseUrl here.
|
|
1488
|
+
`;
|
|
1489
|
+
return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
|
|
1490
|
+
import type { TestProject } from 'vitest/node';
|
|
1663
1491
|
|
|
1492
|
+
declare module 'vitest' {
|
|
1493
|
+
export interface ProvidedContext {
|
|
1494
|
+
databaseUrl: string;
|
|
1495
|
+
}
|
|
1664
1496
|
}
|
|
1665
|
-
`.trim());
|
|
1666
|
-
if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
|
|
1667
|
-
import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
|
|
1668
|
-
${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
|
|
1669
|
-
import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
|
|
1670
1497
|
|
|
1671
|
-
|
|
1498
|
+
const POSTGRES_IMAGE = 'postgres:15';
|
|
1499
|
+
const POSTGRES_PORT = 5432;
|
|
1500
|
+
const POSTGRES_USER = 'test';
|
|
1501
|
+
const POSTGRES_PASSWORD = 'test';
|
|
1502
|
+
const POSTGRES_DB = 'test';
|
|
1672
1503
|
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
})
|
|
1504
|
+
export default async function setup(project: TestProject) {
|
|
1505
|
+
const container = await new GenericContainer(POSTGRES_IMAGE)
|
|
1506
|
+
.withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
|
|
1507
|
+
.withExposedPorts(POSTGRES_PORT)
|
|
1508
|
+
// During init PostgreSQL listens on a unix socket only and restarts,
|
|
1509
|
+
// so checking over TCP passes once the final server is up
|
|
1510
|
+
.withHealthCheck({
|
|
1511
|
+
test: [
|
|
1512
|
+
'CMD-SHELL',
|
|
1513
|
+
\`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
|
|
1514
|
+
],
|
|
1515
|
+
interval: 250,
|
|
1516
|
+
timeout: 1000,
|
|
1517
|
+
retries: 1000
|
|
1518
|
+
})
|
|
1519
|
+
.withWaitStrategy(Wait.forHealthCheck())
|
|
1520
|
+
.withStartupTimeout(120_000)
|
|
1521
|
+
.start();
|
|
1676
1522
|
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
})
|
|
1681
|
-
})
|
|
1682
|
-
`.trim());
|
|
1683
|
-
if (withWiring) return wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
|
|
1684
|
-
import { wireClass } from '@domain-first/wire'
|
|
1685
|
-
import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
|
|
1523
|
+
const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
|
|
1524
|
+
${migrations}
|
|
1525
|
+
project.provide('databaseUrl', databaseUrl);
|
|
1686
1526
|
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1527
|
+
return async () => {
|
|
1528
|
+
await container.stop();
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
`;
|
|
1532
|
+
};
|
|
1533
|
+
const testcontainersSetupEnv = `import 'dotenv/config';
|
|
1534
|
+
import { inject } from 'vitest';
|
|
1535
|
+
|
|
1536
|
+
// Runs before each spec's imports: development implementations get the .env
|
|
1537
|
+
// config, and DATABASE_URL points to the container instead of the one from .env.
|
|
1538
|
+
if (process.env.NODE_ENV !== 'development') {
|
|
1539
|
+
throw new Error(
|
|
1540
|
+
\`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
|
|
1541
|
+
);
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
process.env.DATABASE_URL = inject('databaseUrl');
|
|
1545
|
+
`;
|
|
1546
|
+
const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
|
|
1547
|
+
|
|
1548
|
+
test('connects to the database in the container', () => {
|
|
1549
|
+
expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
|
|
1550
|
+
});
|
|
1551
|
+
`;
|
|
1552
|
+
const excludeFromUnitTests = (content)=>{
|
|
1553
|
+
const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
|
|
1554
|
+
if (!exclude.test(content)) return;
|
|
1555
|
+
const entry = `'${integrationFolder}/**'`;
|
|
1556
|
+
return content.replace(exclude, (_, items, comma, whitespace)=>{
|
|
1557
|
+
const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
|
|
1558
|
+
const separator = void 0 === indent ? ', ' : `,\n${indent}`;
|
|
1559
|
+
return `${items}${separator}${entry}${comma}${whitespace}]`;
|
|
1560
|
+
}).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
|
|
1561
|
+
};
|
|
1562
|
+
const testcontainers_stageFile = (filePath, content)=>{
|
|
1563
|
+
const file = new File(filePath);
|
|
1564
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
1565
|
+
};
|
|
1566
|
+
const addTestcontainers = async ()=>{
|
|
1567
|
+
const config = ConfigFile.Instance.data;
|
|
1568
|
+
const root = new ProjectRoot().path;
|
|
1569
|
+
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1570
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1571
|
+
const dependencies = {
|
|
1572
|
+
...manifest.dependencies,
|
|
1573
|
+
...manifest.devDependencies
|
|
1574
|
+
};
|
|
1575
|
+
const selected = await addPackageScripts(manifestFile, testcontainersScripts);
|
|
1576
|
+
const withPrisma = new File(node_path.resolve(root, config.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
|
|
1577
|
+
const migrationCommand = withPrisma ? `npx ${prismaScripts(config.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
|
|
1578
|
+
const folder = node_path.join(root, integrationFolder);
|
|
1579
|
+
testcontainers_stageFile(node_path.join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
|
|
1580
|
+
testcontainers_stageFile(node_path.join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
|
|
1581
|
+
testcontainers_stageFile(node_path.join(folder, 'setup-env.ts'), testcontainersSetupEnv);
|
|
1582
|
+
const example = new File(node_path.join(folder, 'database/database.spec.ts'));
|
|
1583
|
+
if (!example.exists) example.data = testcontainers_exampleSpec;
|
|
1584
|
+
const unitConfig = new File(node_path.join(root, 'vitest.config.ts'));
|
|
1585
|
+
let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
|
|
1586
|
+
if (!excludedFromUnitTests) {
|
|
1587
|
+
const excluded = excludeFromUnitTests(unitConfig.data);
|
|
1588
|
+
if (excluded) {
|
|
1589
|
+
unitConfig.update(excluded);
|
|
1590
|
+
excludedFromUnitTests = true;
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
const missing = [
|
|
1594
|
+
'vitest',
|
|
1595
|
+
'testcontainers',
|
|
1596
|
+
'dotenv'
|
|
1597
|
+
].filter((name)=>!dependencies[name]);
|
|
1598
|
+
return [
|
|
1599
|
+
...missing.length ? [
|
|
1600
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
1601
|
+
] : [],
|
|
1602
|
+
`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.`,
|
|
1603
|
+
...migrationCommand ? [] : [
|
|
1604
|
+
`Apply your migrations in ${integrationFolder}/global-setup.ts.`
|
|
1605
|
+
],
|
|
1606
|
+
...excludedFromUnitTests ? [] : [
|
|
1607
|
+
`Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
|
|
1608
|
+
],
|
|
1609
|
+
'Docker must be running for integration specs.',
|
|
1610
|
+
...describeScripts(selected, {
|
|
1611
|
+
'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
|
|
1612
|
+
})
|
|
1613
|
+
];
|
|
1692
1614
|
};
|
|
1693
|
-
const
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
});
|
|
1697
|
-
const wireFile = createPresentationService(boundedContextFolder, name);
|
|
1698
|
-
if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
|
|
1615
|
+
const vitestScripts = {
|
|
1616
|
+
test: 'vitest run --reporter=dot --silent=passed-only',
|
|
1617
|
+
'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
|
|
1699
1618
|
};
|
|
1700
|
-
const
|
|
1701
|
-
const
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
}
|
|
1709
|
-
|
|
1710
|
-
/**
|
|
1711
|
-
* The adapter of your HTTP framework.
|
|
1712
|
-
*/
|
|
1713
|
-
const adapter = undefined as unknown as Adapter<any[], any>`}
|
|
1619
|
+
const vitestConfig = (rootFolder, inlineHandlersNext)=>{
|
|
1620
|
+
const folder = (subpath)=>JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), subpath));
|
|
1621
|
+
const server = inlineHandlersNext ? `,
|
|
1622
|
+
server: {
|
|
1623
|
+
deps: {
|
|
1624
|
+
// Imports \`next/headers\` without an extension, which only a bundler can resolve
|
|
1625
|
+
inline: ['@domain-first/handlers-next']
|
|
1626
|
+
}
|
|
1627
|
+
}` : '';
|
|
1628
|
+
return `import { configDefaults, defineConfig } from 'vitest/config';
|
|
1714
1629
|
|
|
1715
|
-
export
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1630
|
+
export default defineConfig({
|
|
1631
|
+
resolve: {
|
|
1632
|
+
tsconfigPaths: true
|
|
1633
|
+
},
|
|
1634
|
+
test: {
|
|
1635
|
+
// Playwright runs end-to-end specs, test:integration runs integration ones
|
|
1636
|
+
exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
|
|
1637
|
+
coverage: {
|
|
1638
|
+
provider: 'v8',
|
|
1639
|
+
include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared-kernel/**/*.ts')}],
|
|
1640
|
+
exclude: [
|
|
1641
|
+
'**/*.spec.ts',
|
|
1642
|
+
${folder('shared-kernel/infrastructure/**')},
|
|
1643
|
+
${folder('bounded-contexts/*/infrastructure/**')},
|
|
1644
|
+
${folder('bounded-contexts/*/presentation/rest/**')},
|
|
1645
|
+
${folder('shared-kernel/wiring/**')},
|
|
1646
|
+
${folder('bounded-contexts/*/wiring/**')}
|
|
1647
|
+
],
|
|
1648
|
+
reporter: [['text', { skipFull: true }], 'html']
|
|
1649
|
+
}${server}
|
|
1720
1650
|
}
|
|
1721
|
-
}
|
|
1722
|
-
|
|
1723
|
-
});
|
|
1724
|
-
const findRestEndpointGenerator = (sharedFolder)=>{
|
|
1725
|
-
const typeFile = node_path.join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
|
|
1726
|
-
if (!new File(typeFile).exists) return;
|
|
1727
|
-
return {
|
|
1728
|
-
typeName: 'RestEndpointGeneratorPresentationService',
|
|
1729
|
-
typeFile,
|
|
1730
|
-
wireName: 'wireRestEndpointGeneratorPresentationService',
|
|
1731
|
-
wireFile: node_path.join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
|
|
1732
|
-
};
|
|
1651
|
+
});
|
|
1652
|
+
`;
|
|
1733
1653
|
};
|
|
1734
|
-
const
|
|
1654
|
+
const addVitest = async ()=>{
|
|
1655
|
+
const config = ConfigFile.Instance.data;
|
|
1656
|
+
if (config.testingLibrary && 'vitest' !== config.testingLibrary && !await prompts_confirm({
|
|
1657
|
+
message: `Replace testing library "${config.testingLibrary}" with vitest for generated tests?`,
|
|
1658
|
+
default: false
|
|
1659
|
+
})) return [];
|
|
1660
|
+
const root = new ProjectRoot().path;
|
|
1735
1661
|
const manifestFile = new File(node_path.join(root, 'package.json'));
|
|
1736
|
-
if (!manifestFile.exists) return false;
|
|
1737
1662
|
const manifest = JSON.parse(manifestFile.data);
|
|
1663
|
+
const dependencies = {
|
|
1664
|
+
...manifest.dependencies,
|
|
1665
|
+
...manifest.devDependencies
|
|
1666
|
+
};
|
|
1667
|
+
const selected = await addPackageScripts(manifestFile, vitestScripts);
|
|
1668
|
+
const configFile = new File(node_path.join(root, 'vitest.config.ts'));
|
|
1669
|
+
const content = vitestConfig(config.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
|
|
1670
|
+
if (!configFile.exists || configFile.data !== content) configFile.data = content;
|
|
1671
|
+
if ('vitest' !== config.testingLibrary) ConfigFile.write({
|
|
1672
|
+
...config,
|
|
1673
|
+
testingLibrary: 'vitest'
|
|
1674
|
+
});
|
|
1675
|
+
addGitignoreEntry(root, '/coverage/');
|
|
1676
|
+
const missing = [
|
|
1677
|
+
'vitest',
|
|
1678
|
+
'@vitest/coverage-v8'
|
|
1679
|
+
].filter((name)=>!dependencies[name]);
|
|
1738
1680
|
return [
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1681
|
+
...missing.length ? [
|
|
1682
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
1683
|
+
] : [],
|
|
1684
|
+
...describeScripts(selected, {
|
|
1685
|
+
test: 'run unit tests',
|
|
1686
|
+
'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
|
|
1687
|
+
})
|
|
1688
|
+
];
|
|
1743
1689
|
};
|
|
1744
|
-
const
|
|
1690
|
+
const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
|
|
1691
|
+
const mergeInstallCommands = (commands)=>{
|
|
1692
|
+
const runtime = new Set();
|
|
1693
|
+
const development = new Set();
|
|
1694
|
+
const rest = [];
|
|
1695
|
+
for (const command of commands){
|
|
1696
|
+
const match = installCommand.exec(command);
|
|
1697
|
+
if (!match) {
|
|
1698
|
+
rest.push(command);
|
|
1699
|
+
continue;
|
|
1700
|
+
}
|
|
1701
|
+
for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
|
|
1702
|
+
}
|
|
1703
|
+
const devOnly = [
|
|
1704
|
+
...development
|
|
1705
|
+
].filter((name)=>!runtime.has(name));
|
|
1706
|
+
return [
|
|
1707
|
+
...runtime.size ? [
|
|
1708
|
+
`npm install ${[
|
|
1709
|
+
...runtime
|
|
1710
|
+
].join(' ')}`
|
|
1711
|
+
] : [],
|
|
1712
|
+
...devOnly.length ? [
|
|
1713
|
+
`npm install --save-dev ${devOnly.join(' ')}`
|
|
1714
|
+
] : [],
|
|
1715
|
+
...rest
|
|
1716
|
+
];
|
|
1717
|
+
};
|
|
1718
|
+
const printNextSteps = (nextSteps)=>{
|
|
1719
|
+
const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
|
|
1720
|
+
const commands = mergeInstallCommands(nextSteps.filter(isCommand));
|
|
1721
|
+
const notes = nextSteps.filter((line)=>!isCommand(line));
|
|
1722
|
+
const sections = [];
|
|
1723
|
+
if (commands.length) sections.push([
|
|
1724
|
+
'Run this command to install the required dependencies:',
|
|
1725
|
+
styleText([
|
|
1726
|
+
'bold',
|
|
1727
|
+
'cyan'
|
|
1728
|
+
], commands.join(' && '))
|
|
1729
|
+
].join('\n'));
|
|
1730
|
+
if (notes.length) sections.push([
|
|
1731
|
+
'Additional information:',
|
|
1732
|
+
...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
|
|
1733
|
+
'bold',
|
|
1734
|
+
'cyan'
|
|
1735
|
+
], path)))
|
|
1736
|
+
].join('\n'));
|
|
1737
|
+
if (sections.length) console.log(sections.join('\n\n'));
|
|
1738
|
+
};
|
|
1739
|
+
const withHandlersRest = ()=>ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers-rest');
|
|
1740
|
+
const created = (...segments)=>new File(node_path.join(new ProjectRoot().path, ...segments)).exists;
|
|
1741
|
+
const createdInRoot = (...segments)=>created(ConfigFile.Instance.data.rootFolder, ...segments);
|
|
1742
|
+
const integrations = [
|
|
1743
|
+
{
|
|
1744
|
+
name: 'Storybook (React + Vite)',
|
|
1745
|
+
group: 'frontend',
|
|
1746
|
+
run: addStorybook,
|
|
1747
|
+
applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
|
|
1748
|
+
},
|
|
1749
|
+
{
|
|
1750
|
+
name: 'REST endpoint generator',
|
|
1751
|
+
group: 'backend',
|
|
1752
|
+
run: addRestEndpointGenerator,
|
|
1753
|
+
available: ()=>withHandlersRest(),
|
|
1754
|
+
applied: restEndpointGeneratorApplied
|
|
1755
|
+
},
|
|
1756
|
+
{
|
|
1757
|
+
name: 'In-memory DB',
|
|
1758
|
+
group: 'backend',
|
|
1759
|
+
run: addInMemoryDb,
|
|
1760
|
+
applied: inMemoryDbApplied
|
|
1761
|
+
},
|
|
1762
|
+
{
|
|
1763
|
+
name: 'Prisma 8 (PostgreSQL, RC)',
|
|
1764
|
+
group: 'backend',
|
|
1765
|
+
run: addPrisma,
|
|
1766
|
+
applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
|
|
1767
|
+
},
|
|
1768
|
+
{
|
|
1769
|
+
name: 'Vitest',
|
|
1770
|
+
group: 'backend',
|
|
1771
|
+
run: addVitest,
|
|
1772
|
+
applied: ()=>created('vitest.config.ts')
|
|
1773
|
+
},
|
|
1774
|
+
{
|
|
1775
|
+
name: 'Playwright',
|
|
1776
|
+
group: 'frontend',
|
|
1777
|
+
run: addPlaywright,
|
|
1778
|
+
applied: ()=>created('playwright.config.ts')
|
|
1779
|
+
},
|
|
1780
|
+
{
|
|
1781
|
+
name: 'Integration tests (Testcontainers, PostgreSQL)',
|
|
1782
|
+
group: 'backend',
|
|
1783
|
+
run: addTestcontainers,
|
|
1784
|
+
applied: ()=>created('specs/integration/vitest.config.ts')
|
|
1785
|
+
},
|
|
1786
|
+
{
|
|
1787
|
+
name: 'OpenAPI',
|
|
1788
|
+
group: 'backend',
|
|
1789
|
+
run: addOpenapi,
|
|
1790
|
+
available: ()=>withHandlersRest(),
|
|
1791
|
+
applied: ()=>created(openapiScriptPath)
|
|
1792
|
+
},
|
|
1793
|
+
{
|
|
1794
|
+
name: 'Orval (API client)',
|
|
1795
|
+
group: 'frontend',
|
|
1796
|
+
run: addOrval,
|
|
1797
|
+
available: ()=>withHandlersRest(),
|
|
1798
|
+
applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
|
|
1799
|
+
}
|
|
1800
|
+
];
|
|
1801
|
+
const addIntegration = async ()=>{
|
|
1802
|
+
const available = integrations.filter(({ available })=>available?.() ?? true).map((value)=>({
|
|
1803
|
+
value,
|
|
1804
|
+
applied: value.applied()
|
|
1805
|
+
}));
|
|
1806
|
+
const section = (title, applied)=>{
|
|
1807
|
+
const items = [
|
|
1808
|
+
'backend',
|
|
1809
|
+
'frontend'
|
|
1810
|
+
].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
|
|
1811
|
+
return items.length ? [
|
|
1812
|
+
new Separator(title),
|
|
1813
|
+
...items.map(({ value })=>({
|
|
1814
|
+
name: `${value.name} · ${value.group}`,
|
|
1815
|
+
value
|
|
1816
|
+
}))
|
|
1817
|
+
] : [];
|
|
1818
|
+
};
|
|
1819
|
+
const choices = [
|
|
1820
|
+
...section('New integrations', false),
|
|
1821
|
+
...section('Already applied (select to reapply)', true)
|
|
1822
|
+
];
|
|
1823
|
+
const selected = await prompts_checkbox({
|
|
1824
|
+
message: 'Integrations:',
|
|
1825
|
+
choices,
|
|
1826
|
+
pageSize: choices.length
|
|
1827
|
+
});
|
|
1745
1828
|
const nextSteps = [];
|
|
1829
|
+
for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
|
|
1830
|
+
if (await savePendingChanges()) printNextSteps(nextSteps);
|
|
1831
|
+
};
|
|
1832
|
+
const initializeUseCase = async ()=>{
|
|
1746
1833
|
const rootFolderName = await input({
|
|
1747
1834
|
message: 'Root folder (use "/" for inner folders):',
|
|
1748
1835
|
default: 'src'
|
|
@@ -1757,9 +1844,7 @@ const initializeUseCase = async ()=>{
|
|
|
1757
1844
|
'@domain-first/handlers-rest'
|
|
1758
1845
|
]
|
|
1759
1846
|
});
|
|
1760
|
-
const withNextAdapter = domainFirstPackages.includes('@domain-first/handlers-rest') &&
|
|
1761
|
-
message: 'Use Next adapter for REST endpoints'
|
|
1762
|
-
});
|
|
1847
|
+
const withNextAdapter = domainFirstPackages.includes('@domain-first/handlers-rest') && await askNextAdapter();
|
|
1763
1848
|
const defaultPersistenceLayerImplementation = await input({
|
|
1764
1849
|
message: 'Default persistence layer implementation:'
|
|
1765
1850
|
});
|
|
@@ -1798,7 +1883,7 @@ const initializeUseCase = async ()=>{
|
|
|
1798
1883
|
const rootFolder = new Folder(path);
|
|
1799
1884
|
if (domainFirstPackages.includes('@domain-first/wire')) rootFolder.subitem([
|
|
1800
1885
|
rootFolderName,
|
|
1801
|
-
'shared',
|
|
1886
|
+
'shared-kernel',
|
|
1802
1887
|
'wiring'
|
|
1803
1888
|
]).createFile('env-branched-wire.ts', `
|
|
1804
1889
|
import { branchedWire } from '@domain-first/wire'
|
|
@@ -1809,28 +1894,12 @@ export const envBranchedWire = branchedWire(() => {
|
|
|
1809
1894
|
`.trim());
|
|
1810
1895
|
if (withInMemoryDb) scaffoldInMemoryDb(rootFolder.subitem([
|
|
1811
1896
|
rootFolderName,
|
|
1812
|
-
'shared'
|
|
1897
|
+
'shared-kernel'
|
|
1813
1898
|
]));
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
'domain',
|
|
1819
|
-
'errors'
|
|
1820
|
-
]).createFile('index.ts', `
|
|
1821
|
-
import { errorNamespace } from '@domain-first/errors'
|
|
1822
|
-
|
|
1823
|
-
export const SharedErrors = errorNamespace('shared')
|
|
1824
|
-
`.trim());
|
|
1825
|
-
if (domainFirstPackages.includes('@domain-first/handlers-rest')) {
|
|
1826
|
-
scaffoldRestEndpointGenerator(rootFolder.subitem([
|
|
1827
|
-
rootFolderName,
|
|
1828
|
-
'shared'
|
|
1829
|
-
]), {
|
|
1830
|
-
withNextAdapter
|
|
1831
|
-
});
|
|
1832
|
-
if (withNextAdapter && !hasDependency(path, '@domain-first/handlers-next')) nextSteps.push('npm i @domain-first/handlers-next');
|
|
1833
|
-
}
|
|
1899
|
+
const nextSteps = missingDomainFirstPackages();
|
|
1900
|
+
if (domainFirstPackages.includes('@domain-first/handlers-rest')) nextSteps.push(...scaffoldRestEndpointGeneratorFiles({
|
|
1901
|
+
withNextAdapter
|
|
1902
|
+
}));
|
|
1834
1903
|
return nextSteps;
|
|
1835
1904
|
};
|
|
1836
1905
|
const ignoredFolders = new Set([
|
|
@@ -2039,7 +2108,7 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
|
|
|
2039
2108
|
const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
|
|
2040
2109
|
const reactFolder = presentationReactFolder.path;
|
|
2041
2110
|
const modules = findReactModules(reactFolder, kind);
|
|
2042
|
-
if (!modules.length) return void console.log(`No ${kind}s generated by df-
|
|
2111
|
+
if (!modules.length) return void console.log(`No ${kind}s generated by df-react were found.`);
|
|
2043
2112
|
const module = await prompts_select({
|
|
2044
2113
|
message: 'page' === kind ? 'Page:' : 'Widget:',
|
|
2045
2114
|
choices: modules.map((value)=>({
|
|
@@ -2195,7 +2264,7 @@ describe('${aggregateNaming.withSpaces} repository', () => {
|
|
|
2195
2264
|
'repositories'
|
|
2196
2265
|
]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
|
|
2197
2266
|
import { wireClass } from '@domain-first/wire'
|
|
2198
|
-
import { envBranchedWire } from '../../../../shared/wiring/env-branched-wire'
|
|
2267
|
+
import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
|
|
2199
2268
|
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${aggregateNaming.ClassName}Repository } from '../../infrastructure/repositories/${fileName}/${fileName}-${aggregateNaming.fileName}-repository'`).join('\n')}
|
|
2200
2269
|
|
|
2201
2270
|
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${aggregateNaming.ClassName}Repository, [])`).join('\n\n')}
|
|
@@ -2291,7 +2360,7 @@ describe('${naming.withSpaces}', () => {
|
|
|
2291
2360
|
if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
|
|
2292
2361
|
const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
|
|
2293
2362
|
import { wireClass } from '@domain-first/wire'
|
|
2294
|
-
import { envBranchedWire } from '../../../${'shared' === boundedContextFolder.name ? '' : '../'}shared/wiring/env-branched-wire'
|
|
2363
|
+
import { envBranchedWire } from '../../../${'shared-kernel' === boundedContextFolder.name ? '' : '../'}shared-kernel/wiring/env-branched-wire'
|
|
2295
2364
|
${implementationTypes.map((x)=>({
|
|
2296
2365
|
naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
|
|
2297
2366
|
implementation: x
|
|
@@ -2374,14 +2443,6 @@ const scaffoldNewBoundedContextUseCase = async ()=>{
|
|
|
2374
2443
|
'bounded-contexts',
|
|
2375
2444
|
name
|
|
2376
2445
|
]);
|
|
2377
|
-
if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/errors')) folder.subitem([
|
|
2378
|
-
'domain',
|
|
2379
|
-
'errors'
|
|
2380
|
-
]).createFile('index.ts', `
|
|
2381
|
-
import { errorNamespace } from '@domain-first/errors'
|
|
2382
|
-
|
|
2383
|
-
export const ${new UnknownFormatNaming(name).ClassName}Errors = errorNamespace('${name}')
|
|
2384
|
-
`.trim());
|
|
2385
2446
|
folder.createIfNotExisted();
|
|
2386
2447
|
};
|
|
2387
2448
|
const scaffoldNewCommand = async (boundedContextFolder)=>{
|
|
@@ -2493,7 +2554,7 @@ describe('${naming.withSpaces} command', () => {
|
|
|
2493
2554
|
'commands'
|
|
2494
2555
|
]).createFile(`wire-${naming.fileName}-command.ts`, `
|
|
2495
2556
|
import { wireClass } from '@domain-first/wire'
|
|
2496
|
-
import { envBranchedWire } from '../../../../shared/wiring/env-branched-wire'
|
|
2557
|
+
import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
|
|
2497
2558
|
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Command } from '../../infrastructure/commands/${fileName}/${fileName}-${naming.fileName}-command'`).join('\n')}
|
|
2498
2559
|
|
|
2499
2560
|
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Command, [])`).join('\n\n')}
|
|
@@ -2614,14 +2675,26 @@ export const wire${naming.ClassName}DomainService = wireClass(
|
|
|
2614
2675
|
const errorNames = (boundedContextFolder)=>{
|
|
2615
2676
|
const isShared = boundedContextFolder.path === new Folder(new ProjectRoot().path).subitem([
|
|
2616
2677
|
ConfigFile.Instance.data.rootFolder,
|
|
2617
|
-
'shared'
|
|
2678
|
+
'shared-kernel'
|
|
2618
2679
|
]).path;
|
|
2619
2680
|
return {
|
|
2620
|
-
namespace: (namespaceName)=>`${namespaceName}${isShared ? '
|
|
2621
|
-
error: (errorName)=>`${errorName}${isShared ? '
|
|
2681
|
+
namespace: (namespaceName)=>`${namespaceName}${isShared ? 'SharedKernel' : ''}Errors`,
|
|
2682
|
+
error: (errorName)=>`${errorName}${isShared ? 'SharedKernelError' : ''}`
|
|
2622
2683
|
};
|
|
2623
2684
|
};
|
|
2624
|
-
const
|
|
2685
|
+
const namespacePattern = /export\s+const\s+(\w+)\s*=\s*errorNamespace\b/;
|
|
2686
|
+
const exportedNamespace = (file, fallback)=>namespacePattern.exec(file.data)?.[1] ?? fallback;
|
|
2687
|
+
const rootNamespace = (indexFile, namespace, code)=>{
|
|
2688
|
+
const content = indexFile.exists ? indexFile.data.trim() : '';
|
|
2689
|
+
const existing = namespacePattern.exec(content)?.[1];
|
|
2690
|
+
if (existing) return existing;
|
|
2691
|
+
indexFile.update([
|
|
2692
|
+
"import { errorNamespace } from '@domain-first/errors'",
|
|
2693
|
+
`export const ${namespace} = errorNamespace('${code}')`,
|
|
2694
|
+
content
|
|
2695
|
+
].filter((x)=>!!x).join('\n\n'));
|
|
2696
|
+
return namespace;
|
|
2697
|
+
};
|
|
2625
2698
|
const errorClass = (className, namespace, code)=>`export class ${className} extends ${namespace}.define('${code}') {}`;
|
|
2626
2699
|
const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
|
|
2627
2700
|
const currentErrorFolder = boundedContextFolder.subitem([
|
|
@@ -2646,7 +2719,7 @@ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
|
|
|
2646
2719
|
});
|
|
2647
2720
|
const naming = new UnknownFormatNaming(errorName);
|
|
2648
2721
|
const indexFile = currentErrorFolder.file('index.ts');
|
|
2649
|
-
indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName),
|
|
2722
|
+
indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), rootNamespace(indexFile, `${contextNaming.ClassName}Errors`, boundedContextFolder.name), naming.fileName), '\n\n');
|
|
2650
2723
|
return;
|
|
2651
2724
|
}
|
|
2652
2725
|
if ('New namespace' === selectedVariant) {
|
|
@@ -2739,7 +2812,7 @@ export const restHandlers = restWires.map(x => x().handle)
|
|
|
2739
2812
|
const endpointGenerator = findRestEndpointGenerator(boundedContextFolder.subitem([
|
|
2740
2813
|
'..',
|
|
2741
2814
|
'..',
|
|
2742
|
-
'shared'
|
|
2815
|
+
'shared-kernel'
|
|
2743
2816
|
]));
|
|
2744
2817
|
const handler = withWiring ? await promptEndpointHandler(boundedContextFolder) : void 0;
|
|
2745
2818
|
const endpointFile = node_path.join(endpointFolder.path, `${method.toUpperCase()}.ts`);
|
|
@@ -2947,7 +3020,7 @@ describe('${naming.withSpaces} query', () => {
|
|
|
2947
3020
|
'queries'
|
|
2948
3021
|
]).createFile(`wire-${naming.fileName}-query.ts`, `
|
|
2949
3022
|
import { wireClass } from '@domain-first/wire'
|
|
2950
|
-
import { envBranchedWire } from '../../../../shared/wiring/env-branched-wire'
|
|
3023
|
+
import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
|
|
2951
3024
|
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Query } from '../../infrastructure/queries/${fileName}/${fileName}-${naming.fileName}-query'`).join('\n')}
|
|
2952
3025
|
|
|
2953
3026
|
${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Query, [])`).join('\n\n')}
|