@domain-first/project-structure 2.16.2 → 2.17.1
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 +198 -20
- package/dist/index.js +198 -20
- 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,164 @@ 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
|
+
// Path parameters (\`:id\`) can't be part of file and folder names
|
|
357
|
+
// everywhere (Windows), so endpoints name them \`_id_\` there.
|
|
358
|
+
const pathParameterAsName = (segment: string) =>
|
|
359
|
+
segment.startsWith(':') ? \`_\${segment.slice(1)}_\` : segment;
|
|
360
|
+
|
|
361
|
+
export const createOpenApiDataFromEndpointLogicExtractor = ({
|
|
362
|
+
summary: summaryTag,
|
|
363
|
+
description: descriptionTag = '@description'
|
|
364
|
+
}: OpenApiDataTags = {}) => {
|
|
365
|
+
return (routeMetadata: {
|
|
366
|
+
method: string;
|
|
367
|
+
path: readonly string[];
|
|
368
|
+
}): OpenApiData | undefined => {
|
|
369
|
+
try {
|
|
370
|
+
const [currentBoundedContext, controller, ...relativePath] =
|
|
371
|
+
routeMetadata.path;
|
|
372
|
+
|
|
373
|
+
if (!currentBoundedContext || !controller) {
|
|
374
|
+
return undefined;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const endpointFile = project.getSourceFile(
|
|
378
|
+
path.join(
|
|
379
|
+
${rootFolderSegments(rootFolder)}'bounded-contexts',
|
|
380
|
+
currentBoundedContext,
|
|
381
|
+
'presentation',
|
|
382
|
+
'rest',
|
|
383
|
+
controller,
|
|
384
|
+
...relativePath.map(pathParameterAsName),
|
|
385
|
+
\`\${routeMetadata.method.toUpperCase()}.ts\`
|
|
386
|
+
)
|
|
387
|
+
);
|
|
388
|
+
|
|
389
|
+
if (!endpointFile) {
|
|
390
|
+
return undefined;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const declaration = findHandlerClass(endpointFile);
|
|
394
|
+
const operationId = declaration?.getName();
|
|
395
|
+
const comment = declaration?.getJsDocs().at(-1)?.getText();
|
|
396
|
+
|
|
397
|
+
if (!comment) {
|
|
398
|
+
return { operationId };
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
return {
|
|
402
|
+
summary: summaryTag
|
|
403
|
+
? getTagText(comment, summaryTag)
|
|
404
|
+
: parseSummary(comment),
|
|
405
|
+
description: getTagText(comment, descriptionTag),
|
|
406
|
+
operationId
|
|
407
|
+
};
|
|
408
|
+
} catch (e: unknown) {
|
|
409
|
+
console.error(e);
|
|
410
|
+
return undefined;
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
};
|
|
414
|
+
`;
|
|
257
415
|
const addPackageScripts = async (file, additions)=>{
|
|
258
416
|
const original = file.data;
|
|
259
417
|
const manifest = JSON.parse(original);
|
|
@@ -291,6 +449,10 @@ const addPackageScripts = async (file, additions)=>{
|
|
|
291
449
|
const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
|
|
292
450
|
const openapiScriptPath = "scripts/generate-openapi.ts";
|
|
293
451
|
const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
|
|
452
|
+
const extractorPackages = [
|
|
453
|
+
'ts-morph',
|
|
454
|
+
'@microsoft/tsdoc'
|
|
455
|
+
];
|
|
294
456
|
const openapiScripts = {
|
|
295
457
|
openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
|
|
296
458
|
};
|
|
@@ -302,33 +464,36 @@ const apiTitle = (packageName)=>{
|
|
|
302
464
|
'API'
|
|
303
465
|
].join(' ');
|
|
304
466
|
};
|
|
305
|
-
const openapiGenerator = (rootFolder, title, routePrefix, outputPath)=>{
|
|
467
|
+
const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
|
|
306
468
|
const restFolder = external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
|
|
307
469
|
const restImport = external_node_path_default().posix.relative(external_node_path_default().posix.dirname(openapiScriptPath), restFolder);
|
|
308
470
|
const prefixSegments = splitPath(routePrefix);
|
|
309
471
|
const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
|
|
472
|
+
const extractorImport = `./${external_node_path_default().posix.relative(external_node_path_default().posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
|
|
473
|
+
const handlers = withExtractor ? `
|
|
474
|
+
const extractOpenApiDataFromEndpointLogic =
|
|
475
|
+
createOpenApiDataFromEndpointLogicExtractor();
|
|
476
|
+
|
|
477
|
+
const handlers = restHandlers.map((x) => ({
|
|
478
|
+
...x,
|
|
479
|
+
metadata: {
|
|
480
|
+
...x.metadata,
|
|
481
|
+
openApiMetadata: {
|
|
482
|
+
...extractOpenApiDataFromEndpointLogic(x.metadata.route),
|
|
483
|
+
...(x.metadata.openApiMetadata ?? {})
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}));
|
|
487
|
+
` : '';
|
|
310
488
|
return `import { generateOpenAPI } from '@domain-first/handlers-rest';
|
|
311
|
-
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}'
|
|
312
|
-
|
|
313
|
-
generateOpenAPI(restHandlers, {
|
|
489
|
+
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
|
|
490
|
+
${handlers}
|
|
491
|
+
generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
|
|
314
492
|
document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
|
|
315
493
|
outputFile: { path: '${outputPath}' }
|
|
316
494
|
});
|
|
317
495
|
`;
|
|
318
496
|
};
|
|
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
497
|
const addOpenapi = async ()=>{
|
|
333
498
|
const { rootFolder } = ConfigFile.Instance.data;
|
|
334
499
|
const root = new ProjectRoot().path;
|
|
@@ -347,18 +512,31 @@ const addOpenapi = async ()=>{
|
|
|
347
512
|
default: defaultOpenapiPath(Boolean(dependencies.next)),
|
|
348
513
|
validate: (value)=>splitPath(value).length ? true : 'Path is required'
|
|
349
514
|
});
|
|
515
|
+
const withExtractor = await (0, prompts_namespaceObject.confirm)({
|
|
516
|
+
message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
|
|
517
|
+
default: true
|
|
518
|
+
});
|
|
350
519
|
const selected = await addPackageScripts(manifestFile, openapiScripts);
|
|
520
|
+
if (withExtractor) {
|
|
521
|
+
const extractorFile = new File(external_node_path_default().join(root, openapiExtractorPath));
|
|
522
|
+
const extractor = openapiExtractor(rootFolder);
|
|
523
|
+
if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
|
|
524
|
+
}
|
|
351
525
|
const generatorFile = new File(external_node_path_default().join(root, openapiScriptPath));
|
|
352
|
-
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'));
|
|
526
|
+
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
|
|
353
527
|
if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
|
|
354
528
|
const hasRestHandlers = new File(external_node_path_default().join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
|
|
529
|
+
const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
|
|
355
530
|
return [
|
|
356
|
-
...
|
|
357
|
-
|
|
531
|
+
...dependencies['@domain-first/handlers-rest'] ? [] : [
|
|
532
|
+
'npm install @domain-first/handlers-rest'
|
|
358
533
|
],
|
|
359
534
|
...dependencies.tsx ? [] : [
|
|
360
535
|
'npm install --save-dev tsx'
|
|
361
536
|
],
|
|
537
|
+
...missingExtractorPackages.length ? [
|
|
538
|
+
`npm install --save-dev ${missingExtractorPackages.join(' ')}`
|
|
539
|
+
] : [],
|
|
362
540
|
...describeScripts(selected, {
|
|
363
541
|
openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
|
|
364
542
|
}),
|
package/dist/index.js
CHANGED
|
@@ -224,6 +224,164 @@ 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
|
+
// Path parameters (\`:id\`) can't be part of file and folder names
|
|
327
|
+
// everywhere (Windows), so endpoints name them \`_id_\` there.
|
|
328
|
+
const pathParameterAsName = (segment: string) =>
|
|
329
|
+
segment.startsWith(':') ? \`_\${segment.slice(1)}_\` : segment;
|
|
330
|
+
|
|
331
|
+
export const createOpenApiDataFromEndpointLogicExtractor = ({
|
|
332
|
+
summary: summaryTag,
|
|
333
|
+
description: descriptionTag = '@description'
|
|
334
|
+
}: OpenApiDataTags = {}) => {
|
|
335
|
+
return (routeMetadata: {
|
|
336
|
+
method: string;
|
|
337
|
+
path: readonly string[];
|
|
338
|
+
}): OpenApiData | undefined => {
|
|
339
|
+
try {
|
|
340
|
+
const [currentBoundedContext, controller, ...relativePath] =
|
|
341
|
+
routeMetadata.path;
|
|
342
|
+
|
|
343
|
+
if (!currentBoundedContext || !controller) {
|
|
344
|
+
return undefined;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const endpointFile = project.getSourceFile(
|
|
348
|
+
path.join(
|
|
349
|
+
${rootFolderSegments(rootFolder)}'bounded-contexts',
|
|
350
|
+
currentBoundedContext,
|
|
351
|
+
'presentation',
|
|
352
|
+
'rest',
|
|
353
|
+
controller,
|
|
354
|
+
...relativePath.map(pathParameterAsName),
|
|
355
|
+
\`\${routeMetadata.method.toUpperCase()}.ts\`
|
|
356
|
+
)
|
|
357
|
+
);
|
|
358
|
+
|
|
359
|
+
if (!endpointFile) {
|
|
360
|
+
return undefined;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const declaration = findHandlerClass(endpointFile);
|
|
364
|
+
const operationId = declaration?.getName();
|
|
365
|
+
const comment = declaration?.getJsDocs().at(-1)?.getText();
|
|
366
|
+
|
|
367
|
+
if (!comment) {
|
|
368
|
+
return { operationId };
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
return {
|
|
372
|
+
summary: summaryTag
|
|
373
|
+
? getTagText(comment, summaryTag)
|
|
374
|
+
: parseSummary(comment),
|
|
375
|
+
description: getTagText(comment, descriptionTag),
|
|
376
|
+
operationId
|
|
377
|
+
};
|
|
378
|
+
} catch (e: unknown) {
|
|
379
|
+
console.error(e);
|
|
380
|
+
return undefined;
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
};
|
|
384
|
+
`;
|
|
227
385
|
const addPackageScripts = async (file, additions)=>{
|
|
228
386
|
const original = file.data;
|
|
229
387
|
const manifest = JSON.parse(original);
|
|
@@ -261,6 +419,10 @@ const addPackageScripts = async (file, additions)=>{
|
|
|
261
419
|
const describeScripts = (selected, descriptions)=>Object.entries(descriptions).filter(([name])=>selected[name]).map(([name, description])=>`npm run ${selected[name]} — ${description}`);
|
|
262
420
|
const openapiScriptPath = "scripts/generate-openapi.ts";
|
|
263
421
|
const defaultOpenapiPath = (withNext)=>withNext ? 'public/openapi.json' : 'openapi.json';
|
|
422
|
+
const extractorPackages = [
|
|
423
|
+
'ts-morph',
|
|
424
|
+
'@microsoft/tsdoc'
|
|
425
|
+
];
|
|
264
426
|
const openapiScripts = {
|
|
265
427
|
openapi: `tsx --env-file-if-exists=.env ${openapiScriptPath}`
|
|
266
428
|
};
|
|
@@ -272,33 +434,36 @@ const apiTitle = (packageName)=>{
|
|
|
272
434
|
'API'
|
|
273
435
|
].join(' ');
|
|
274
436
|
};
|
|
275
|
-
const openapiGenerator = (rootFolder, title, routePrefix, outputPath)=>{
|
|
437
|
+
const openapiGenerator = (rootFolder, title, routePrefix, outputPath, withExtractor = false)=>{
|
|
276
438
|
const restFolder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest');
|
|
277
439
|
const restImport = node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), restFolder);
|
|
278
440
|
const prefixSegments = splitPath(routePrefix);
|
|
279
441
|
const apiRoutePrefix = prefixSegments.length ? `\n apiRoutePrefix: [${prefixSegments.map((segment)=>`'${segment}'`).join(', ')}],` : '';
|
|
442
|
+
const extractorImport = `./${node_path.posix.relative(node_path.posix.dirname(openapiScriptPath), openapiExtractorPath.replace(/\.ts$/, ''))}`;
|
|
443
|
+
const handlers = withExtractor ? `
|
|
444
|
+
const extractOpenApiDataFromEndpointLogic =
|
|
445
|
+
createOpenApiDataFromEndpointLogicExtractor();
|
|
446
|
+
|
|
447
|
+
const handlers = restHandlers.map((x) => ({
|
|
448
|
+
...x,
|
|
449
|
+
metadata: {
|
|
450
|
+
...x.metadata,
|
|
451
|
+
openApiMetadata: {
|
|
452
|
+
...extractOpenApiDataFromEndpointLogic(x.metadata.route),
|
|
453
|
+
...(x.metadata.openApiMetadata ?? {})
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}));
|
|
457
|
+
` : '';
|
|
280
458
|
return `import { generateOpenAPI } from '@domain-first/handlers-rest';
|
|
281
|
-
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}'
|
|
282
|
-
|
|
283
|
-
generateOpenAPI(restHandlers, {
|
|
459
|
+
import { restHandlers } from '${restImport.startsWith('.') ? restImport : `./${restImport}`}';${withExtractor ? `\nimport { createOpenApiDataFromEndpointLogicExtractor } from '${extractorImport}';` : ''}
|
|
460
|
+
${handlers}
|
|
461
|
+
generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
|
|
284
462
|
document: { info: { title: '${title}', version: '1.0.0' } },${apiRoutePrefix}
|
|
285
463
|
outputFile: { path: '${outputPath}' }
|
|
286
464
|
});
|
|
287
465
|
`;
|
|
288
466
|
};
|
|
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
467
|
const addOpenapi = async ()=>{
|
|
303
468
|
const { rootFolder } = ConfigFile.Instance.data;
|
|
304
469
|
const root = new ProjectRoot().path;
|
|
@@ -317,18 +482,31 @@ const addOpenapi = async ()=>{
|
|
|
317
482
|
default: defaultOpenapiPath(Boolean(dependencies.next)),
|
|
318
483
|
validate: (value)=>splitPath(value).length ? true : 'Path is required'
|
|
319
484
|
});
|
|
485
|
+
const withExtractor = await prompts_confirm({
|
|
486
|
+
message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
|
|
487
|
+
default: true
|
|
488
|
+
});
|
|
320
489
|
const selected = await addPackageScripts(manifestFile, openapiScripts);
|
|
490
|
+
if (withExtractor) {
|
|
491
|
+
const extractorFile = new File(node_path.join(root, openapiExtractorPath));
|
|
492
|
+
const extractor = openapiExtractor(rootFolder);
|
|
493
|
+
if (!extractorFile.exists || extractorFile.data !== extractor) extractorFile.data = extractor;
|
|
494
|
+
}
|
|
321
495
|
const generatorFile = new File(node_path.join(root, openapiScriptPath));
|
|
322
|
-
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'));
|
|
496
|
+
const content = openapiGenerator(rootFolder, apiTitle(manifest.name), routePrefix, splitPath(outputPath).join('/'), withExtractor);
|
|
323
497
|
if (!generatorFile.exists || generatorFile.data !== content) generatorFile.data = content;
|
|
324
498
|
const hasRestHandlers = new File(node_path.join(root, rootFolder, 'presentation', 'rest', 'index.ts')).exists;
|
|
499
|
+
const missingExtractorPackages = withExtractor ? extractorPackages.filter((name)=>!dependencies[name]) : [];
|
|
325
500
|
return [
|
|
326
|
-
...
|
|
327
|
-
|
|
501
|
+
...dependencies['@domain-first/handlers-rest'] ? [] : [
|
|
502
|
+
'npm install @domain-first/handlers-rest'
|
|
328
503
|
],
|
|
329
504
|
...dependencies.tsx ? [] : [
|
|
330
505
|
'npm install --save-dev tsx'
|
|
331
506
|
],
|
|
507
|
+
...missingExtractorPackages.length ? [
|
|
508
|
+
`npm install --save-dev ${missingExtractorPackages.join(' ')}`
|
|
509
|
+
] : [],
|
|
332
510
|
...describeScripts(selected, {
|
|
333
511
|
openapi: `generate the OpenAPI document from restHandlers in ${splitPath(outputPath).join('/')}`
|
|
334
512
|
}),
|
|
@@ -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[]>;
|