@domain-first/project-structure 2.16.1 → 2.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +206 -27
- package/dist/index.js +206 -27
- package/dist/integrations/openapi-extractor.d.ts +2 -0
- package/dist/integrations/openapi.d.ts +1 -6
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -254,6 +254,159 @@ const missingDomainFirstPackages = ()=>{
|
|
|
254
254
|
`npm i ${missing.join(' ')}`
|
|
255
255
|
] : [];
|
|
256
256
|
};
|
|
257
|
+
const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
|
|
258
|
+
const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
|
|
259
|
+
const openapiExtractor = (rootFolder)=>`import path from 'node:path';
|
|
260
|
+
import {
|
|
261
|
+
type DocNode,
|
|
262
|
+
DocPlainText,
|
|
263
|
+
TSDocConfiguration,
|
|
264
|
+
TSDocParser,
|
|
265
|
+
TSDocTagDefinition,
|
|
266
|
+
TSDocTagSyntaxKind
|
|
267
|
+
} from '@microsoft/tsdoc';
|
|
268
|
+
import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
|
|
269
|
+
|
|
270
|
+
type BlockTag = \`@\${string}\`;
|
|
271
|
+
|
|
272
|
+
type OpenApiDataTags = {
|
|
273
|
+
/** Omit to take the summary from the comment text before the first tag. */
|
|
274
|
+
summary?: BlockTag;
|
|
275
|
+
description?: BlockTag;
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
type OpenApiData = Partial<{
|
|
279
|
+
summary: string;
|
|
280
|
+
description: string;
|
|
281
|
+
operationId: string;
|
|
282
|
+
}>;
|
|
283
|
+
|
|
284
|
+
const project = new Project({
|
|
285
|
+
tsConfigFilePath: 'tsconfig.json'
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
const getText = (node: DocNode): string =>
|
|
289
|
+
node
|
|
290
|
+
.getChildNodes()
|
|
291
|
+
.map((child) => {
|
|
292
|
+
if (child instanceof DocPlainText) {
|
|
293
|
+
return child.text;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return getText(child);
|
|
297
|
+
})
|
|
298
|
+
.join('');
|
|
299
|
+
|
|
300
|
+
const getRawCommentText = (comment: string): string =>
|
|
301
|
+
comment
|
|
302
|
+
.replace(/^\\/\\*\\*/, '')
|
|
303
|
+
.replace(/\\*\\/$/, '')
|
|
304
|
+
.split(/\\r?\\n/)
|
|
305
|
+
.map((line) => line.replace(/^\\s*\\*\\s?/, ''))
|
|
306
|
+
.join('\\n');
|
|
307
|
+
|
|
308
|
+
// TSDoc treats an unknown tag as summary content, so every block tag of the
|
|
309
|
+
// comment has to be registered for the summary section to end before it.
|
|
310
|
+
const parseSummary = (comment: string): string | undefined => {
|
|
311
|
+
const configuration = new TSDocConfiguration();
|
|
312
|
+
const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
|
|
313
|
+
|
|
314
|
+
for (const [, tagName] of tagNames) {
|
|
315
|
+
if (!configuration.tryGetTagDefinition(tagName)) {
|
|
316
|
+
configuration.addTagDefinition(
|
|
317
|
+
new TSDocTagDefinition({
|
|
318
|
+
tagName,
|
|
319
|
+
syntaxKind: TSDocTagSyntaxKind.BlockTag
|
|
320
|
+
})
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const { docComment } = new TSDocParser(configuration).parseString(comment);
|
|
326
|
+
|
|
327
|
+
return getText(docComment.summarySection).trim() || undefined;
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
// Parsed by hand rather than through TSDoc, which drops the line breaks.
|
|
331
|
+
const getTagText = (comment: string, tag: BlockTag): string | undefined => {
|
|
332
|
+
const tagMatch = getRawCommentText(comment).match(
|
|
333
|
+
new RegExp(
|
|
334
|
+
\`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
|
|
335
|
+
)
|
|
336
|
+
);
|
|
337
|
+
|
|
338
|
+
return tagMatch?.[1].trim() || undefined;
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
// Endpoints pass their logic as the generator's first argument
|
|
342
|
+
// (\`this.endpointGenerator(this.handler.handle, ...)\`), while other injected
|
|
343
|
+
// queries only serve as helpers, e.g. guest checks.
|
|
344
|
+
const findHandlerClass = (endpointFile: SourceFile) =>
|
|
345
|
+
endpointFile
|
|
346
|
+
.getDescendantsOfKind(SyntaxKind.CallExpression)
|
|
347
|
+
.map((call) => call.getArguments()[0])
|
|
348
|
+
.filter(Node.isPropertyAccessExpression)
|
|
349
|
+
.find((argument) => argument.getName() === 'handle')
|
|
350
|
+
?.getExpression()
|
|
351
|
+
.getType()
|
|
352
|
+
.getSymbol()
|
|
353
|
+
?.getDeclarations()
|
|
354
|
+
.find(Node.isClassDeclaration);
|
|
355
|
+
|
|
356
|
+
export const createOpenApiDataFromEndpointLogicExtractor = ({
|
|
357
|
+
summary: summaryTag,
|
|
358
|
+
description: descriptionTag = '@description'
|
|
359
|
+
}: OpenApiDataTags = {}) => {
|
|
360
|
+
return (routeMetadata: {
|
|
361
|
+
method: string;
|
|
362
|
+
path: string[];
|
|
363
|
+
}): OpenApiData | undefined => {
|
|
364
|
+
try {
|
|
365
|
+
const [currentBoundedContext, controller, ...relativePath] =
|
|
366
|
+
routeMetadata.path;
|
|
367
|
+
|
|
368
|
+
if (!currentBoundedContext || !controller) {
|
|
369
|
+
return undefined;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const endpointFile = project.getSourceFile(
|
|
373
|
+
path.join(
|
|
374
|
+
${rootFolderSegments(rootFolder)}'bounded-contexts',
|
|
375
|
+
currentBoundedContext,
|
|
376
|
+
'presentation',
|
|
377
|
+
'rest',
|
|
378
|
+
controller,
|
|
379
|
+
...relativePath,
|
|
380
|
+
\`\${routeMetadata.method.toUpperCase()}.ts\`
|
|
381
|
+
)
|
|
382
|
+
);
|
|
383
|
+
|
|
384
|
+
if (!endpointFile) {
|
|
385
|
+
return undefined;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const declaration = findHandlerClass(endpointFile);
|
|
389
|
+
const operationId = declaration?.getName();
|
|
390
|
+
const comment = declaration?.getJsDocs().at(-1)?.getText();
|
|
391
|
+
|
|
392
|
+
if (!comment) {
|
|
393
|
+
return { operationId };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
return {
|
|
397
|
+
summary: summaryTag
|
|
398
|
+
? getTagText(comment, summaryTag)
|
|
399
|
+
: parseSummary(comment),
|
|
400
|
+
description: getTagText(comment, descriptionTag),
|
|
401
|
+
operationId
|
|
402
|
+
};
|
|
403
|
+
} catch (e: unknown) {
|
|
404
|
+
console.error(e);
|
|
405
|
+
return undefined;
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
};
|
|
409
|
+
`;
|
|
257
410
|
const addPackageScripts = async (file, additions)=>{
|
|
258
411
|
const original = file.data;
|
|
259
412
|
const manifest = JSON.parse(original);
|
|
@@ -291,6 +444,10 @@ const addPackageScripts = async (file, additions)=>{
|
|
|
291
444
|
const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
|
|
292
445
|
const openapiScriptPath = "scripts/generate-openapi.ts";
|
|
293
446
|
const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
|
|
447
|
+
const extractorPackages = [
|
|
448
|
+
'ts-morph',
|
|
449
|
+
'@microsoft/tsdoc'
|
|
450
|
+
];
|
|
294
451
|
const openapiScripts = {
|
|
295
452
|
openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
|
|
296
453
|
};
|
|
@@ -302,33 +459,36 @@ const apiTitle = (packageName)=>{
|
|
|
302
459
|
'API'
|
|
303
460
|
].join(' ');
|
|
304
461
|
};
|
|
305
|
-
const openapiGenerator = (rootFolder, title, routePrefix, outputPath)=>{
|
|
462
|
+
const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
|
|
306
463
|
const restFolder = external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
|
|
307
464
|
const restImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(openapiScriptPath), restFolder);
|
|
308
465
|
const prefixSegments = splitPath(routePrefix);
|
|
309
466
|
const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
|
|
467
|
+
const extractorImport = `./${external_node_path_default().posix.relative(external_node_path_default().posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
|
|
468
|
+
const handlers = withExtractor ? `
|
|
469
|
+
const extractOpenApiDataFromEndpointLogic =
|
|
470
|
+
createOpenApiDataFromEndpointLogicExtractor();
|
|
471
|
+
|
|
472
|
+
const handlers = restHandlers.map((x) => ({
|
|
473
|
+
...x,
|
|
474
|
+
metadata: {
|
|
475
|
+
...x.metadata,
|
|
476
|
+
openApiMetadata: {
|
|
477
|
+
...extractOpenApiDataFromEndpointLogic(x.metadata.route),
|
|
478
|
+
...(x.metadata.openApiMetadata ?? {})
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}));
|
|
482
|
+
` : '';
|
|
310
483
|
return `import { generateOpenAPI } from '@domain-first/handlers-rest';
|
|
311
|
-
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}'
|
|
312
|
-
|
|
313
|
-
generateOpenAPI(restHandlers, {
|
|
484
|
+
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
|
|
485
|
+
${handlers}
|
|
486
|
+
generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
|
|
314
487
|
document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
|
|
315
488
|
outputFile: { path: '${outputPath}' }
|
|
316
489
|
});
|
|
317
490
|
`;
|
|
318
491
|
};
|
|
319
|
-
const minimalHandlersRest = [
|
|
320
|
-
7,
|
|
321
|
-
0,
|
|
322
|
-
2
|
|
323
|
-
];
|
|
324
|
-
const parseVersion = (value)=>String(value ?? '').match(/(\d+)\.(\d+)\.(\d+)/)?.slice(1).map(Number);
|
|
325
|
-
const handlersRestUpToDate = (root, declared)=>{
|
|
326
|
-
const installed = new File(external_node_path_default().join(root, 'node_modules/@domain-first/handlers-rest/package.json'));
|
|
327
|
-
const version = parseVersion(installed.exists ? JSON.parse(installed.data).version : declared);
|
|
328
|
-
if (!version) return false;
|
|
329
|
-
for (const [index, part] of minimalHandlersRest.entries())if (version[index] !== part) return version[index] > part;
|
|
330
|
-
return true;
|
|
331
|
-
};
|
|
332
492
|
const addOpenapi = async ()=>{
|
|
333
493
|
const { rootFolder } = ConfigFile.Instance.data;
|
|
334
494
|
const root = new ProjectRoot().path;
|
|
@@ -347,18 +507,31 @@ const addOpenapi = async ()=>{
|
|
|
347
507
|
default: defaultOpenapiPath(Boolean(dependencies.next)),
|
|
348
508
|
validate: (value)=>splitPath(value).length ? true : 'Path is required'
|
|
349
509
|
});
|
|
510
|
+
const withExtractor = await (0, prompts_namespaceObject.confirm)({
|
|
511
|
+
message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
|
|
512
|
+
default: true
|
|
513
|
+
});
|
|
350
514
|
const selected = await addPackageScripts(manifestFile, openapiScripts);
|
|
515
|
+
if (withExtractor) {
|
|
516
|
+
const extractorFile = new File(external_node_path_default().join(root, openapiExtractorPath));
|
|
517
|
+
const extractor = openapiExtractor(rootFolder);
|
|
518
|
+
if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
|
|
519
|
+
}
|
|
351
520
|
const generatorFile = new File(external_node_path_default().join(root, openapiScriptPath));
|
|
352
|
-
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'));
|
|
521
|
+
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
|
|
353
522
|
if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
|
|
354
523
|
const hasRestHandlers = new File(external_node_path_default().join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
|
|
524
|
+
const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
|
|
355
525
|
return [
|
|
356
|
-
...
|
|
357
|
-
|
|
526
|
+
...dependencies['@domain-first/handlers-rest'] ? [] : [
|
|
527
|
+
'npm install @domain-first/handlers-rest'
|
|
358
528
|
],
|
|
359
529
|
...dependencies.tsx ? [] : [
|
|
360
530
|
'npm install --save-dev tsx'
|
|
361
531
|
],
|
|
532
|
+
...missingExtractorPackages.length ? [
|
|
533
|
+
`npm install --save-dev ${missingExtractorPackages.join(' ')}`
|
|
534
|
+
] : [],
|
|
362
535
|
...describeScripts(selected, {
|
|
363
536
|
openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
|
|
364
537
|
}),
|
|
@@ -2483,12 +2656,18 @@ export const restHandlers = restWires.map(x => x().handle)
|
|
|
2483
2656
|
const routeSegments = (await (0, prompts_namespaceObject.input)({
|
|
2484
2657
|
message: 'Relative path (split by "/"):'
|
|
2485
2658
|
})).split('/').filter((x)=>!!x);
|
|
2659
|
+
const pathParameterAsName = (segment)=>segment.startsWith(':') ? `_${segment.slice(1)}_` : segment;
|
|
2486
2660
|
const controllerFolder = restPresentationFolder.subitem([
|
|
2487
2661
|
controller
|
|
2488
2662
|
]);
|
|
2489
|
-
const endpointFolder = controllerFolder.subitem(routeSegments);
|
|
2490
|
-
const nameBase = `${controller}-${routeSegments.length ? `${routeSegments.join('-')}-` : ''}${method}-endpoint`;
|
|
2491
|
-
const
|
|
2663
|
+
const endpointFolder = controllerFolder.subitem(routeSegments.map(pathParameterAsName));
|
|
2664
|
+
const nameBase = `${controller}-${routeSegments.length ? `${routeSegments.map(pathParameterAsName).join('-')}-` : ''}${method}-endpoint`;
|
|
2665
|
+
const endpointClassName = [
|
|
2666
|
+
controller,
|
|
2667
|
+
...routeSegments,
|
|
2668
|
+
method,
|
|
2669
|
+
'endpoint'
|
|
2670
|
+
].map((segment)=>segment.startsWith(':') ? pathParameterAsName(segment) : new UnknownFormatNaming(segment).ClassName).join('');
|
|
2492
2671
|
const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
2493
2672
|
const { endpointGenerator, handler } = withWiring ? await promptEndpointDependencies(boundedContextFolder) : {
|
|
2494
2673
|
endpointGenerator: void 0,
|
|
@@ -2499,7 +2678,7 @@ export const restHandlers = restWires.map(x => x().handle)
|
|
|
2499
2678
|
${endpointGenerator ? `import type { ${endpointGenerator.typeName} } from '${relativeImport(endpointFile, endpointGenerator.typeFile)}'` : "import { EndpointGenerator } from '@domain-first/handlers-rest'"}${handler ? `
|
|
2500
2679
|
import type { ${handler.typeName} } from '${relativeImport(endpointFile, handler.typeFile)}'` : ''}
|
|
2501
2680
|
|
|
2502
|
-
export class ${
|
|
2681
|
+
export class ${endpointClassName} {
|
|
2503
2682
|
constructor(
|
|
2504
2683
|
private readonly endpointGenerator: ${endpointGenerator?.typeName ?? 'EndpointGenerator'},
|
|
2505
2684
|
private readonly handler: ${handler?.typeName ?? 'never'}
|
|
@@ -2529,11 +2708,11 @@ export class ${endpointNaming.ClassName} {
|
|
|
2529
2708
|
].filter((x)=>!!x) : [];
|
|
2530
2709
|
wiringFolder.createFile(`${wireNaming.fileName}.ts`, `
|
|
2531
2710
|
import { wireClass } from '@domain-first/wire'
|
|
2532
|
-
import { ${
|
|
2711
|
+
import { ${endpointClassName} } from '${relativeImport(wireFile, endpointFile)}'
|
|
2533
2712
|
${dependencies.map((x)=>`import { ${x.wireName} } from '${relativeImport(wireFile, x.wireFile)}'`).join('\n')}
|
|
2534
2713
|
|
|
2535
|
-
export const wire${
|
|
2536
|
-
${
|
|
2714
|
+
export const wire${endpointClassName} = wireClass(
|
|
2715
|
+
${endpointClassName},
|
|
2537
2716
|
[${dependencies.map((x)=>x.wireName).join(', ')}]
|
|
2538
2717
|
)
|
|
2539
2718
|
`.trim());
|
package/dist/index.js
CHANGED
|
@@ -224,6 +224,159 @@ const missingDomainFirstPackages = ()=>{
|
|
|
224
224
|
`npm i ${missing.join(' ')}`
|
|
225
225
|
] : [];
|
|
226
226
|
};
|
|
227
|
+
const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
|
|
228
|
+
const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
|
|
229
|
+
const openapiExtractor = (rootFolder)=>`import path from 'node:path';
|
|
230
|
+
import {
|
|
231
|
+
type DocNode,
|
|
232
|
+
DocPlainText,
|
|
233
|
+
TSDocConfiguration,
|
|
234
|
+
TSDocParser,
|
|
235
|
+
TSDocTagDefinition,
|
|
236
|
+
TSDocTagSyntaxKind
|
|
237
|
+
} from '@microsoft/tsdoc';
|
|
238
|
+
import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';
|
|
239
|
+
|
|
240
|
+
type BlockTag = \`@\${string}\`;
|
|
241
|
+
|
|
242
|
+
type OpenApiDataTags = {
|
|
243
|
+
/** Omit to take the summary from the comment text before the first tag. */
|
|
244
|
+
summary?: BlockTag;
|
|
245
|
+
description?: BlockTag;
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
type OpenApiData = Partial<{
|
|
249
|
+
summary: string;
|
|
250
|
+
description: string;
|
|
251
|
+
operationId: string;
|
|
252
|
+
}>;
|
|
253
|
+
|
|
254
|
+
const project = new Project({
|
|
255
|
+
tsConfigFilePath: 'tsconfig.json'
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
const getText = (node: DocNode): string =>
|
|
259
|
+
node
|
|
260
|
+
.getChildNodes()
|
|
261
|
+
.map((child) => {
|
|
262
|
+
if (child instanceof DocPlainText) {
|
|
263
|
+
return child.text;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return getText(child);
|
|
267
|
+
})
|
|
268
|
+
.join('');
|
|
269
|
+
|
|
270
|
+
const getRawCommentText = (comment: string): string =>
|
|
271
|
+
comment
|
|
272
|
+
.replace(/^\\/\\*\\*/, '')
|
|
273
|
+
.replace(/\\*\\/$/, '')
|
|
274
|
+
.split(/\\r?\\n/)
|
|
275
|
+
.map((line) => line.replace(/^\\s*\\*\\s?/, ''))
|
|
276
|
+
.join('\\n');
|
|
277
|
+
|
|
278
|
+
// TSDoc treats an unknown tag as summary content, so every block tag of the
|
|
279
|
+
// comment has to be registered for the summary section to end before it.
|
|
280
|
+
const parseSummary = (comment: string): string | undefined => {
|
|
281
|
+
const configuration = new TSDocConfiguration();
|
|
282
|
+
const tagNames = getRawCommentText(comment).matchAll(/(?:^|\\n)\\s*(@\\w+)/g);
|
|
283
|
+
|
|
284
|
+
for (const [, tagName] of tagNames) {
|
|
285
|
+
if (!configuration.tryGetTagDefinition(tagName)) {
|
|
286
|
+
configuration.addTagDefinition(
|
|
287
|
+
new TSDocTagDefinition({
|
|
288
|
+
tagName,
|
|
289
|
+
syntaxKind: TSDocTagSyntaxKind.BlockTag
|
|
290
|
+
})
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const { docComment } = new TSDocParser(configuration).parseString(comment);
|
|
296
|
+
|
|
297
|
+
return getText(docComment.summarySection).trim() || undefined;
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
// Parsed by hand rather than through TSDoc, which drops the line breaks.
|
|
301
|
+
const getTagText = (comment: string, tag: BlockTag): string | undefined => {
|
|
302
|
+
const tagMatch = getRawCommentText(comment).match(
|
|
303
|
+
new RegExp(
|
|
304
|
+
\`(?:^|\\\\n)\\\\s*\${tag}(?:[ \\\\t]*\\\\n|[ \\\\t]+)([\\\\s\\\\S]*?)(?=\\\\n\\\\s*@\\\\w+|\\\\s*$)\`
|
|
305
|
+
)
|
|
306
|
+
);
|
|
307
|
+
|
|
308
|
+
return tagMatch?.[1].trim() || undefined;
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
// Endpoints pass their logic as the generator's first argument
|
|
312
|
+
// (\`this.endpointGenerator(this.handler.handle, ...)\`), while other injected
|
|
313
|
+
// queries only serve as helpers, e.g. guest checks.
|
|
314
|
+
const findHandlerClass = (endpointFile: SourceFile) =>
|
|
315
|
+
endpointFile
|
|
316
|
+
.getDescendantsOfKind(SyntaxKind.CallExpression)
|
|
317
|
+
.map((call) => call.getArguments()[0])
|
|
318
|
+
.filter(Node.isPropertyAccessExpression)
|
|
319
|
+
.find((argument) => argument.getName() === 'handle')
|
|
320
|
+
?.getExpression()
|
|
321
|
+
.getType()
|
|
322
|
+
.getSymbol()
|
|
323
|
+
?.getDeclarations()
|
|
324
|
+
.find(Node.isClassDeclaration);
|
|
325
|
+
|
|
326
|
+
export const createOpenApiDataFromEndpointLogicExtractor = ({
|
|
327
|
+
summary: summaryTag,
|
|
328
|
+
description: descriptionTag = '@description'
|
|
329
|
+
}: OpenApiDataTags = {}) => {
|
|
330
|
+
return (routeMetadata: {
|
|
331
|
+
method: string;
|
|
332
|
+
path: string[];
|
|
333
|
+
}): OpenApiData | undefined => {
|
|
334
|
+
try {
|
|
335
|
+
const [currentBoundedContext, controller, ...relativePath] =
|
|
336
|
+
routeMetadata.path;
|
|
337
|
+
|
|
338
|
+
if (!currentBoundedContext || !controller) {
|
|
339
|
+
return undefined;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const endpointFile = project.getSourceFile(
|
|
343
|
+
path.join(
|
|
344
|
+
${rootFolderSegments(rootFolder)}'bounded-contexts',
|
|
345
|
+
currentBoundedContext,
|
|
346
|
+
'presentation',
|
|
347
|
+
'rest',
|
|
348
|
+
controller,
|
|
349
|
+
...relativePath,
|
|
350
|
+
\`\${routeMetadata.method.toUpperCase()}.ts\`
|
|
351
|
+
)
|
|
352
|
+
);
|
|
353
|
+
|
|
354
|
+
if (!endpointFile) {
|
|
355
|
+
return undefined;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const declaration = findHandlerClass(endpointFile);
|
|
359
|
+
const operationId = declaration?.getName();
|
|
360
|
+
const comment = declaration?.getJsDocs().at(-1)?.getText();
|
|
361
|
+
|
|
362
|
+
if (!comment) {
|
|
363
|
+
return { operationId };
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
return {
|
|
367
|
+
summary: summaryTag
|
|
368
|
+
? getTagText(comment, summaryTag)
|
|
369
|
+
: parseSummary(comment),
|
|
370
|
+
description: getTagText(comment, descriptionTag),
|
|
371
|
+
operationId
|
|
372
|
+
};
|
|
373
|
+
} catch (e: unknown) {
|
|
374
|
+
console.error(e);
|
|
375
|
+
return undefined;
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
};
|
|
379
|
+
`;
|
|
227
380
|
const addPackageScripts = async (file, additions)=>{
|
|
228
381
|
const original = file.data;
|
|
229
382
|
const manifest = JSON.parse(original);
|
|
@@ -261,6 +414,10 @@ const addPackageScripts = async (file, additions)=>{
|
|
|
261
414
|
const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
|
|
262
415
|
const openapiScriptPath = "scripts/generate-openapi.ts";
|
|
263
416
|
const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
|
|
417
|
+
const extractorPackages = [
|
|
418
|
+
'ts-morph',
|
|
419
|
+
'@microsoft/tsdoc'
|
|
420
|
+
];
|
|
264
421
|
const openapiScripts = {
|
|
265
422
|
openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
|
|
266
423
|
};
|
|
@@ -272,33 +429,36 @@ const apiTitle = (packageName)=>{
|
|
|
272
429
|
'API'
|
|
273
430
|
].join(' ');
|
|
274
431
|
};
|
|
275
|
-
const openapiGenerator = (rootFolder, title, routePrefix, outputPath)=>{
|
|
432
|
+
const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
|
|
276
433
|
const restFolder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
|
|
277
434
|
const restImport = node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), restFolder);
|
|
278
435
|
const prefixSegments = splitPath(routePrefix);
|
|
279
436
|
const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
|
|
437
|
+
const extractorImport = `./${node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
|
|
438
|
+
const handlers = withExtractor ? `
|
|
439
|
+
const extractOpenApiDataFromEndpointLogic =
|
|
440
|
+
createOpenApiDataFromEndpointLogicExtractor();
|
|
441
|
+
|
|
442
|
+
const handlers = restHandlers.map((x) => ({
|
|
443
|
+
...x,
|
|
444
|
+
metadata: {
|
|
445
|
+
...x.metadata,
|
|
446
|
+
openApiMetadata: {
|
|
447
|
+
...extractOpenApiDataFromEndpointLogic(x.metadata.route),
|
|
448
|
+
...(x.metadata.openApiMetadata ?? {})
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}));
|
|
452
|
+
` : '';
|
|
280
453
|
return `import { generateOpenAPI } from '@domain-first/handlers-rest';
|
|
281
|
-
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}'
|
|
282
|
-
|
|
283
|
-
generateOpenAPI(restHandlers, {
|
|
454
|
+
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
|
|
455
|
+
${handlers}
|
|
456
|
+
generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
|
|
284
457
|
document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
|
|
285
458
|
outputFile: { path: '${outputPath}' }
|
|
286
459
|
});
|
|
287
460
|
`;
|
|
288
461
|
};
|
|
289
|
-
const minimalHandlersRest = [
|
|
290
|
-
7,
|
|
291
|
-
0,
|
|
292
|
-
2
|
|
293
|
-
];
|
|
294
|
-
const parseVersion = (value)=>String(value ?? '').match(/(\d+)\.(\d+)\.(\d+)/)?.slice(1).map(Number);
|
|
295
|
-
const handlersRestUpToDate = (root, declared)=>{
|
|
296
|
-
const installed = new File(node_path.join(root, 'node_modules/@domain-first/handlers-rest/package.json'));
|
|
297
|
-
const version = parseVersion(installed.exists ? JSON.parse(installed.data).version : declared);
|
|
298
|
-
if (!version) return false;
|
|
299
|
-
for (const [index, part] of minimalHandlersRest.entries())if (version[index] !== part) return version[index] > part;
|
|
300
|
-
return true;
|
|
301
|
-
};
|
|
302
462
|
const addOpenapi = async ()=>{
|
|
303
463
|
const { rootFolder } = ConfigFile.Instance.data;
|
|
304
464
|
const root = new ProjectRoot().path;
|
|
@@ -317,18 +477,31 @@ const addOpenapi = async ()=>{
|
|
|
317
477
|
default: defaultOpenapiPath(Boolean(dependencies.next)),
|
|
318
478
|
validate: (value)=>splitPath(value).length ? true : 'Path is required'
|
|
319
479
|
});
|
|
480
|
+
const withExtractor = await prompts_confirm({
|
|
481
|
+
message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
|
|
482
|
+
default: true
|
|
483
|
+
});
|
|
320
484
|
const selected = await addPackageScripts(manifestFile, openapiScripts);
|
|
485
|
+
if (withExtractor) {
|
|
486
|
+
const extractorFile = new File(node_path.join(root, openapiExtractorPath));
|
|
487
|
+
const extractor = openapiExtractor(rootFolder);
|
|
488
|
+
if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
|
|
489
|
+
}
|
|
321
490
|
const generatorFile = new File(node_path.join(root, openapiScriptPath));
|
|
322
|
-
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'));
|
|
491
|
+
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
|
|
323
492
|
if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
|
|
324
493
|
const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
|
|
494
|
+
const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
|
|
325
495
|
return [
|
|
326
|
-
...
|
|
327
|
-
|
|
496
|
+
...dependencies['@domain-first/handlers-rest'] ? [] : [
|
|
497
|
+
'npm install @domain-first/handlers-rest'
|
|
328
498
|
],
|
|
329
499
|
...dependencies.tsx ? [] : [
|
|
330
500
|
'npm install --save-dev tsx'
|
|
331
501
|
],
|
|
502
|
+
...missingExtractorPackages.length ? [
|
|
503
|
+
`npm install --save-dev ${missingExtractorPackages.join(' ')}`
|
|
504
|
+
] : [],
|
|
332
505
|
...describeScripts(selected, {
|
|
333
506
|
openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
|
|
334
507
|
}),
|
|
@@ -2453,12 +2626,18 @@ export const restHandlers = restWires.map(x => x().handle)
|
|
|
2453
2626
|
const routeSegments = (await input({
|
|
2454
2627
|
message: 'Relative path (split by "/"):'
|
|
2455
2628
|
})).split('/').filter((x)=>!!x);
|
|
2629
|
+
const pathParameterAsName = (segment)=>segment.startsWith(':') ? `_${segment.slice(1)}_` : segment;
|
|
2456
2630
|
const controllerFolder = restPresentationFolder.subitem([
|
|
2457
2631
|
controller
|
|
2458
2632
|
]);
|
|
2459
|
-
const endpointFolder = controllerFolder.subitem(routeSegments);
|
|
2460
|
-
const nameBase = `${controller}-${routeSegments.length ? `${routeSegments.join('-')}-` : ''}${method}-endpoint`;
|
|
2461
|
-
const
|
|
2633
|
+
const endpointFolder = controllerFolder.subitem(routeSegments.map(pathParameterAsName));
|
|
2634
|
+
const nameBase = `${controller}-${routeSegments.length ? `${routeSegments.map(pathParameterAsName).join('-')}-` : ''}${method}-endpoint`;
|
|
2635
|
+
const endpointClassName = [
|
|
2636
|
+
controller,
|
|
2637
|
+
...routeSegments,
|
|
2638
|
+
method,
|
|
2639
|
+
'endpoint'
|
|
2640
|
+
].map((segment)=>segment.startsWith(':') ? pathParameterAsName(segment) : new UnknownFormatNaming(segment).ClassName).join('');
|
|
2462
2641
|
const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
|
|
2463
2642
|
const { endpointGenerator, handler } = withWiring ? await promptEndpointDependencies(boundedContextFolder) : {
|
|
2464
2643
|
endpointGenerator: void 0,
|
|
@@ -2469,7 +2648,7 @@ export const restHandlers = restWires.map(x => x().handle)
|
|
|
2469
2648
|
${endpointGenerator ? `import type { ${endpointGenerator.typeName} } from '${relativeImport(endpointFile, endpointGenerator.typeFile)}'` : "import { EndpointGenerator } from '@domain-first/handlers-rest'"}${handler ? `
|
|
2470
2649
|
import type { ${handler.typeName} } from '${relativeImport(endpointFile, handler.typeFile)}'` : ''}
|
|
2471
2650
|
|
|
2472
|
-
export class ${
|
|
2651
|
+
export class ${endpointClassName} {
|
|
2473
2652
|
constructor(
|
|
2474
2653
|
private readonly endpointGenerator: ${endpointGenerator?.typeName ?? 'EndpointGenerator'},
|
|
2475
2654
|
private readonly handler: ${handler?.typeName ?? 'never'}
|
|
@@ -2499,11 +2678,11 @@ export class ${endpointNaming.ClassName} {
|
|
|
2499
2678
|
].filter((x)=>!!x) : [];
|
|
2500
2679
|
wiringFolder.createFile(`${wireNaming.fileName}.ts`, `
|
|
2501
2680
|
import { wireClass } from '@domain-first/wire'
|
|
2502
|
-
import { ${
|
|
2681
|
+
import { ${endpointClassName} } from '${relativeImport(wireFile, endpointFile)}'
|
|
2503
2682
|
${dependencies.map((x)=>`import { ${x.wireName} } from '${relativeImport(wireFile, x.wireFile)}'`).join('\n')}
|
|
2504
2683
|
|
|
2505
|
-
export const wire${
|
|
2506
|
-
${
|
|
2684
|
+
export const wire${endpointClassName} = wireClass(
|
|
2685
|
+
${endpointClassName},
|
|
2507
2686
|
[${dependencies.map((x)=>x.wireName).join(', ')}]
|
|
2508
2687
|
)
|
|
2509
2688
|
`.trim());
|
|
@@ -4,10 +4,5 @@ export declare const openapiScripts: {
|
|
|
4
4
|
openapi: string;
|
|
5
5
|
};
|
|
6
6
|
export declare const apiTitle: (packageName: unknown) => string;
|
|
7
|
-
export declare const openapiGenerator: (rootFolder: string, title: string, routePrefix: string, outputPath: string) => string;
|
|
8
|
-
/**
|
|
9
|
-
* The installed version wins over the declared range, which only gives
|
|
10
|
-
* the lowest version allowed.
|
|
11
|
-
*/
|
|
12
|
-
export declare const handlersRestUpToDate: (root: string, declared: unknown) => boolean;
|
|
7
|
+
export declare const openapiGenerator: (rootFolder: string, title: string, routePrefix: string, outputPath: string, withExtractor?: boolean) => string;
|
|
13
8
|
export declare const addOpenapi: () => Promise<string[]>;
|