-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathtransformers.ts
More file actions
55 lines (50 loc) · 1.64 KB
/
transformers.ts
File metadata and controls
55 lines (50 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import type { PluginConfig, TransformerExtras } from 'ts-patch';
import type * as ts from 'typescript';
const tsInstance: typeof ts = require('typescript');
function generateJSDocComment(typeName: string, baseUrl: string): string {
const markdownLink = `${baseUrl}#${typeName.toLowerCase()}`;
return `*
* Type Definition: \`${typeName}\`
*
* This type is derived from a Zod schema and represents
* the validated structure of \`${typeName}\` used within the application.
*
* @see {@link ${markdownLink}}
`;
}
function annotateTypeDefinitions(
_program: ts.Program,
pluginConfig: PluginConfig,
extras?: TransformerExtras,
): ts.TransformerFactory<ts.SourceFile> {
const baseUrl = pluginConfig.baseUrl as string | undefined;
if (!baseUrl) {
throw new Error(
'zod2md-jsdocs: "baseUrl" option is required. ' +
'Please configure it in your tsconfig.json plugins section.',
);
}
const tsLib = extras?.ts ?? tsInstance;
return (context: ts.TransformationContext) => {
const visitor = (node: ts.Node): ts.Node => {
if (
tsLib.isTypeAliasDeclaration(node) ||
tsLib.isInterfaceDeclaration(node)
) {
const jsDocComment = generateJSDocComment(node.name.text, baseUrl);
tsLib.addSyntheticLeadingComment(
node,
tsLib.SyntaxKind.MultiLineCommentTrivia,
jsDocComment,
true,
);
return node;
}
return tsLib.visitEachChild(node, visitor, context);
};
return (sourceFile: ts.SourceFile) => {
return tsLib.visitNode(sourceFile, visitor, tsLib.isSourceFile);
};
};
}
module.exports = annotateTypeDefinitions;