@domain-first/project-structure 5.1.2 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/dist/287.js +3217 -0
- package/dist/index.cjs +148 -1293
- package/dist/index.js +4 -3124
- package/dist/integration.cjs +1684 -0
- package/dist/integration.d.ts +2 -0
- package/dist/integration.js +31 -0
- package/dist/integrations/orval.d.ts +7 -4
- package/dist/print-next-steps.d.ts +7 -0
- package/dist/use-cases/add-integration-order.spec.d.ts +1 -0
- package/package.json +3 -2
- package/skills/df-ps-implement/SKILL.md +4 -4
- package/skills/df-ps-plan-feature/SKILL.md +1 -1
- package/skills/df-ps-scaffold/SKILL.md +16 -16
- package/skills/df-ps-scaffold/references/generators.md +2 -2
- package/skills/df-ps-scaffold/scripts/drive.mjs +3 -3
|
@@ -0,0 +1,1684 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __webpack_require__ = {};
|
|
4
|
+
(()=>{
|
|
5
|
+
__webpack_require__.n = (module)=>{
|
|
6
|
+
var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
|
|
7
|
+
__webpack_require__.d(getter, {
|
|
8
|
+
a: getter
|
|
9
|
+
});
|
|
10
|
+
return getter;
|
|
11
|
+
};
|
|
12
|
+
})();
|
|
13
|
+
(()=>{
|
|
14
|
+
__webpack_require__.d = (exports1, getters, values)=>{
|
|
15
|
+
var define = (defs, kind)=>{
|
|
16
|
+
for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
|
|
17
|
+
enumerable: true,
|
|
18
|
+
[kind]: defs[key]
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
define(getters, "get");
|
|
22
|
+
define(values, "value");
|
|
23
|
+
};
|
|
24
|
+
})();
|
|
25
|
+
(()=>{
|
|
26
|
+
__webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
|
|
27
|
+
})();
|
|
28
|
+
var __webpack_exports__ = {};
|
|
29
|
+
const external_node_util_namespaceObject = require("node:util");
|
|
30
|
+
const external_node_path_namespaceObject = require("node:path");
|
|
31
|
+
var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
|
|
32
|
+
const external_zod_namespaceObject = require("zod");
|
|
33
|
+
var external_zod_default = /*#__PURE__*/ __webpack_require__.n(external_zod_namespaceObject);
|
|
34
|
+
const moduleKinds = [
|
|
35
|
+
'repositories',
|
|
36
|
+
'domain-services',
|
|
37
|
+
'application-ports',
|
|
38
|
+
'application-services',
|
|
39
|
+
'use-cases',
|
|
40
|
+
'commands',
|
|
41
|
+
'queries',
|
|
42
|
+
'infrastructure-services',
|
|
43
|
+
'presentation-services'
|
|
44
|
+
];
|
|
45
|
+
const domain = [
|
|
46
|
+
'repositories',
|
|
47
|
+
'domain-services'
|
|
48
|
+
];
|
|
49
|
+
const commandsAndQueries = [
|
|
50
|
+
'commands',
|
|
51
|
+
'queries'
|
|
52
|
+
];
|
|
53
|
+
const infrastructure = [
|
|
54
|
+
...domain,
|
|
55
|
+
'application-ports',
|
|
56
|
+
'infrastructure-services'
|
|
57
|
+
];
|
|
58
|
+
const defaultDependencies = {
|
|
59
|
+
'domain-services': [
|
|
60
|
+
'domain-services'
|
|
61
|
+
],
|
|
62
|
+
repositories: [
|
|
63
|
+
'domain-services',
|
|
64
|
+
'application-ports',
|
|
65
|
+
'infrastructure-services'
|
|
66
|
+
],
|
|
67
|
+
'application-ports': infrastructure,
|
|
68
|
+
'application-services': [
|
|
69
|
+
...domain,
|
|
70
|
+
'application-ports',
|
|
71
|
+
...commandsAndQueries
|
|
72
|
+
],
|
|
73
|
+
'use-cases': [
|
|
74
|
+
...domain,
|
|
75
|
+
'application-ports',
|
|
76
|
+
'application-services',
|
|
77
|
+
...commandsAndQueries
|
|
78
|
+
],
|
|
79
|
+
commands: [
|
|
80
|
+
'infrastructure-services'
|
|
81
|
+
],
|
|
82
|
+
queries: [
|
|
83
|
+
'infrastructure-services'
|
|
84
|
+
],
|
|
85
|
+
'infrastructure-services': infrastructure,
|
|
86
|
+
'presentation-services': [
|
|
87
|
+
'application-ports',
|
|
88
|
+
'application-services',
|
|
89
|
+
'use-cases',
|
|
90
|
+
...commandsAndQueries,
|
|
91
|
+
'presentation-services'
|
|
92
|
+
]
|
|
93
|
+
};
|
|
94
|
+
const kindSchema = external_zod_default()["enum"](moduleKinds);
|
|
95
|
+
const dependencyRulesSchema = external_zod_default().partialRecord(kindSchema, external_zod_default().union([
|
|
96
|
+
external_zod_default().array(kindSchema),
|
|
97
|
+
external_zod_default().object({
|
|
98
|
+
add: external_zod_default().array(kindSchema).optional(),
|
|
99
|
+
remove: external_zod_default().array(kindSchema).optional()
|
|
100
|
+
})
|
|
101
|
+
]));
|
|
102
|
+
const dependency_rules_resolveDependencyRules = (config = {})=>{
|
|
103
|
+
const entries = moduleKinds.map((kind)=>{
|
|
104
|
+
const override = config[kind];
|
|
105
|
+
if (Array.isArray(override)) return [
|
|
106
|
+
kind,
|
|
107
|
+
new Set(override)
|
|
108
|
+
];
|
|
109
|
+
const kinds = new Set([
|
|
110
|
+
...defaultDependencies[kind],
|
|
111
|
+
...override?.add ?? []
|
|
112
|
+
]);
|
|
113
|
+
for (const removed of override?.remove ?? [])kinds.delete(removed);
|
|
114
|
+
return [
|
|
115
|
+
kind,
|
|
116
|
+
kinds
|
|
117
|
+
];
|
|
118
|
+
});
|
|
119
|
+
return Object.fromEntries(entries);
|
|
120
|
+
};
|
|
121
|
+
dependency_rules_resolveDependencyRules();
|
|
122
|
+
const external_node_fs_namespaceObject = require("node:fs");
|
|
123
|
+
var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
|
|
124
|
+
const pendingFiles = new Map();
|
|
125
|
+
const pendingFolders = new Set();
|
|
126
|
+
const pendingMoves = new Map();
|
|
127
|
+
const pendingDeletions = new Map();
|
|
128
|
+
const filesToOverwrite = ()=>[
|
|
129
|
+
...pendingFiles
|
|
130
|
+
].filter(([filePath, { replacesFile }])=>replacesFile && external_node_fs_default().existsSync(filePath)).map(([filePath])=>filePath);
|
|
131
|
+
const file_system_discardPendingChanges = ()=>{
|
|
132
|
+
pendingFolders.clear();
|
|
133
|
+
pendingFiles.clear();
|
|
134
|
+
pendingMoves.clear();
|
|
135
|
+
pendingDeletions.clear();
|
|
136
|
+
};
|
|
137
|
+
const removeEmptyFolders = (folderPath, stopAt)=>{
|
|
138
|
+
let current = folderPath;
|
|
139
|
+
while(current.startsWith(`${stopAt}${external_node_path_default().sep}`) && external_node_fs_default().existsSync(current) && !external_node_fs_default().readdirSync(current).length){
|
|
140
|
+
external_node_fs_default().rmdirSync(current);
|
|
141
|
+
current = external_node_path_default().dirname(current);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
const writePendingChanges = ()=>{
|
|
145
|
+
for (const folderPath of pendingFolders)external_node_fs_default().mkdirSync(folderPath, {
|
|
146
|
+
recursive: true
|
|
147
|
+
});
|
|
148
|
+
for (const [filePath, { content }] of pendingFiles){
|
|
149
|
+
external_node_fs_default().mkdirSync(external_node_path_default().dirname(filePath), {
|
|
150
|
+
recursive: true
|
|
151
|
+
});
|
|
152
|
+
external_node_fs_default().writeFileSync(filePath, content, 'utf8');
|
|
153
|
+
}
|
|
154
|
+
for (const [targetPath, { sourcePath }] of pendingMoves){
|
|
155
|
+
external_node_fs_default().mkdirSync(external_node_path_default().dirname(targetPath), {
|
|
156
|
+
recursive: true
|
|
157
|
+
});
|
|
158
|
+
external_node_fs_default().renameSync(sourcePath, targetPath);
|
|
159
|
+
}
|
|
160
|
+
for (const filePath of pendingDeletions.keys())external_node_fs_default().rmSync(filePath, {
|
|
161
|
+
force: true
|
|
162
|
+
});
|
|
163
|
+
for (const [filePath, stopAt] of pendingDeletions)removeEmptyFolders(external_node_path_default().dirname(filePath), stopAt);
|
|
164
|
+
for (const { sourcePath, stopAt } of pendingMoves.values())removeEmptyFolders(external_node_path_default().dirname(sourcePath), stopAt);
|
|
165
|
+
file_system_discardPendingChanges();
|
|
166
|
+
};
|
|
167
|
+
class FileSystemItem {
|
|
168
|
+
path;
|
|
169
|
+
constructor(path){
|
|
170
|
+
this.path = path;
|
|
171
|
+
}
|
|
172
|
+
subitem = (relativePath)=>new this.constructor(external_node_path_default().resolve(this.path, ...relativePath));
|
|
173
|
+
get exists() {
|
|
174
|
+
return external_node_fs_default().existsSync(this.path);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
class file_system_Folder extends FileSystemItem {
|
|
178
|
+
createIfNotExisted = ()=>{
|
|
179
|
+
pendingFolders.add(this.path);
|
|
180
|
+
};
|
|
181
|
+
get content() {
|
|
182
|
+
if (!this.exists) return {
|
|
183
|
+
subfolderNames: [],
|
|
184
|
+
fileNames: []
|
|
185
|
+
};
|
|
186
|
+
const content = external_node_fs_default().readdirSync(this.path, {
|
|
187
|
+
withFileTypes: true
|
|
188
|
+
});
|
|
189
|
+
return {
|
|
190
|
+
subfolderNames: content.filter((x)=>x.isDirectory()).map((x)=>x.name),
|
|
191
|
+
fileNames: content.filter((x)=>!x.isDirectory()).map((x)=>external_node_path_default().parse(x.name).name)
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
get name() {
|
|
195
|
+
return external_node_path_default().basename(this.path);
|
|
196
|
+
}
|
|
197
|
+
createFile = (name, content)=>{
|
|
198
|
+
this.createIfNotExisted();
|
|
199
|
+
const file = new file_system_File(this.path).subitem([
|
|
200
|
+
name
|
|
201
|
+
]);
|
|
202
|
+
file.data = content;
|
|
203
|
+
return file;
|
|
204
|
+
};
|
|
205
|
+
file = (name)=>{
|
|
206
|
+
this.createIfNotExisted();
|
|
207
|
+
const file = new file_system_File(this.path).subitem([
|
|
208
|
+
name
|
|
209
|
+
]);
|
|
210
|
+
return file;
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
class file_system_File extends FileSystemItem {
|
|
214
|
+
get exists() {
|
|
215
|
+
return pendingFiles.has(this.path) || pendingMoves.has(this.path) || external_node_fs_default().existsSync(this.path) && !pendingDeletions.has(this.path);
|
|
216
|
+
}
|
|
217
|
+
delete = (stopAt)=>{
|
|
218
|
+
pendingDeletions.set(this.path, stopAt);
|
|
219
|
+
};
|
|
220
|
+
moveTo = (targetPath, stopAt)=>{
|
|
221
|
+
pendingMoves.set(targetPath, {
|
|
222
|
+
sourcePath: this.path,
|
|
223
|
+
stopAt
|
|
224
|
+
});
|
|
225
|
+
};
|
|
226
|
+
get data() {
|
|
227
|
+
const pendingFile = pendingFiles.get(this.path);
|
|
228
|
+
if (pendingFile) return pendingFile.content;
|
|
229
|
+
if (!this.exists) throw new Error('File does not exist');
|
|
230
|
+
return external_node_fs_default().readFileSync(this.path, 'utf-8');
|
|
231
|
+
}
|
|
232
|
+
set data(content) {
|
|
233
|
+
pendingFiles.set(this.path, {
|
|
234
|
+
content,
|
|
235
|
+
replacesFile: true
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
update = (content)=>{
|
|
239
|
+
pendingFiles.set(this.path, {
|
|
240
|
+
content,
|
|
241
|
+
replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
|
|
242
|
+
});
|
|
243
|
+
};
|
|
244
|
+
addLine = (newLine, separator = '\n')=>{
|
|
245
|
+
const content = this.exists ? this.data : '';
|
|
246
|
+
pendingFiles.set(this.path, {
|
|
247
|
+
content: [
|
|
248
|
+
content.trim(),
|
|
249
|
+
newLine.trim()
|
|
250
|
+
].filter((x)=>!!x).join(separator),
|
|
251
|
+
replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
|
|
252
|
+
});
|
|
253
|
+
};
|
|
254
|
+
addLineIfMissing = (newLine, separator = '\n')=>{
|
|
255
|
+
const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
|
|
256
|
+
if (!alreadyAdded) this.addLine(newLine, separator);
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
class project_root_ProjectRoot {
|
|
260
|
+
path;
|
|
261
|
+
constructor(){
|
|
262
|
+
let dir = process.cwd();
|
|
263
|
+
while(dir !== external_node_path_default().parse(dir).root){
|
|
264
|
+
if (external_node_fs_default().existsSync(external_node_path_default().join(dir, 'package.json'))) {
|
|
265
|
+
this.path = dir;
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
dir = external_node_path_default().dirname(dir);
|
|
269
|
+
}
|
|
270
|
+
throw new Error('No package.json was found');
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const lintChecks = [
|
|
274
|
+
'context-isolation',
|
|
275
|
+
'shared-layer',
|
|
276
|
+
'layers',
|
|
277
|
+
'dependencies',
|
|
278
|
+
'react',
|
|
279
|
+
'clock'
|
|
280
|
+
];
|
|
281
|
+
const configFileName = 'domain-first.project-structure.config.json';
|
|
282
|
+
const configSchema = external_zod_default().object({
|
|
283
|
+
rootFolder: external_zod_default().string(),
|
|
284
|
+
domainFirstPackages: external_zod_default().array(external_zod_default()["enum"]([
|
|
285
|
+
'@domain-first/types',
|
|
286
|
+
'@domain-first/errors',
|
|
287
|
+
'@domain-first/handlers',
|
|
288
|
+
'@domain-first/wire',
|
|
289
|
+
'@domain-first/handlers-rest'
|
|
290
|
+
])),
|
|
291
|
+
defaultPersistenceLayerImplementation: external_zod_default().string(),
|
|
292
|
+
withInMemoryDb: external_zod_default().boolean().optional(),
|
|
293
|
+
useReact: external_zod_default().boolean(),
|
|
294
|
+
storybookFramework: external_zod_default().string().optional(),
|
|
295
|
+
testingLibrary: external_zod_default().string().optional(),
|
|
296
|
+
rules: external_zod_default().object({
|
|
297
|
+
dependencies: dependencyRulesSchema.optional(),
|
|
298
|
+
lint: external_zod_default().partialRecord(external_zod_default()["enum"](lintChecks), external_zod_default().boolean()).optional()
|
|
299
|
+
}).optional()
|
|
300
|
+
});
|
|
301
|
+
class config_file_ConfigFile {
|
|
302
|
+
data;
|
|
303
|
+
constructor(){
|
|
304
|
+
const filePath = config_file_ConfigFile.path;
|
|
305
|
+
const file = new file_system_File(filePath);
|
|
306
|
+
const configObject = JSON.parse(file.data);
|
|
307
|
+
this.data = configSchema.parse(configObject);
|
|
308
|
+
}
|
|
309
|
+
static get Instance() {
|
|
310
|
+
return new config_file_ConfigFile();
|
|
311
|
+
}
|
|
312
|
+
static get path() {
|
|
313
|
+
const { path: root } = new project_root_ProjectRoot();
|
|
314
|
+
return external_node_path_default().resolve(root, configFileName);
|
|
315
|
+
}
|
|
316
|
+
static get exists() {
|
|
317
|
+
return new file_system_File(config_file_ConfigFile.path).exists;
|
|
318
|
+
}
|
|
319
|
+
static write = (config)=>{
|
|
320
|
+
new file_system_File(config_file_ConfigFile.path).data = JSON.stringify(config, null, '\t');
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
const prompts_namespaceObject = require("@inquirer/prompts");
|
|
324
|
+
const missingDomainFirstPackages = ()=>{
|
|
325
|
+
const packages = config_file_ConfigFile.Instance.data.domainFirstPackages;
|
|
326
|
+
const manifest = JSON.parse(new file_system_File(external_node_path_default().join(new project_root_ProjectRoot().path, 'package.json')).data);
|
|
327
|
+
const dependencies = {
|
|
328
|
+
...manifest.dependencies,
|
|
329
|
+
...manifest.devDependencies,
|
|
330
|
+
...manifest.optionalDependencies
|
|
331
|
+
};
|
|
332
|
+
const missing = [
|
|
333
|
+
...new Set(packages)
|
|
334
|
+
].filter((name)=>!Object.hasOwn(dependencies, name));
|
|
335
|
+
return missing.length ? [
|
|
336
|
+
`npm i ${missing.join(' ')}`
|
|
337
|
+
] : [];
|
|
338
|
+
};
|
|
339
|
+
const external_node_module_namespaceObject = require("node:module");
|
|
340
|
+
const tsconfig_stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
|
|
341
|
+
const resolveExtends = (fromFile, target)=>{
|
|
342
|
+
if (target.startsWith('.') || external_node_path_default().isAbsolute(target)) {
|
|
343
|
+
const resolved = external_node_path_default().resolve(external_node_path_default().dirname(fromFile), target);
|
|
344
|
+
return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
|
|
345
|
+
}
|
|
346
|
+
const require1 = (0, external_node_module_namespaceObject.createRequire)(fromFile);
|
|
347
|
+
for (const candidate of [
|
|
348
|
+
target,
|
|
349
|
+
`${target}/tsconfig.json`
|
|
350
|
+
])try {
|
|
351
|
+
return require1.resolve(candidate);
|
|
352
|
+
} catch {}
|
|
353
|
+
};
|
|
354
|
+
const compilerOption = (configFile, name, seen = new Set())=>{
|
|
355
|
+
if (seen.has(configFile) || !external_node_fs_default().existsSync(configFile)) return null;
|
|
356
|
+
seen.add(configFile);
|
|
357
|
+
let config;
|
|
358
|
+
try {
|
|
359
|
+
config = JSON.parse(tsconfig_stripJsonComments(external_node_fs_default().readFileSync(configFile, 'utf8')));
|
|
360
|
+
} catch {
|
|
361
|
+
return null;
|
|
362
|
+
}
|
|
363
|
+
if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
|
|
364
|
+
const parents = [
|
|
365
|
+
config.extends ?? []
|
|
366
|
+
].flat().reverse();
|
|
367
|
+
for (const parent of parents){
|
|
368
|
+
const parentFile = resolveExtends(configFile, parent);
|
|
369
|
+
const value = parentFile ? compilerOption(parentFile, name, seen) : null;
|
|
370
|
+
if (void 0 !== value) return value;
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
|
|
374
|
+
${[
|
|
375
|
+
...imports,
|
|
376
|
+
"import { type FC } from 'react'"
|
|
377
|
+
].join('\n')}
|
|
378
|
+
|
|
379
|
+
export type ${ClassName}PageProps = {}
|
|
380
|
+
|
|
381
|
+
export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
|
|
382
|
+
return ${body}
|
|
383
|
+
}
|
|
384
|
+
`.trim();
|
|
385
|
+
const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
|
|
386
|
+
const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
|
|
387
|
+
const openapiExtractor = (rootFolder)=>`import path from 'node:path';
|
|
388
|
+
import {
|
|
389
|
+
type DocNode,
|
|
390
|
+
DocPlainText,
|
|
391
|
+
TSDocConfiguration,
|
|
392
|
+
TSDocParser,
|
|
393
|
+
TSDocTagDefinition,
|
|
394
|
+
TSDocTagSyntaxKind
|
|
395
|
+
} from '@microsoft/tsdoc';
|
|
396
|
+
import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
|
|
397
|
+
|
|
398
|
+
type BlockTag = \`@\${string}\`;
|
|
399
|
+
|
|
400
|
+
type OpenApiDataTags = {
|
|
401
|
+
/** Omit to take the summary from the comment text before the first tag. */
|
|
402
|
+
summary?: BlockTag;
|
|
403
|
+
description?: BlockTag;
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
type OpenApiData = Partial<{
|
|
407
|
+
summary: string;
|
|
408
|
+
description: string;
|
|
409
|
+
operationId: string;
|
|
410
|
+
}>;
|
|
411
|
+
|
|
412
|
+
const project = new Project({
|
|
413
|
+
tsConfigFilePath: 'tsconfig.json'
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
const getText = (node: DocNode): string =>
|
|
417
|
+
node
|
|
418
|
+
.getChildNodes()
|
|
419
|
+
.map((child) => {
|
|
420
|
+
if (child instanceof DocPlainText) {
|
|
421
|
+
return child.text;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
return getText(child);
|
|
425
|
+
})
|
|
426
|
+
.join('');
|
|
427
|
+
|
|
428
|
+
const getRawCommentText = (comment: string): string =>
|
|
429
|
+
comment
|
|
430
|
+
.replace(/^\\/\\*\\*/, '')
|
|
431
|
+
.replace(/\\*\\/$/, '')
|
|
432
|
+
.split(/\\r?\\n/)
|
|
433
|
+
.map((line) => line.replace(/^\\s*\\*\\s?/, ''))
|
|
434
|
+
.join('\\n');
|
|
435
|
+
|
|
436
|
+
// TSDoc treats an unknown tag as summary content, so every block tag of the
|
|
437
|
+
// comment has to be registered for the summary section to end before it.
|
|
438
|
+
const parseSummary = (comment: string): string | undefined => {
|
|
439
|
+
const configuration = new TSDocConfiguration();
|
|
440
|
+
const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
|
|
441
|
+
|
|
442
|
+
for (const [, tagName] of tagNames) {
|
|
443
|
+
if (!configuration.tryGetTagDefinition(tagName)) {
|
|
444
|
+
configuration.addTagDefinition(
|
|
445
|
+
new TSDocTagDefinition({
|
|
446
|
+
tagName,
|
|
447
|
+
syntaxKind: TSDocTagSyntaxKind.BlockTag
|
|
448
|
+
})
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const { docComment } = new TSDocParser(configuration).parseString(comment);
|
|
454
|
+
|
|
455
|
+
return getText(docComment.summarySection).trim() || undefined;
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
// Parsed by hand rather than through TSDoc, which drops the line breaks.
|
|
459
|
+
const getTagText = (comment: string, tag: BlockTag): string | undefined => {
|
|
460
|
+
const tagMatch = getRawCommentText(comment).match(
|
|
461
|
+
new RegExp(
|
|
462
|
+
\`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
|
|
463
|
+
)
|
|
464
|
+
);
|
|
465
|
+
|
|
466
|
+
return tagMatch?.[1].trim() || undefined;
|
|
467
|
+
};
|
|
468
|
+
|
|
469
|
+
// Endpoints pass their logic as the generator's first argument
|
|
470
|
+
// (\`this.endpointGenerator(this.handler.handle, ...)\`), while other injected
|
|
471
|
+
// queries only serve as helpers, e.g. guest checks.
|
|
472
|
+
const findHandlerClass = (endpointFile: SourceFile) =>
|
|
473
|
+
endpointFile
|
|
474
|
+
.getDescendantsOfKind(SyntaxKind.CallExpression)
|
|
475
|
+
.map((call) => call.getArguments()[0])
|
|
476
|
+
.filter(Node.isPropertyAccessExpression)
|
|
477
|
+
.find((argument) => argument.getName() === 'handle')
|
|
478
|
+
?.getExpression()
|
|
479
|
+
.getType()
|
|
480
|
+
.getSymbol()
|
|
481
|
+
?.getDeclarations()
|
|
482
|
+
.find(Node.isClassDeclaration);
|
|
483
|
+
|
|
484
|
+
// Path parameters (\`:id\`) can't be part of file and folder names
|
|
485
|
+
// everywhere (Windows), so endpoints name them \`_id_\` there.
|
|
486
|
+
const pathParameterAsName = (segment: string) =>
|
|
487
|
+
segment.startsWith(':') ? \`_\${segment.slice(1)}_\` : segment;
|
|
488
|
+
|
|
489
|
+
export const createOpenApiDataFromEndpointLogicExtractor = ({
|
|
490
|
+
summary: summaryTag,
|
|
491
|
+
description: descriptionTag = '@description'
|
|
492
|
+
}: OpenApiDataTags = {}) => {
|
|
493
|
+
return (routeMetadata: {
|
|
494
|
+
method: string;
|
|
495
|
+
path: readonly string[];
|
|
496
|
+
}): OpenApiData | undefined => {
|
|
497
|
+
try {
|
|
498
|
+
const [currentBoundedContext, controller, ...relativePath] =
|
|
499
|
+
routeMetadata.path;
|
|
500
|
+
|
|
501
|
+
if (!currentBoundedContext || !controller) {
|
|
502
|
+
return undefined;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
const endpointFile = project.getSourceFile(
|
|
506
|
+
path.join(
|
|
507
|
+
${rootFolderSegments(rootFolder)}'bounded-contexts',
|
|
508
|
+
currentBoundedContext,
|
|
509
|
+
'presentation',
|
|
510
|
+
'rest',
|
|
511
|
+
controller,
|
|
512
|
+
...relativePath.map(pathParameterAsName),
|
|
513
|
+
\`\${routeMetadata.method.toUpperCase()}.ts\`
|
|
514
|
+
)
|
|
515
|
+
);
|
|
516
|
+
|
|
517
|
+
if (!endpointFile) {
|
|
518
|
+
return undefined;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const declaration = findHandlerClass(endpointFile);
|
|
522
|
+
const operationId = declaration?.getName();
|
|
523
|
+
const comment = declaration?.getJsDocs().at(-1)?.getText();
|
|
524
|
+
|
|
525
|
+
if (!comment) {
|
|
526
|
+
return { operationId };
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
return {
|
|
530
|
+
summary: summaryTag
|
|
531
|
+
? getTagText(comment, summaryTag)
|
|
532
|
+
: parseSummary(comment),
|
|
533
|
+
description: getTagText(comment, descriptionTag),
|
|
534
|
+
operationId
|
|
535
|
+
};
|
|
536
|
+
} catch (e: unknown) {
|
|
537
|
+
console.error(e);
|
|
538
|
+
return undefined;
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
};
|
|
542
|
+
`;
|
|
543
|
+
const addPackageScripts = async (file, additions)=>{
|
|
544
|
+
const original = file.data;
|
|
545
|
+
const manifest = JSON.parse(original);
|
|
546
|
+
const scripts = {
|
|
547
|
+
...manifest.scripts
|
|
548
|
+
};
|
|
549
|
+
const selected = {};
|
|
550
|
+
for (const [name, command] of Object.entries(additions)){
|
|
551
|
+
let target = name;
|
|
552
|
+
if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
|
|
553
|
+
const action = await (0, prompts_namespaceObject.select)({
|
|
554
|
+
message: `Script "${name}" already exists: ${scripts[name]}`,
|
|
555
|
+
choices: [
|
|
556
|
+
'Keep existing',
|
|
557
|
+
'Replace',
|
|
558
|
+
'Use another name'
|
|
559
|
+
]
|
|
560
|
+
});
|
|
561
|
+
if ('Keep existing' === action) continue;
|
|
562
|
+
if ('Use another name' === action) target = await (0, prompts_namespaceObject.input)({
|
|
563
|
+
message: "New script name:",
|
|
564
|
+
validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
scripts[target] = command;
|
|
568
|
+
selected[name] = target;
|
|
569
|
+
}
|
|
570
|
+
if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
|
|
571
|
+
manifest.scripts = scripts;
|
|
572
|
+
const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
|
|
573
|
+
file.update(`${JSON.stringify(manifest, null, indent)}\n`);
|
|
574
|
+
}
|
|
575
|
+
return selected;
|
|
576
|
+
};
|
|
577
|
+
const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
|
|
578
|
+
const openapiScriptPath = "scripts/generate-openapi.ts";
|
|
579
|
+
const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
|
|
580
|
+
const extractorPackages = [
|
|
581
|
+
'ts-morph',
|
|
582
|
+
'@microsoft/tsdoc'
|
|
583
|
+
];
|
|
584
|
+
const swaggerPagePath = (rootFolder)=>external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react/pages/swagger-page.tsx');
|
|
585
|
+
const swaggerPage = (rootFolder, outputPath)=>{
|
|
586
|
+
const specImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(swaggerPagePath(rootFolder)), outputPath);
|
|
587
|
+
return reactPageContent('Swagger', {
|
|
588
|
+
imports: [
|
|
589
|
+
"import 'swagger-ui-react/swagger-ui.css'",
|
|
590
|
+
"import SwaggerUI from 'swagger-ui-react'",
|
|
591
|
+
`import spec from '${specImport.startsWith('.') ? specImport : `./${specImport}`}' with { type: 'json' }`
|
|
592
|
+
],
|
|
593
|
+
body: '<SwaggerUI displayOperationId spec={spec} />'
|
|
594
|
+
});
|
|
595
|
+
};
|
|
596
|
+
const openapiScripts = {
|
|
597
|
+
openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
|
|
598
|
+
};
|
|
599
|
+
const splitPath = (value)=>value.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
|
|
600
|
+
const apiTitle = (packageName)=>{
|
|
601
|
+
const words = String(packageName ?? '').replace(/^@[^/]*\//, '').split(/[^a-zA-Z0-9]+/).filter((word)=>!!word).map((word)=>word[0].toUpperCase() + word.slice(1));
|
|
602
|
+
return [
|
|
603
|
+
...words,
|
|
604
|
+
'API'
|
|
605
|
+
].join(' ');
|
|
606
|
+
};
|
|
607
|
+
const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
|
|
608
|
+
const restFolder = external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
|
|
609
|
+
const restImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(openapiScriptPath), restFolder);
|
|
610
|
+
const prefixSegments = splitPath(routePrefix);
|
|
611
|
+
const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
|
|
612
|
+
const extractorImport = `./${external_node_path_default().posix.relative(external_node_path_default().posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
|
|
613
|
+
const handlers = withExtractor ? `
|
|
614
|
+
const extractOpenApiDataFromEndpointLogic =
|
|
615
|
+
createOpenApiDataFromEndpointLogicExtractor();
|
|
616
|
+
|
|
617
|
+
const handlers = restHandlers.map((x) => ({
|
|
618
|
+
...x,
|
|
619
|
+
metadata: {
|
|
620
|
+
...x.metadata,
|
|
621
|
+
openApiMetadata: {
|
|
622
|
+
...extractOpenApiDataFromEndpointLogic(x.metadata.route),
|
|
623
|
+
...(x.metadata.openApiMetadata ?? {})
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
}));
|
|
627
|
+
` : '';
|
|
628
|
+
return `import { generateOpenAPI } from '@domain-first/handlers-rest';
|
|
629
|
+
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
|
|
630
|
+
${handlers}
|
|
631
|
+
generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
|
|
632
|
+
document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
|
|
633
|
+
outputFile: { path: '${outputPath}' }
|
|
634
|
+
});
|
|
635
|
+
`;
|
|
636
|
+
};
|
|
637
|
+
const addOpenapi = async ()=>{
|
|
638
|
+
const { rootFolder } = config_file_ConfigFile.Instance.data;
|
|
639
|
+
const root = new project_root_ProjectRoot().path;
|
|
640
|
+
const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
|
|
641
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
642
|
+
const dependencies = {
|
|
643
|
+
...manifest.dependencies,
|
|
644
|
+
...manifest.devDependencies
|
|
645
|
+
};
|
|
646
|
+
const routePrefix = await (0, prompts_namespaceObject.input)({
|
|
647
|
+
message: 'Route prefix the REST handlers are served under:',
|
|
648
|
+
default: '/api'
|
|
649
|
+
});
|
|
650
|
+
const outputPath = await (0, prompts_namespaceObject.input)({
|
|
651
|
+
message: 'OpenAPI document path:',
|
|
652
|
+
default: defaultOpenapiPath(Boolean(dependencies.next)),
|
|
653
|
+
validate: (value)=>splitPath(value).length ? true : 'Path is required'
|
|
654
|
+
});
|
|
655
|
+
const withExtractor = await (0, prompts_namespaceObject.confirm)({
|
|
656
|
+
message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
|
|
657
|
+
default: true
|
|
658
|
+
});
|
|
659
|
+
const withSwaggerPage = config_file_ConfigFile.Instance.data.useReact && await (0, prompts_namespaceObject.confirm)({
|
|
660
|
+
message: 'Add a Swagger UI page?',
|
|
661
|
+
default: true
|
|
662
|
+
});
|
|
663
|
+
const selected = await addPackageScripts(manifestFile, openapiScripts);
|
|
664
|
+
if (withExtractor) {
|
|
665
|
+
const extractorFile = new file_system_File(external_node_path_default().join(root, openapiExtractorPath));
|
|
666
|
+
const extractor = openapiExtractor(rootFolder);
|
|
667
|
+
if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
|
|
668
|
+
}
|
|
669
|
+
const generatorFile = new file_system_File(external_node_path_default().join(root, openapiScriptPath));
|
|
670
|
+
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
|
|
671
|
+
if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
|
|
672
|
+
if (withSwaggerPage) {
|
|
673
|
+
const pageFile = new file_system_File(external_node_path_default().join(root, swaggerPagePath(rootFolder)));
|
|
674
|
+
const page = swaggerPage(rootFolder, splitPath(outputPath).join('/'));
|
|
675
|
+
if (!pageFile.exists || pageFile.data !== page) pageFile.data = page;
|
|
676
|
+
}
|
|
677
|
+
const resolveJsonModule = withSwaggerPage ? compilerOption(external_node_path_default().join(root, 'tsconfig.json'), 'resolveJsonModule') : true;
|
|
678
|
+
const hasRestHandlers = new file_system_File(external_node_path_default().join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
|
|
679
|
+
const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
|
|
680
|
+
return [
|
|
681
|
+
...dependencies['@domain-first/handlers-rest'] ? [] : [
|
|
682
|
+
'npm install @domain-first/handlers-rest'
|
|
683
|
+
],
|
|
684
|
+
...dependencies.tsx ? [] : [
|
|
685
|
+
'npm install --save-dev tsx'
|
|
686
|
+
],
|
|
687
|
+
...missingExtractorPackages.length ? [
|
|
688
|
+
`npm install --save-dev ${missingExtractorPackages.join(' ')}`
|
|
689
|
+
] : [],
|
|
690
|
+
...withSwaggerPage && !dependencies['swagger-ui-react'] ? [
|
|
691
|
+
'npm install swagger-ui-react'
|
|
692
|
+
] : [],
|
|
693
|
+
...withSwaggerPage && !dependencies['@types/swagger-ui-react'] ? [
|
|
694
|
+
'npm install --save-dev @types/swagger-ui-react'
|
|
695
|
+
] : [],
|
|
696
|
+
...true === resolveJsonModule || null === resolveJsonModule ? [] : [
|
|
697
|
+
'set "resolveJsonModule": true in compilerOptions of tsconfig.json — the Swagger UI page imports the OpenAPI document as JSON'
|
|
698
|
+
],
|
|
699
|
+
...describeScripts(selected, {
|
|
700
|
+
openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
|
|
701
|
+
}),
|
|
702
|
+
...withSwaggerPage ? [
|
|
703
|
+
`SwaggerPage from ${swaggerPagePath(rootFolder)} shows ${splitPath(outputPath).join('/')} once it is generated — render it on a route of your app`
|
|
704
|
+
] : [],
|
|
705
|
+
...hasRestHandlers ? [] : [
|
|
706
|
+
`restHandlers appear in ${external_node_path_default().posix.join(rootFolder, 'presentation/rest/index.ts')} with the first REST endpoint generated with @domain-first/wire`
|
|
707
|
+
]
|
|
708
|
+
];
|
|
709
|
+
};
|
|
710
|
+
const addGitignoreEntry = (root, entry)=>{
|
|
711
|
+
const gitignore = new file_system_File(external_node_path_default().join(root, '.gitignore'));
|
|
712
|
+
const ignored = gitignore.exists ? gitignore.data : '';
|
|
713
|
+
if (ignored.split(/\r?\n/).includes(entry)) return;
|
|
714
|
+
const newline = ignored.includes('\r\n') ? '\r\n' : '\n';
|
|
715
|
+
gitignore.update(`${ignored}${ignored && !ignored.endsWith('\n') ? newline : ''}${entry}${newline}`);
|
|
716
|
+
};
|
|
717
|
+
const dataLayerFolder = (rootFolder, target)=>external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'hooks' === target ? 'presentation/react/data-layer' : 'presentation/data-layer');
|
|
718
|
+
const orvalScripts = (rootFolder, targets)=>({
|
|
719
|
+
'client:orval': targets.map((target)=>`orval --config ${JSON.stringify(`${dataLayerFolder(rootFolder, target)}/orval.config.ts`)}`).join(' && ')
|
|
720
|
+
});
|
|
721
|
+
const orvalConfig = (rootFolder, openapiPath, withNext, target = 'hooks', mutatorPath = './api-client/mutator.ts')=>{
|
|
722
|
+
const inputPath = external_node_path_default().posix.relative(dataLayerFolder(rootFolder, target), openapiPath);
|
|
723
|
+
const baseUrl = withNext ? `
|
|
724
|
+
baseUrl: {
|
|
725
|
+
runtime: 'process.env.NEXT_PUBLIC_API_BASE_URL ?? ""'
|
|
726
|
+
},` : '';
|
|
727
|
+
const client = 'hooks' === target ? `
|
|
728
|
+
client: 'react-query',
|
|
729
|
+
httpClient: 'fetch',` : `
|
|
730
|
+
client: 'fetch',`;
|
|
731
|
+
const query = 'hooks' === target ? `,
|
|
732
|
+
query: {
|
|
733
|
+
version: 5
|
|
734
|
+
}` : '';
|
|
735
|
+
return `import { defineConfig } from 'orval';
|
|
736
|
+
|
|
737
|
+
export default defineConfig({
|
|
738
|
+
api: {
|
|
739
|
+
input: '${inputPath.startsWith('.') ? inputPath : `./${inputPath}`}',
|
|
740
|
+
output: {
|
|
741
|
+
mode: 'tags-split',
|
|
742
|
+
target: './orval',
|
|
743
|
+
schemas: './orval/model',${client}${baseUrl}
|
|
744
|
+
clean: true,
|
|
745
|
+
override: {
|
|
746
|
+
mutator: {
|
|
747
|
+
path: '${mutatorPath}',
|
|
748
|
+
name: 'customInstance'
|
|
749
|
+
},
|
|
750
|
+
fetch: {
|
|
751
|
+
includeHttpResponseReturnType: false
|
|
752
|
+
}${query}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
});
|
|
757
|
+
`;
|
|
758
|
+
};
|
|
759
|
+
const orvalMutator = `/** Error of the generated requests, with the parsed response body. */
|
|
760
|
+
export class ApiError<Body = unknown> extends Error {
|
|
761
|
+
constructor(
|
|
762
|
+
public readonly status: number,
|
|
763
|
+
public readonly body: Body
|
|
764
|
+
) {
|
|
765
|
+
super(\`API error \${status}\`);
|
|
766
|
+
this.name = 'ApiError';
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** Error type of the generated requests, typed per endpoint by Orval. */
|
|
771
|
+
export type ErrorType<Body> = ApiError<Body>;
|
|
772
|
+
|
|
773
|
+
/** Every generated request goes through here: add auth headers, token refresh, logging. */
|
|
774
|
+
export const customInstance = async <T>(
|
|
775
|
+
url: string,
|
|
776
|
+
init?: RequestInit
|
|
777
|
+
): Promise<T> => {
|
|
778
|
+
const response = await fetch(url, init);
|
|
779
|
+
const text = await response.text();
|
|
780
|
+
const body = text ? JSON.parse(text) : undefined;
|
|
781
|
+
|
|
782
|
+
if (!response.ok) {
|
|
783
|
+
throw new ApiError(response.status, body);
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
return body as T;
|
|
787
|
+
};
|
|
788
|
+
`;
|
|
789
|
+
const queryProvider = `'use client';
|
|
790
|
+
|
|
791
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
792
|
+
import { type FC, type ReactNode, useState } from 'react';
|
|
793
|
+
|
|
794
|
+
export const QueryProvider: FC<{ children: ReactNode }> = ({ children }) => {
|
|
795
|
+
// One client per browser session; a module-level client would be shared between requests on the server
|
|
796
|
+
const [queryClient] = useState(() => new QueryClient());
|
|
797
|
+
|
|
798
|
+
return (
|
|
799
|
+
<QueryClientProvider client={queryClient}>
|
|
800
|
+
{children}
|
|
801
|
+
</QueryClientProvider>
|
|
802
|
+
);
|
|
803
|
+
};
|
|
804
|
+
`;
|
|
805
|
+
const openapiOutputPath = (root)=>{
|
|
806
|
+
const generator = new file_system_File(external_node_path_default().join(root, openapiScriptPath));
|
|
807
|
+
if (!generator.exists) return;
|
|
808
|
+
return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
|
|
809
|
+
};
|
|
810
|
+
const addOrval = async ()=>{
|
|
811
|
+
const { rootFolder, useReact } = config_file_ConfigFile.Instance.data;
|
|
812
|
+
const root = new project_root_ProjectRoot().path;
|
|
813
|
+
const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
|
|
814
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
815
|
+
const dependencies = {
|
|
816
|
+
...manifest.dependencies,
|
|
817
|
+
...manifest.devDependencies
|
|
818
|
+
};
|
|
819
|
+
const withNext = Boolean(dependencies.next);
|
|
820
|
+
const generatedOpenapiPath = openapiOutputPath(root);
|
|
821
|
+
const openapiPath = await (0, prompts_namespaceObject.input)({
|
|
822
|
+
message: 'OpenAPI document path:',
|
|
823
|
+
default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
|
|
824
|
+
validate: (value)=>value.trim() ? true : 'Path is required'
|
|
825
|
+
});
|
|
826
|
+
const targets = useReact ? await (0, prompts_namespaceObject.checkbox)({
|
|
827
|
+
message: 'Generate:',
|
|
828
|
+
choices: [
|
|
829
|
+
{
|
|
830
|
+
name: 'React Query hooks',
|
|
831
|
+
value: 'hooks',
|
|
832
|
+
checked: true
|
|
833
|
+
},
|
|
834
|
+
{
|
|
835
|
+
name: 'Typed API client',
|
|
836
|
+
value: 'client'
|
|
837
|
+
}
|
|
838
|
+
],
|
|
839
|
+
required: true
|
|
840
|
+
}) : [
|
|
841
|
+
'client'
|
|
842
|
+
];
|
|
843
|
+
const selected = await addPackageScripts(manifestFile, orvalScripts(rootFolder, targets));
|
|
844
|
+
const document = external_node_path_default().posix.normalize(openapiPath.trim().replaceAll('\\', '/'));
|
|
845
|
+
const withClient = targets.includes('client');
|
|
846
|
+
for (const target of targets){
|
|
847
|
+
const dataLayer = dataLayerFolder(rootFolder, target);
|
|
848
|
+
const sharedMutator = 'hooks' === target && withClient;
|
|
849
|
+
const mutatorPath = sharedMutator ? `${external_node_path_default().posix.relative(dataLayer, dataLayerFolder(rootFolder, 'client'))}/api-client/mutator.ts` : void 0;
|
|
850
|
+
const configFile = new file_system_File(external_node_path_default().join(root, dataLayer, 'orval.config.ts'));
|
|
851
|
+
const content = orvalConfig(rootFolder, document, withNext, target, mutatorPath);
|
|
852
|
+
if (!configFile.exists || configFile.data !== content) configFile.data = content;
|
|
853
|
+
for (const [name, fileContent] of [
|
|
854
|
+
...sharedMutator ? [] : [
|
|
855
|
+
[
|
|
856
|
+
'api-client/mutator.ts',
|
|
857
|
+
orvalMutator
|
|
858
|
+
]
|
|
859
|
+
],
|
|
860
|
+
...'hooks' === target ? [
|
|
861
|
+
[
|
|
862
|
+
'query-provider.tsx',
|
|
863
|
+
queryProvider
|
|
864
|
+
]
|
|
865
|
+
] : []
|
|
866
|
+
]){
|
|
867
|
+
const file = new file_system_File(external_node_path_default().join(root, dataLayer, name));
|
|
868
|
+
if (!file.exists) file.data = fileContent;
|
|
869
|
+
}
|
|
870
|
+
addGitignoreEntry(root, `/${dataLayer}/orval/`);
|
|
871
|
+
}
|
|
872
|
+
const generated = targets.map((target)=>'hooks' === target ? `React Query hooks in ${dataLayerFolder(rootFolder, 'hooks')}/orval` : `a typed API client in ${dataLayerFolder(rootFolder, 'client')}/orval`);
|
|
873
|
+
const missing = (names)=>names.filter((name)=>!dependencies[name]);
|
|
874
|
+
const runtime = missing(targets.includes('hooks') ? [
|
|
875
|
+
'@tanstack/react-query'
|
|
876
|
+
] : []);
|
|
877
|
+
const development = missing([
|
|
878
|
+
'orval'
|
|
879
|
+
]);
|
|
880
|
+
return [
|
|
881
|
+
...runtime.length ? [
|
|
882
|
+
`npm install ${runtime.join(' ')}`
|
|
883
|
+
] : [],
|
|
884
|
+
...development.length ? [
|
|
885
|
+
`npm install --save-dev ${development.join(' ')}`
|
|
886
|
+
] : [],
|
|
887
|
+
...describeScripts(selected, {
|
|
888
|
+
'client:orval': `generate ${generated.join(' and ')} from ${openapiPath.trim()}`
|
|
889
|
+
}),
|
|
890
|
+
...targets.includes('hooks') ? [
|
|
891
|
+
`Wrap your app in QueryProvider from ${dataLayerFolder(rootFolder, 'hooks')}/query-provider.tsx`
|
|
892
|
+
] : [],
|
|
893
|
+
...generatedOpenapiPath ? [] : [
|
|
894
|
+
'npx df-integration → OpenAPI generates the OpenAPI document the client is built from'
|
|
895
|
+
]
|
|
896
|
+
];
|
|
897
|
+
};
|
|
898
|
+
const playwrightScripts = {
|
|
899
|
+
'test:e2e': 'playwright test'
|
|
900
|
+
};
|
|
901
|
+
const playwrightConfig = `import { defineConfig, devices } from '@playwright/test';
|
|
902
|
+
|
|
903
|
+
export default defineConfig({
|
|
904
|
+
testDir: './specs/e2e',
|
|
905
|
+
fullyParallel: true,
|
|
906
|
+
forbidOnly: !!process.env.CI,
|
|
907
|
+
retries: process.env.CI ? 2 : 0,
|
|
908
|
+
workers: process.env.CI ? 1 : undefined,
|
|
909
|
+
reporter: 'html',
|
|
910
|
+
use: {
|
|
911
|
+
baseURL: 'http://localhost:3000',
|
|
912
|
+
trace: 'on-first-retry',
|
|
913
|
+
screenshot: 'only-on-failure',
|
|
914
|
+
video: 'retain-on-failure'
|
|
915
|
+
},
|
|
916
|
+
|
|
917
|
+
projects: [
|
|
918
|
+
{
|
|
919
|
+
name: 'chromium',
|
|
920
|
+
use: { ...devices['Desktop Chrome'] }
|
|
921
|
+
},
|
|
922
|
+
{
|
|
923
|
+
name: 'firefox',
|
|
924
|
+
use: { ...devices['Desktop Firefox'] }
|
|
925
|
+
},
|
|
926
|
+
{
|
|
927
|
+
name: 'webkit',
|
|
928
|
+
use: { ...devices['Desktop Safari'] }
|
|
929
|
+
},
|
|
930
|
+
{
|
|
931
|
+
name: 'Mobile Chrome',
|
|
932
|
+
use: { ...devices['Pixel 5'] }
|
|
933
|
+
},
|
|
934
|
+
{
|
|
935
|
+
name: 'Mobile Safari',
|
|
936
|
+
use: { ...devices['iPhone 12'] }
|
|
937
|
+
}
|
|
938
|
+
],
|
|
939
|
+
|
|
940
|
+
webServer: {
|
|
941
|
+
// Playwright only stops the dev server on a clean shutdown. If its process dies any other
|
|
942
|
+
// way (SIGHUP, SIGKILL), the dev server lives on in its own process group, so it is killed
|
|
943
|
+
// as soon as Playwright is gone.
|
|
944
|
+
command:
|
|
945
|
+
process.platform === 'win32'
|
|
946
|
+
? 'npm run dev'
|
|
947
|
+
: \`npm run dev & while kill -0 \${process.pid} 2>/dev/null && kill -0 $! 2>/dev/null; do sleep 1; done; kill 0\`,
|
|
948
|
+
url: 'http://localhost:3000',
|
|
949
|
+
timeout: 120000,
|
|
950
|
+
reuseExistingServer: !process.env.CI
|
|
951
|
+
}
|
|
952
|
+
});
|
|
953
|
+
`;
|
|
954
|
+
const exampleSpec = `import { expect, test } from '@playwright/test';
|
|
955
|
+
|
|
956
|
+
test.describe('home page', () => {
|
|
957
|
+
test('opens the home page', async ({ page, baseURL }) => {
|
|
958
|
+
await page.goto('/');
|
|
959
|
+
await expect(page).toHaveURL(\`\${baseURL}/\`);
|
|
960
|
+
});
|
|
961
|
+
});
|
|
962
|
+
`;
|
|
963
|
+
const exampleReadme = `# Home page e2e cases
|
|
964
|
+
|
|
965
|
+
## User Stories
|
|
966
|
+
|
|
967
|
+
1. Guest opens \`/\` and stays on the home page.
|
|
968
|
+
`;
|
|
969
|
+
const gitignoreEntries = [
|
|
970
|
+
'/test-results/',
|
|
971
|
+
'/playwright-report/',
|
|
972
|
+
'/blob-report/',
|
|
973
|
+
'/playwright/.cache/',
|
|
974
|
+
'/playwright/.auth/'
|
|
975
|
+
];
|
|
976
|
+
const addPlaywright = async ()=>{
|
|
977
|
+
const root = new project_root_ProjectRoot().path;
|
|
978
|
+
const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
|
|
979
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
980
|
+
const dependencies = {
|
|
981
|
+
...manifest.dependencies,
|
|
982
|
+
...manifest.devDependencies
|
|
983
|
+
};
|
|
984
|
+
const selected = await addPackageScripts(manifestFile, playwrightScripts);
|
|
985
|
+
const configFile = new file_system_File(external_node_path_default().join(root, 'playwright.config.ts'));
|
|
986
|
+
if (!configFile.exists || configFile.data !== playwrightConfig) configFile.data = playwrightConfig;
|
|
987
|
+
const exampleFolder = external_node_path_default().join(root, 'specs/e2e/home');
|
|
988
|
+
for (const [name, content] of [
|
|
989
|
+
[
|
|
990
|
+
'home.e2e.spec.ts',
|
|
991
|
+
exampleSpec
|
|
992
|
+
],
|
|
993
|
+
[
|
|
994
|
+
'README.MD',
|
|
995
|
+
exampleReadme
|
|
996
|
+
]
|
|
997
|
+
]){
|
|
998
|
+
const file = new file_system_File(external_node_path_default().join(exampleFolder, name));
|
|
999
|
+
if (!file.exists) file.data = content;
|
|
1000
|
+
}
|
|
1001
|
+
for (const entry of gitignoreEntries)addGitignoreEntry(root, entry);
|
|
1002
|
+
return [
|
|
1003
|
+
...dependencies['@playwright/test'] ? [] : [
|
|
1004
|
+
'npm install --save-dev @playwright/test'
|
|
1005
|
+
],
|
|
1006
|
+
'npx playwright install --with-deps',
|
|
1007
|
+
...describeScripts(selected, {
|
|
1008
|
+
'test:e2e': 'start the dev server and run end-to-end specs from specs/e2e'
|
|
1009
|
+
})
|
|
1010
|
+
];
|
|
1011
|
+
};
|
|
1012
|
+
const runtimePackages = [
|
|
1013
|
+
'@prisma/orm-postgres',
|
|
1014
|
+
'temporal-polyfill',
|
|
1015
|
+
'dotenv'
|
|
1016
|
+
];
|
|
1017
|
+
const developmentPackages = [
|
|
1018
|
+
'prisma',
|
|
1019
|
+
'@prisma/cli-engine'
|
|
1020
|
+
];
|
|
1021
|
+
const prismaScripts = (rootFolder)=>{
|
|
1022
|
+
const config = JSON.stringify(external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'shared/infrastructure/prisma/prisma.config.ts'));
|
|
1023
|
+
const emit = `prisma contract emit --config ${config}`;
|
|
1024
|
+
return {
|
|
1025
|
+
'prisma:emit': emit,
|
|
1026
|
+
'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
|
|
1027
|
+
'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
|
|
1028
|
+
};
|
|
1029
|
+
};
|
|
1030
|
+
const prismaConfig = `import 'dotenv/config';
|
|
1031
|
+
import { definePrismaConfig } from '@prisma/cli-engine';
|
|
1032
|
+
import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
|
|
1033
|
+
|
|
1034
|
+
export default definePrismaConfig({
|
|
1035
|
+
orm: ormConfig({
|
|
1036
|
+
contract: './contract.prisma',
|
|
1037
|
+
migrations: { dir: './migrations' },
|
|
1038
|
+
db: {
|
|
1039
|
+
connection: process.env.DATABASE_URL
|
|
1040
|
+
}
|
|
1041
|
+
})
|
|
1042
|
+
});
|
|
1043
|
+
`;
|
|
1044
|
+
const prismaService = `import 'temporal-polyfill/global';
|
|
1045
|
+
import postgres from '@prisma/orm-postgres/runtime';
|
|
1046
|
+
import type {} from 'temporal-polyfill/types/global';
|
|
1047
|
+
import type { Contract } from '../prisma/contract.d';
|
|
1048
|
+
import contractJson from '../prisma/contract.json' with { type: 'json' };
|
|
1049
|
+
|
|
1050
|
+
type PrismaClient = ReturnType<typeof postgres<Contract>>;
|
|
1051
|
+
|
|
1052
|
+
const globalForPrisma = globalThis as typeof globalThis & {
|
|
1053
|
+
prismaClient?: PrismaClient;
|
|
1054
|
+
};
|
|
1055
|
+
|
|
1056
|
+
// Reuse the client across development hot reloads.
|
|
1057
|
+
const prismaClient = globalForPrisma.prismaClient ??
|
|
1058
|
+
postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
|
|
1059
|
+
|
|
1060
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
1061
|
+
globalForPrisma.prismaClient = prismaClient;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
export class PrismaInfrastructureService {
|
|
1065
|
+
readonly orm = prismaClient.orm.public;
|
|
1066
|
+
}
|
|
1067
|
+
`;
|
|
1068
|
+
const prismaWiring = `import { wireClass } from '@domain-first/wire';
|
|
1069
|
+
import { PrismaInfrastructureService } from '../../infrastructure/services/prisma-infrastructure-service';
|
|
1070
|
+
|
|
1071
|
+
export const wirePrismaInfrastructureService = wireClass(
|
|
1072
|
+
PrismaInfrastructureService,
|
|
1073
|
+
[]
|
|
1074
|
+
);
|
|
1075
|
+
`;
|
|
1076
|
+
const stageFile = (filePath, content)=>{
|
|
1077
|
+
const file = new file_system_File(filePath);
|
|
1078
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
1079
|
+
};
|
|
1080
|
+
const addPrisma = async ()=>{
|
|
1081
|
+
const config = config_file_ConfigFile.Instance.data;
|
|
1082
|
+
const root = new project_root_ProjectRoot().path;
|
|
1083
|
+
const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
|
|
1084
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1085
|
+
const dependencies = {
|
|
1086
|
+
...manifest.dependencies,
|
|
1087
|
+
...manifest.devDependencies
|
|
1088
|
+
};
|
|
1089
|
+
const shared = external_node_path_default().resolve(root, config.rootFolder, 'shared');
|
|
1090
|
+
const prismaFolder = external_node_path_default().join(shared, 'infrastructure/prisma');
|
|
1091
|
+
if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
|
|
1092
|
+
external_node_path_default().join(root, 'prisma/schema.prisma'),
|
|
1093
|
+
external_node_path_default().join(prismaFolder, 'schema.prisma')
|
|
1094
|
+
].some((filePath)=>new file_system_File(filePath).exists)) throw new Error('This preset adds Prisma 8 for PostgreSQL. Migrate the existing Prisma setup separately before using it.');
|
|
1095
|
+
const withService = await (0, prompts_namespaceObject.confirm)({
|
|
1096
|
+
message: 'Create shared Prisma infrastructure service?',
|
|
1097
|
+
default: true
|
|
1098
|
+
});
|
|
1099
|
+
const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await (0, prompts_namespaceObject.confirm)({
|
|
1100
|
+
message: 'Use prisma as the default persistence implementation?',
|
|
1101
|
+
default: false
|
|
1102
|
+
});
|
|
1103
|
+
const selected = await addPackageScripts(manifestFile, prismaScripts(config.rootFolder));
|
|
1104
|
+
stageFile(external_node_path_default().join(prismaFolder, 'prisma.config.ts'), prismaConfig);
|
|
1105
|
+
const contract = new file_system_File(external_node_path_default().join(prismaFolder, 'contract.prisma'));
|
|
1106
|
+
if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
|
|
1107
|
+
if (withService) {
|
|
1108
|
+
stageFile(external_node_path_default().join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
|
|
1109
|
+
if (config.domainFirstPackages.includes('@domain-first/wire')) stageFile(external_node_path_default().join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
|
|
1110
|
+
}
|
|
1111
|
+
if (useByDefault) config_file_ConfigFile.write({
|
|
1112
|
+
...config,
|
|
1113
|
+
defaultPersistenceLayerImplementation: 'prisma'
|
|
1114
|
+
});
|
|
1115
|
+
const install = (packages, dev)=>{
|
|
1116
|
+
const missing = packages.filter((name)=>!dependencies[name]);
|
|
1117
|
+
return missing.length ? [
|
|
1118
|
+
`npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
|
|
1119
|
+
] : [];
|
|
1120
|
+
};
|
|
1121
|
+
const relativeFolder = external_node_path_default().relative(root, prismaFolder).split(external_node_path_default().sep).join('/');
|
|
1122
|
+
return [
|
|
1123
|
+
...install(runtimePackages, false),
|
|
1124
|
+
...install(developmentPackages, true),
|
|
1125
|
+
`Add !${relativeFolder} in your linter, to ignore prisma files.`,
|
|
1126
|
+
...describeScripts(selected, {
|
|
1127
|
+
'prisma:emit': 'emit contract.json and contract.d.ts from contract.prisma',
|
|
1128
|
+
'prisma:migration:plan': 'emit the contract and plan a migration',
|
|
1129
|
+
'prisma:migration:apply': 'apply planned migrations to the database in DATABASE_URL'
|
|
1130
|
+
})
|
|
1131
|
+
];
|
|
1132
|
+
};
|
|
1133
|
+
const storybookFiles = (relativeProjectRoot)=>({
|
|
1134
|
+
'main.ts': `import { resolve } from 'node:path';
|
|
1135
|
+
import react from '@vitejs/plugin-react';
|
|
1136
|
+
import type { StorybookConfig } from '@storybook/react-vite';
|
|
1137
|
+
|
|
1138
|
+
const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
|
|
1139
|
+
|
|
1140
|
+
const config: StorybookConfig = {
|
|
1141
|
+
stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
|
|
1142
|
+
framework: {
|
|
1143
|
+
name: '@storybook/react-vite',
|
|
1144
|
+
options: {}
|
|
1145
|
+
},
|
|
1146
|
+
core: {
|
|
1147
|
+
disableTelemetry: true
|
|
1148
|
+
},
|
|
1149
|
+
async viteFinal(viteConfig) {
|
|
1150
|
+
const { mergeConfig } = await import('vite');
|
|
1151
|
+
|
|
1152
|
+
return mergeConfig(viteConfig, {
|
|
1153
|
+
plugins: [react()],
|
|
1154
|
+
resolve: {
|
|
1155
|
+
alias: {
|
|
1156
|
+
'@': projectRoot
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
});
|
|
1160
|
+
}
|
|
1161
|
+
};
|
|
1162
|
+
|
|
1163
|
+
export default config;
|
|
1164
|
+
`,
|
|
1165
|
+
'preview.ts': `import type { Preview } from '@storybook/react-vite';
|
|
1166
|
+
|
|
1167
|
+
const preview: Preview = {
|
|
1168
|
+
parameters: {
|
|
1169
|
+
controls: {
|
|
1170
|
+
matchers: {
|
|
1171
|
+
color: /(background|color)$/i,
|
|
1172
|
+
date: /Date$/i
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
};
|
|
1177
|
+
|
|
1178
|
+
export default preview;
|
|
1179
|
+
`
|
|
1180
|
+
});
|
|
1181
|
+
const storybookScripts = (rootFolder)=>{
|
|
1182
|
+
const folder = external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
|
|
1183
|
+
const quote = (value)=>JSON.stringify(value);
|
|
1184
|
+
return {
|
|
1185
|
+
storybook: `storybook dev -p 6006 -c ${quote(`${folder}/.storybook`)}`,
|
|
1186
|
+
'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
|
|
1187
|
+
};
|
|
1188
|
+
};
|
|
1189
|
+
const addStorybook = async ()=>{
|
|
1190
|
+
const config = config_file_ConfigFile.Instance.data;
|
|
1191
|
+
if ((!config.useReact || config.storybookFramework && '@storybook/react-vite' !== config.storybookFramework) && !await (0, prompts_namespaceObject.confirm)({
|
|
1192
|
+
message: 'Configure React scaffolding with @storybook/react-vite?',
|
|
1193
|
+
default: false
|
|
1194
|
+
})) return [];
|
|
1195
|
+
const root = new project_root_ProjectRoot().path;
|
|
1196
|
+
const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
|
|
1197
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1198
|
+
const selected = await addPackageScripts(manifestFile, storybookScripts(config.rootFolder));
|
|
1199
|
+
const folder = new file_system_Folder(root).subitem([
|
|
1200
|
+
config.rootFolder,
|
|
1201
|
+
'presentation',
|
|
1202
|
+
'react',
|
|
1203
|
+
'.storybook'
|
|
1204
|
+
]);
|
|
1205
|
+
for (const [name, content] of Object.entries(storybookFiles(external_node_path_default().relative(folder.path, root).split(external_node_path_default().sep).join('/')))){
|
|
1206
|
+
const file = new file_system_File(external_node_path_default().join(folder.path, name));
|
|
1207
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
1208
|
+
}
|
|
1209
|
+
if (!config.useReact || '@storybook/react-vite' !== config.storybookFramework) config_file_ConfigFile.write({
|
|
1210
|
+
...config,
|
|
1211
|
+
useReact: true,
|
|
1212
|
+
storybookFramework: '@storybook/react-vite'
|
|
1213
|
+
});
|
|
1214
|
+
const buildFolder = external_node_path_default().posix.join(config.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
|
|
1215
|
+
addGitignoreEntry(root, `/${buildFolder}/`);
|
|
1216
|
+
const dependencies = {
|
|
1217
|
+
...manifest.dependencies,
|
|
1218
|
+
...manifest.devDependencies
|
|
1219
|
+
};
|
|
1220
|
+
const missing = [
|
|
1221
|
+
'storybook',
|
|
1222
|
+
'@storybook/react-vite',
|
|
1223
|
+
'vite',
|
|
1224
|
+
'@vitejs/plugin-react'
|
|
1225
|
+
].filter((name)=>!dependencies[name]);
|
|
1226
|
+
const missingReact = [
|
|
1227
|
+
'react',
|
|
1228
|
+
'react-dom'
|
|
1229
|
+
].filter((name)=>!dependencies[name]);
|
|
1230
|
+
return [
|
|
1231
|
+
...missing.length ? [
|
|
1232
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
1233
|
+
] : [],
|
|
1234
|
+
...missingReact.length ? [
|
|
1235
|
+
`npm install ${missingReact.join(' ')}`
|
|
1236
|
+
] : [],
|
|
1237
|
+
...describeScripts(selected, {
|
|
1238
|
+
storybook: 'start Storybook on http://localhost:6006',
|
|
1239
|
+
'build-storybook': `build static Storybook into ${buildFolder}`
|
|
1240
|
+
})
|
|
1241
|
+
];
|
|
1242
|
+
};
|
|
1243
|
+
const integrationFolder = 'specs/integration';
|
|
1244
|
+
const testcontainersScripts = {
|
|
1245
|
+
'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
|
|
1246
|
+
};
|
|
1247
|
+
const testcontainersVitestConfig = (inlineHandlersNext)=>{
|
|
1248
|
+
const server = inlineHandlersNext ? `,
|
|
1249
|
+
server: {
|
|
1250
|
+
deps: {
|
|
1251
|
+
// Imports \`next/headers\` without an extension, which only a bundler can resolve
|
|
1252
|
+
inline: ['@domain-first/handlers-next']
|
|
1253
|
+
}
|
|
1254
|
+
}` : '';
|
|
1255
|
+
return `import { fileURLToPath } from 'node:url';
|
|
1256
|
+
import { defineConfig } from 'vitest/config';
|
|
1257
|
+
|
|
1258
|
+
// Runs specs from this folder against PostgreSQL in a container, see global-setup.ts.
|
|
1259
|
+
export default defineConfig({
|
|
1260
|
+
// Paths below are relative to the project root, not this folder
|
|
1261
|
+
root: fileURLToPath(new URL('../..', import.meta.url)),
|
|
1262
|
+
resolve: {
|
|
1263
|
+
tsconfigPaths: true
|
|
1264
|
+
},
|
|
1265
|
+
test: {
|
|
1266
|
+
include: ['${integrationFolder}/**/*.spec.ts'],
|
|
1267
|
+
// Development implementations work with the real database
|
|
1268
|
+
env: { NODE_ENV: 'development' },
|
|
1269
|
+
globalSetup: ['${integrationFolder}/global-setup.ts'],
|
|
1270
|
+
setupFiles: ['${integrationFolder}/setup-env.ts'],
|
|
1271
|
+
// Pulling the image on the first run takes a while
|
|
1272
|
+
hookTimeout: 120_000${server}
|
|
1273
|
+
}
|
|
1274
|
+
});
|
|
1275
|
+
`;
|
|
1276
|
+
};
|
|
1277
|
+
const testcontainersGlobalSetup = (migrationCommand)=>{
|
|
1278
|
+
const migrations = migrationCommand ? `
|
|
1279
|
+
// dotenv in the Prisma config does not override an already set variable
|
|
1280
|
+
execSync(${JSON.stringify(migrationCommand)}, {
|
|
1281
|
+
cwd: project.config.root,
|
|
1282
|
+
env: { ...process.env, DATABASE_URL: databaseUrl },
|
|
1283
|
+
// On failure the error carries the command's output
|
|
1284
|
+
stdio: 'pipe'
|
|
1285
|
+
});
|
|
1286
|
+
` : `
|
|
1287
|
+
// Apply your migrations to databaseUrl here.
|
|
1288
|
+
`;
|
|
1289
|
+
return `${migrationCommand ? "import { execSync } from 'node:child_process';\n" : ''}import { GenericContainer, Wait } from 'testcontainers';
|
|
1290
|
+
import type { TestProject } from 'vitest/node';
|
|
1291
|
+
|
|
1292
|
+
declare module 'vitest' {
|
|
1293
|
+
export interface ProvidedContext {
|
|
1294
|
+
databaseUrl: string;
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
const POSTGRES_IMAGE = 'postgres:15';
|
|
1299
|
+
const POSTGRES_PORT = 5432;
|
|
1300
|
+
const POSTGRES_USER = 'test';
|
|
1301
|
+
const POSTGRES_PASSWORD = 'test';
|
|
1302
|
+
const POSTGRES_DB = 'test';
|
|
1303
|
+
|
|
1304
|
+
export default async function setup(project: TestProject) {
|
|
1305
|
+
const container = await new GenericContainer(POSTGRES_IMAGE)
|
|
1306
|
+
.withEnvironment({ POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB })
|
|
1307
|
+
.withExposedPorts(POSTGRES_PORT)
|
|
1308
|
+
// During init PostgreSQL listens on a unix socket only and restarts,
|
|
1309
|
+
// so checking over TCP passes once the final server is up
|
|
1310
|
+
.withHealthCheck({
|
|
1311
|
+
test: [
|
|
1312
|
+
'CMD-SHELL',
|
|
1313
|
+
\`pg_isready --host localhost --username \${POSTGRES_USER} --dbname \${POSTGRES_DB}\`
|
|
1314
|
+
],
|
|
1315
|
+
interval: 250,
|
|
1316
|
+
timeout: 1000,
|
|
1317
|
+
retries: 1000
|
|
1318
|
+
})
|
|
1319
|
+
.withWaitStrategy(Wait.forHealthCheck())
|
|
1320
|
+
.withStartupTimeout(120_000)
|
|
1321
|
+
.start();
|
|
1322
|
+
|
|
1323
|
+
const databaseUrl = \`postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@\${container.getHost()}:\${container.getMappedPort(POSTGRES_PORT)}/\${POSTGRES_DB}\`;
|
|
1324
|
+
${migrations}
|
|
1325
|
+
project.provide('databaseUrl', databaseUrl);
|
|
1326
|
+
|
|
1327
|
+
return async () => {
|
|
1328
|
+
await container.stop();
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
`;
|
|
1332
|
+
};
|
|
1333
|
+
const testcontainersSetupEnv = `import 'dotenv/config';
|
|
1334
|
+
import { inject } from 'vitest';
|
|
1335
|
+
|
|
1336
|
+
// Runs before each spec's imports: development implementations get the .env
|
|
1337
|
+
// config, and DATABASE_URL points to the container instead of the one from .env.
|
|
1338
|
+
if (process.env.NODE_ENV !== 'development') {
|
|
1339
|
+
throw new Error(
|
|
1340
|
+
\`Integration specs need NODE_ENV=development to wire development implementations, got "\${process.env.NODE_ENV}"\`
|
|
1341
|
+
);
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
process.env.DATABASE_URL = inject('databaseUrl');
|
|
1345
|
+
`;
|
|
1346
|
+
const testcontainers_exampleSpec = `import { expect, inject, test } from 'vitest';
|
|
1347
|
+
|
|
1348
|
+
test('connects to the database in the container', () => {
|
|
1349
|
+
expect(process.env.DATABASE_URL).toBe(inject('databaseUrl'));
|
|
1350
|
+
});
|
|
1351
|
+
`;
|
|
1352
|
+
const excludeFromUnitTests = (content)=>{
|
|
1353
|
+
const exclude = /(exclude:\s*\[\s*\.\.\.configDefaults\.exclude\b[^\]]*?)(,?)(\s*)\]/;
|
|
1354
|
+
if (!exclude.test(content)) return;
|
|
1355
|
+
const entry = `'${integrationFolder}/**'`;
|
|
1356
|
+
return content.replace(exclude, (_, items, comma, whitespace)=>{
|
|
1357
|
+
const indent = whitespace.includes('\n') ? /\n([ \t]*)[^\n]*$/.exec(items)?.[1] : void 0;
|
|
1358
|
+
const separator = void 0 === indent ? ', ' : `,\n${indent}`;
|
|
1359
|
+
return `${items}${separator}${entry}${comma}${whitespace}]`;
|
|
1360
|
+
}).replace('// Playwright runs end-to-end specs\n', '// Playwright runs end-to-end specs, test:integration runs integration ones\n');
|
|
1361
|
+
};
|
|
1362
|
+
const testcontainers_stageFile = (filePath, content)=>{
|
|
1363
|
+
const file = new file_system_File(filePath);
|
|
1364
|
+
if (!file.exists || file.data !== content) file.data = content;
|
|
1365
|
+
};
|
|
1366
|
+
const addTestcontainers = async ()=>{
|
|
1367
|
+
const config = config_file_ConfigFile.Instance.data;
|
|
1368
|
+
const root = new project_root_ProjectRoot().path;
|
|
1369
|
+
const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
|
|
1370
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1371
|
+
const dependencies = {
|
|
1372
|
+
...manifest.dependencies,
|
|
1373
|
+
...manifest.devDependencies
|
|
1374
|
+
};
|
|
1375
|
+
const selected = await addPackageScripts(manifestFile, testcontainersScripts);
|
|
1376
|
+
const withPrisma = new file_system_File(external_node_path_default().resolve(root, config.rootFolder, 'shared/infrastructure/prisma/prisma.config.ts')).exists;
|
|
1377
|
+
const migrationCommand = withPrisma ? `npx ${prismaScripts(config.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
|
|
1378
|
+
const folder = external_node_path_default().join(root, integrationFolder);
|
|
1379
|
+
testcontainers_stageFile(external_node_path_default().join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
|
|
1380
|
+
testcontainers_stageFile(external_node_path_default().join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
|
|
1381
|
+
testcontainers_stageFile(external_node_path_default().join(folder, 'setup-env.ts'), testcontainersSetupEnv);
|
|
1382
|
+
const example = new file_system_File(external_node_path_default().join(folder, 'database/database.spec.ts'));
|
|
1383
|
+
if (!example.exists) example.data = testcontainers_exampleSpec;
|
|
1384
|
+
const unitConfig = new file_system_File(external_node_path_default().join(root, 'vitest.config.ts'));
|
|
1385
|
+
let excludedFromUnitTests = !unitConfig.exists || unitConfig.data.includes(integrationFolder);
|
|
1386
|
+
if (!excludedFromUnitTests) {
|
|
1387
|
+
const excluded = excludeFromUnitTests(unitConfig.data);
|
|
1388
|
+
if (excluded) {
|
|
1389
|
+
unitConfig.update(excluded);
|
|
1390
|
+
excludedFromUnitTests = true;
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
const missing = [
|
|
1394
|
+
'vitest',
|
|
1395
|
+
'testcontainers',
|
|
1396
|
+
'dotenv'
|
|
1397
|
+
].filter((name)=>!dependencies[name]);
|
|
1398
|
+
return [
|
|
1399
|
+
...missing.length ? [
|
|
1400
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
1401
|
+
] : [],
|
|
1402
|
+
`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.`,
|
|
1403
|
+
...migrationCommand ? [] : [
|
|
1404
|
+
`Apply your migrations in ${integrationFolder}/global-setup.ts.`
|
|
1405
|
+
],
|
|
1406
|
+
...excludedFromUnitTests ? [] : [
|
|
1407
|
+
`Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
|
|
1408
|
+
],
|
|
1409
|
+
'Docker must be running for integration specs.',
|
|
1410
|
+
...describeScripts(selected, {
|
|
1411
|
+
'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
|
|
1412
|
+
})
|
|
1413
|
+
];
|
|
1414
|
+
};
|
|
1415
|
+
const vitestScripts = {
|
|
1416
|
+
test: 'vitest run --reporter=dot --silent=passed-only',
|
|
1417
|
+
'test:coverage': 'vitest run --coverage --reporter=dot --silent=passed-only'
|
|
1418
|
+
};
|
|
1419
|
+
const vitestConfig = (rootFolder, inlineHandlersNext)=>{
|
|
1420
|
+
const folder = (subpath)=>JSON.stringify(external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), subpath));
|
|
1421
|
+
const server = inlineHandlersNext ? `,
|
|
1422
|
+
server: {
|
|
1423
|
+
deps: {
|
|
1424
|
+
// Imports \`next/headers\` without an extension, which only a bundler can resolve
|
|
1425
|
+
inline: ['@domain-first/handlers-next']
|
|
1426
|
+
}
|
|
1427
|
+
}` : '';
|
|
1428
|
+
return `import { configDefaults, defineConfig } from 'vitest/config';
|
|
1429
|
+
|
|
1430
|
+
export default defineConfig({
|
|
1431
|
+
resolve: {
|
|
1432
|
+
tsconfigPaths: true
|
|
1433
|
+
},
|
|
1434
|
+
test: {
|
|
1435
|
+
// Playwright runs end-to-end specs, test:integration runs integration ones
|
|
1436
|
+
exclude: [...configDefaults.exclude, 'specs/e2e/**', 'specs/integration/**'],
|
|
1437
|
+
coverage: {
|
|
1438
|
+
provider: 'v8',
|
|
1439
|
+
include: [${folder('bounded-contexts/**/*.ts')}, ${folder('shared/**/*.ts')}],
|
|
1440
|
+
exclude: [
|
|
1441
|
+
'**/*.spec.ts',
|
|
1442
|
+
${folder('shared/infrastructure/**')},
|
|
1443
|
+
${folder('bounded-contexts/*/infrastructure/**')},
|
|
1444
|
+
${folder('bounded-contexts/*/presentation/rest/**')},
|
|
1445
|
+
${folder('shared/wiring/**')},
|
|
1446
|
+
${folder('bounded-contexts/*/wiring/**')}
|
|
1447
|
+
],
|
|
1448
|
+
reporter: [['text', { skipFull: true }], 'html']
|
|
1449
|
+
}${server}
|
|
1450
|
+
}
|
|
1451
|
+
});
|
|
1452
|
+
`;
|
|
1453
|
+
};
|
|
1454
|
+
const addVitest = async ()=>{
|
|
1455
|
+
const config = config_file_ConfigFile.Instance.data;
|
|
1456
|
+
if (config.testingLibrary && 'vitest' !== config.testingLibrary && !await (0, prompts_namespaceObject.confirm)({
|
|
1457
|
+
message: `Replace testing library "${config.testingLibrary}" with vitest for generated tests?`,
|
|
1458
|
+
default: false
|
|
1459
|
+
})) return [];
|
|
1460
|
+
const root = new project_root_ProjectRoot().path;
|
|
1461
|
+
const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
|
|
1462
|
+
const manifest = JSON.parse(manifestFile.data);
|
|
1463
|
+
const dependencies = {
|
|
1464
|
+
...manifest.dependencies,
|
|
1465
|
+
...manifest.devDependencies
|
|
1466
|
+
};
|
|
1467
|
+
const selected = await addPackageScripts(manifestFile, vitestScripts);
|
|
1468
|
+
const configFile = new file_system_File(external_node_path_default().join(root, 'vitest.config.ts'));
|
|
1469
|
+
const content = vitestConfig(config.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
|
|
1470
|
+
if (!configFile.exists || configFile.data !== content) configFile.data = content;
|
|
1471
|
+
if ('vitest' !== config.testingLibrary) config_file_ConfigFile.write({
|
|
1472
|
+
...config,
|
|
1473
|
+
testingLibrary: 'vitest'
|
|
1474
|
+
});
|
|
1475
|
+
addGitignoreEntry(root, '/coverage/');
|
|
1476
|
+
const missing = [
|
|
1477
|
+
'vitest',
|
|
1478
|
+
'@vitest/coverage-v8'
|
|
1479
|
+
].filter((name)=>!dependencies[name]);
|
|
1480
|
+
return [
|
|
1481
|
+
...missing.length ? [
|
|
1482
|
+
`npm install --save-dev ${missing.join(' ')}`
|
|
1483
|
+
] : [],
|
|
1484
|
+
...describeScripts(selected, {
|
|
1485
|
+
test: 'run unit tests',
|
|
1486
|
+
'test:coverage': 'run unit tests with a V8 coverage report in coverage/'
|
|
1487
|
+
})
|
|
1488
|
+
];
|
|
1489
|
+
};
|
|
1490
|
+
const installCommand = /^\s*npm (?:i|install)((?:\s+(?:--save-dev|-D))?)\s+(.+)$/;
|
|
1491
|
+
const mergeInstallCommands = (commands)=>{
|
|
1492
|
+
const runtime = new Set();
|
|
1493
|
+
const development = new Set();
|
|
1494
|
+
const rest = [];
|
|
1495
|
+
for (const command of commands){
|
|
1496
|
+
const match = installCommand.exec(command);
|
|
1497
|
+
if (!match) {
|
|
1498
|
+
rest.push(command);
|
|
1499
|
+
continue;
|
|
1500
|
+
}
|
|
1501
|
+
for (const name of match[2].trim().split(/\s+/))(match[1] ? development : runtime).add(name);
|
|
1502
|
+
}
|
|
1503
|
+
const devOnly = [
|
|
1504
|
+
...development
|
|
1505
|
+
].filter((name)=>!runtime.has(name));
|
|
1506
|
+
return [
|
|
1507
|
+
...runtime.size ? [
|
|
1508
|
+
`npm install ${[
|
|
1509
|
+
...runtime
|
|
1510
|
+
].join(' ')}`
|
|
1511
|
+
] : [],
|
|
1512
|
+
...devOnly.length ? [
|
|
1513
|
+
`npm install --save-dev ${devOnly.join(' ')}`
|
|
1514
|
+
] : [],
|
|
1515
|
+
...rest
|
|
1516
|
+
];
|
|
1517
|
+
};
|
|
1518
|
+
const printNextSteps = (nextSteps)=>{
|
|
1519
|
+
const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
|
|
1520
|
+
const commands = mergeInstallCommands(nextSteps.filter(isCommand));
|
|
1521
|
+
const notes = nextSteps.filter((line)=>!isCommand(line));
|
|
1522
|
+
const sections = [];
|
|
1523
|
+
if (commands.length) sections.push([
|
|
1524
|
+
'Run these commands to install the required dependencies:',
|
|
1525
|
+
...commands.map((line)=>(0, external_node_util_namespaceObject.styleText)([
|
|
1526
|
+
'bold',
|
|
1527
|
+
'cyan'
|
|
1528
|
+
], line))
|
|
1529
|
+
].join('\n'));
|
|
1530
|
+
if (notes.length) sections.push([
|
|
1531
|
+
'Additional information:',
|
|
1532
|
+
...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + (0, external_node_util_namespaceObject.styleText)([
|
|
1533
|
+
'bold',
|
|
1534
|
+
'cyan'
|
|
1535
|
+
], path)))
|
|
1536
|
+
].join('\n'));
|
|
1537
|
+
if (sections.length) console.log(sections.join('\n\n'));
|
|
1538
|
+
};
|
|
1539
|
+
const savePendingChanges = async ()=>{
|
|
1540
|
+
const overwrittenFiles = filesToOverwrite();
|
|
1541
|
+
if (overwrittenFiles.length) {
|
|
1542
|
+
const root = new project_root_ProjectRoot().path;
|
|
1543
|
+
console.log('These files already exist and will be overwritten:');
|
|
1544
|
+
for (const filePath of overwrittenFiles)console.log(` ${external_node_path_default().relative(root, filePath)}`);
|
|
1545
|
+
const overwrite = await (0, prompts_namespaceObject.confirm)({
|
|
1546
|
+
message: 'Overwrite them?',
|
|
1547
|
+
default: false
|
|
1548
|
+
});
|
|
1549
|
+
if (!overwrite) {
|
|
1550
|
+
file_system_discardPendingChanges();
|
|
1551
|
+
console.log('Cancelled: nothing was written.');
|
|
1552
|
+
return false;
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
writePendingChanges();
|
|
1556
|
+
return true;
|
|
1557
|
+
};
|
|
1558
|
+
const withHandlersRest = ()=>config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers-rest');
|
|
1559
|
+
const created = (...segments)=>new file_system_File(external_node_path_default().join(new project_root_ProjectRoot().path, ...segments)).exists;
|
|
1560
|
+
const createdInRoot = (...segments)=>created(config_file_ConfigFile.Instance.data.rootFolder, ...segments);
|
|
1561
|
+
const integrations = [
|
|
1562
|
+
{
|
|
1563
|
+
name: 'Storybook (React + Vite)',
|
|
1564
|
+
group: 'frontend',
|
|
1565
|
+
run: addStorybook,
|
|
1566
|
+
applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
|
|
1567
|
+
},
|
|
1568
|
+
{
|
|
1569
|
+
name: 'Prisma 8 (PostgreSQL, RC)',
|
|
1570
|
+
group: 'backend',
|
|
1571
|
+
run: addPrisma,
|
|
1572
|
+
applied: ()=>createdInRoot('shared/infrastructure/prisma/prisma.config.ts')
|
|
1573
|
+
},
|
|
1574
|
+
{
|
|
1575
|
+
name: 'Vitest',
|
|
1576
|
+
group: 'backend',
|
|
1577
|
+
run: addVitest,
|
|
1578
|
+
applied: ()=>created('vitest.config.ts')
|
|
1579
|
+
},
|
|
1580
|
+
{
|
|
1581
|
+
name: 'Playwright',
|
|
1582
|
+
group: 'frontend',
|
|
1583
|
+
run: addPlaywright,
|
|
1584
|
+
applied: ()=>created('playwright.config.ts')
|
|
1585
|
+
},
|
|
1586
|
+
{
|
|
1587
|
+
name: 'Integration tests (Testcontainers, PostgreSQL)',
|
|
1588
|
+
group: 'backend',
|
|
1589
|
+
run: addTestcontainers,
|
|
1590
|
+
applied: ()=>created('specs/integration/vitest.config.ts')
|
|
1591
|
+
},
|
|
1592
|
+
{
|
|
1593
|
+
name: 'OpenAPI',
|
|
1594
|
+
group: 'backend',
|
|
1595
|
+
run: addOpenapi,
|
|
1596
|
+
available: ()=>withHandlersRest(),
|
|
1597
|
+
applied: ()=>created(openapiScriptPath)
|
|
1598
|
+
},
|
|
1599
|
+
{
|
|
1600
|
+
name: 'Orval (API client)',
|
|
1601
|
+
group: 'frontend',
|
|
1602
|
+
run: addOrval,
|
|
1603
|
+
available: ()=>withHandlersRest(),
|
|
1604
|
+
applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
|
|
1605
|
+
},
|
|
1606
|
+
{
|
|
1607
|
+
name: 'Missing domain-first packages',
|
|
1608
|
+
group: 'backend',
|
|
1609
|
+
run: missingDomainFirstPackages,
|
|
1610
|
+
applied: ()=>!missingDomainFirstPackages().length
|
|
1611
|
+
}
|
|
1612
|
+
];
|
|
1613
|
+
const addIntegration = async ()=>{
|
|
1614
|
+
const available = integrations.filter(({ available })=>available?.() ?? true).map((value)=>({
|
|
1615
|
+
value,
|
|
1616
|
+
applied: value.applied()
|
|
1617
|
+
}));
|
|
1618
|
+
const section = (title, applied)=>{
|
|
1619
|
+
const items = [
|
|
1620
|
+
'backend',
|
|
1621
|
+
'frontend'
|
|
1622
|
+
].flatMap((group)=>available.filter((item)=>item.applied === applied && item.value.group === group));
|
|
1623
|
+
return items.length ? [
|
|
1624
|
+
new prompts_namespaceObject.Separator(title),
|
|
1625
|
+
...items.map(({ value })=>({
|
|
1626
|
+
name: `${value.name} · ${value.group}`,
|
|
1627
|
+
value
|
|
1628
|
+
}))
|
|
1629
|
+
] : [];
|
|
1630
|
+
};
|
|
1631
|
+
const choices = [
|
|
1632
|
+
...section('New integrations', false),
|
|
1633
|
+
...section('Already applied (select to reapply)', true)
|
|
1634
|
+
];
|
|
1635
|
+
const selected = await (0, prompts_namespaceObject.checkbox)({
|
|
1636
|
+
message: 'Integrations:',
|
|
1637
|
+
choices,
|
|
1638
|
+
pageSize: choices.length
|
|
1639
|
+
});
|
|
1640
|
+
const nextSteps = [];
|
|
1641
|
+
for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
|
|
1642
|
+
if (await savePendingChanges()) printNextSteps(nextSteps);
|
|
1643
|
+
};
|
|
1644
|
+
new Set([
|
|
1645
|
+
'node_modules',
|
|
1646
|
+
'.git',
|
|
1647
|
+
'.next',
|
|
1648
|
+
'dist',
|
|
1649
|
+
'build',
|
|
1650
|
+
'out',
|
|
1651
|
+
'coverage',
|
|
1652
|
+
'storybook-static'
|
|
1653
|
+
]);
|
|
1654
|
+
const help = `Usage: df-integration
|
|
1655
|
+
|
|
1656
|
+
Adds integrations to a Domain-First project: Storybook, Prisma, Vitest,
|
|
1657
|
+
Playwright, integration tests, OpenAPI, Orval and missing domain-first
|
|
1658
|
+
packages. Several can be selected at once. Changes project files and prints
|
|
1659
|
+
the install commands; nothing is installed or run.
|
|
1660
|
+
|
|
1661
|
+
Options:
|
|
1662
|
+
-h, --help show this help`;
|
|
1663
|
+
const { values } = (0, external_node_util_namespaceObject.parseArgs)({
|
|
1664
|
+
options: {
|
|
1665
|
+
help: {
|
|
1666
|
+
type: 'boolean',
|
|
1667
|
+
short: 'h',
|
|
1668
|
+
default: false
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
});
|
|
1672
|
+
if (values.help) {
|
|
1673
|
+
console.log(help);
|
|
1674
|
+
process.exit(0);
|
|
1675
|
+
}
|
|
1676
|
+
if (!config_file_ConfigFile.exists) {
|
|
1677
|
+
console.log('No domain-first.project-structure.config.json found: run df-scaffold first to initialize the project.');
|
|
1678
|
+
process.exit(1);
|
|
1679
|
+
}
|
|
1680
|
+
addIntegration();
|
|
1681
|
+
for(var __rspack_i in __webpack_exports__)exports[__rspack_i] = __webpack_exports__[__rspack_i];
|
|
1682
|
+
Object.defineProperty(exports, '__esModule', {
|
|
1683
|
+
value: true
|
|
1684
|
+
});
|