-
-
Notifications
You must be signed in to change notification settings - Fork 880
/
signature.ts
215 lines (191 loc) · 6.22 KB
/
signature.ts
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import sanitizeHtml from 'sanitize-html';
import type {
Comment,
ParameterReflection,
Reflection,
SignatureReflection,
SomeType,
} from 'typedoc';
import { ReflectionFlag, ReflectionKind } from 'typedoc';
import { createMarkdownRenderer } from 'vitepress';
import type {
Method,
MethodParameter,
} from '../../docs/.vitepress/components/api-docs/method';
import faker from '../../src';
import { pathOutputDir } from './utils';
// TODO ST-DDT 2022-02-20: Actually import this/fix module import errors
// import vitepressConfig from '../../docs/.vitepress/config';
export function prettifyMethodName(method: string): string {
return (
// Capitalize and insert space before upper case characters
method.substring(0, 1).toUpperCase() +
method.substring(1).replace(/([A-Z]+)/g, ' $1')
);
}
export function toBlock(comment?: Comment): string {
return (
(comment?.shortText.trim() || 'Missing') +
(comment?.text ? '\n\n' + comment.text : '')
);
}
const markdown = createMarkdownRenderer(
pathOutputDir,
undefined,
// TODO ST-DDT 2022-02-20: Actually import this/fix module import errors
// vitepressConfig.markdown,
'/'
);
const htmlSanitizeOptions: sanitizeHtml.IOptions = {
allowedTags: ['a', 'code', 'div', 'li', 'span', 'p', 'pre', 'ul'],
allowedAttributes: {
a: ['href', 'target', 'rel'],
div: ['class'],
pre: ['v-pre'],
span: ['class'],
},
selfClosing: [],
};
function mdToHtml(md: string): string {
const rawHtml = markdown.render(md);
const safeHtml: string = sanitizeHtml(rawHtml, htmlSanitizeOptions);
// Revert some escaped characters for comparison.
if (rawHtml.replace(/>/g, '>') === safeHtml.replace(/>/g, '>')) {
return safeHtml;
} else {
console.debug('Rejected unsafe md:', md);
console.error('Rejected unsafe html:', rawHtml.replace(/>/g, '>'));
console.error('Expected safe html:', safeHtml.replace(/>/g, '>'));
throw new Error('Found unsafe html');
}
}
export function analyzeSignature(
signature: SignatureReflection,
moduleName: string,
methodName: string
): Method {
const parameters: MethodParameter[] = [];
// Collect Type Parameters
const typeParameters = signature.typeParameters || [];
const signatureTypeParameters: string[] = [];
for (const parameter of typeParameters) {
signatureTypeParameters.push(parameter.name);
parameters.push({
name: parameter.name,
description: mdToHtml(toBlock(parameter.comment)),
});
}
// Collect Parameters
const signatureParameters: string[] = [];
for (
let index = 0;
signature.parameters && index < signature.parameters.length;
index++
) {
const parameter = signature.parameters[index];
const aParam = analyzeParameter(parameter);
signatureParameters.push(aParam.signature);
parameters.push(...aParam.parameters);
}
// Generate usage section
let signatureTypeParametersString = '';
if (signatureTypeParameters.length !== 0) {
signatureTypeParametersString = `<${signatureTypeParameters.join(', ')}>`;
}
const signatureParametersString = signatureParameters.join(', ');
let examples: string;
if (moduleName) {
examples = `faker.${moduleName}.${methodName}${signatureTypeParametersString}(${signatureParametersString}): ${signature.type.toString()}\n`;
} else {
examples = `faker.${methodName}${signatureTypeParametersString}(${signatureParametersString}): ${signature.type.toString()}\n`;
}
faker.seed(0);
if (moduleName) {
try {
let example = JSON.stringify(faker[moduleName][methodName]());
if (example.length > 50) {
example = example.substring(0, 47) + '...';
}
examples += `faker.${moduleName}.${methodName}()`;
examples += (example ? ` // => ${example}` : '') + '\n';
} catch (error) {
// Ignore the error => hide the example call + result.
}
}
const exampleTags =
signature?.comment?.tags
.filter((tag) => tag.tagName === 'example')
.map((tag) => tag.text.trimEnd()) || [];
if (exampleTags.length > 0) {
examples += exampleTags.join('\n').trim() + '\n';
}
const seeAlsos =
signature.comment?.tags
.filter((t) => t.tagName === 'see')
.map((t) => t.text.trim()) ?? [];
const prettyMethodName = prettifyMethodName(methodName);
return {
name: methodName,
title: prettyMethodName,
description: mdToHtml(toBlock(signature.comment)),
parameters: parameters,
returns: signature.type.toString(),
examples: mdToHtml('```ts\n' + examples + '```'),
deprecated: signature.comment?.hasTag('deprecated') ?? false,
seeAlsos,
};
}
function analyzeParameter(parameter: ParameterReflection): {
parameters: MethodParameter[];
signature: string;
} {
const name = parameter.name;
const declarationName = name + (isOptional(parameter) ? '?' : '');
const type = parameter.type;
const typeText = type.toString();
const defaultValue = parameter.defaultValue;
let signatureText = '';
if (defaultValue) {
signatureText = ' = ' + defaultValue;
}
const signature = declarationName + ': ' + typeText + signatureText;
const parameters: MethodParameter[] = [
{
name: declarationName,
type: typeText,
default: defaultValue,
description: mdToHtml(toBlock(parameter.comment)),
},
];
parameters.push(...analyzeParameterOptions(name, type));
return {
parameters,
signature,
};
}
function analyzeParameterOptions(
name: string,
parameterType: SomeType
): MethodParameter[] {
if (parameterType.type === 'union') {
return [];
// TODO ST-DDT 2022-02-26: Currently not supported by typedoc
// https://github.com/TypeStrong/typedoc/issues/1876
// return parameterType.types.flatMap((type) =>
// analyzeParameterOptions(name, type)
// );
} else if (parameterType.type === 'reflection') {
const properties = parameterType.declaration.getChildrenByKind(
ReflectionKind.Property
);
return properties.map((property) => ({
name: `${name}.${property.name}${isOptional(property) ? '?' : ''}`,
type: property.type.toString(),
description: mdToHtml(toBlock(property.comment)),
}));
}
return [];
}
function isOptional(parameter: Reflection): boolean {
return parameter.flags.hasFlag(ReflectionFlag.Optional);
}