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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
|
import { writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { ApiDocsMethod } from '../../../docs/.vitepress/components/api-docs/method';
import type { RawApiDocsPage } from '../processing/class';
import type { RawApiDocsMethod } from '../processing/method';
import { formatMarkdown, formatTypescript } from '../utils/format';
import { adjustUrls, codeToHtml, mdToHtml } from '../utils/markdown';
import { FILE_PATH_API_DOCS } from '../utils/paths';
import { required } from '../utils/value-checks';
import { SCRIPT_COMMAND } from './constants';
// Extracted to a constant because the contents must not be formatted by prettier
const vitePressInFileOptions = `---
editLink: false
---
`;
/**
* Writes the api docs page and data for the given modules to the correct location.
*
* @param pages The pages to write.
*/
export async function writePages(pages: RawApiDocsPage[]): Promise<void> {
await Promise.all(pages.map(writePage));
}
/**
* Writes the api docs page and data for the given module to the correct location.
*
* @param page The page to write.
*/
async function writePage(page: RawApiDocsPage): Promise<void> {
try {
await writePageMarkdown(page);
await writePageData(page);
} catch (error) {
throw new Error(`Error writing page ${page.title}`, { cause: error });
}
}
/**
* Writes the api docs page for the given module to the correct location.
*
* @param page The page to write.
*/
async function writePageMarkdown(page: RawApiDocsPage): Promise<void> {
const { title, camelTitle, deprecated, description, examples, methods } =
page;
// Write api docs page
let content = `
<script setup>
import ApiDocsMethod from '../.vitepress/components/api-docs/method.vue';
import ${camelTitle} from './${camelTitle}.ts';
</script>
<!-- This file is automatically generated. -->
<!-- Run '${SCRIPT_COMMAND}' to update -->
# ${title}
::: v-pre
${
deprecated == null
? ''
: `<div class="warning custom-block">
<p class="custom-block-title">Deprecated</p>
<p>This module is deprecated and will be removed in a future version.</p>
<span>${deprecated}</span>
</div>`
}
${adjustUrls(description)}
${examples.length === 0 ? '' : `<div class="examples">${codeToHtml(examples.join('\n'))}</div>`}
:::
${methods
.map(
(method) => `
## ${method.name}
<ApiDocsMethod :method="${camelTitle}.${method.name}" v-once />
`
)
.join('')}
`.replaceAll(/\n +/g, '\n');
content = vitePressInFileOptions + (await formatMarkdown(content));
writeFileSync(resolve(FILE_PATH_API_DOCS, `${camelTitle}.md`), content);
}
/**
* Writes the api docs data for the given module to correct location.
*
* @param page The page to write.
*/
async function writePageData(page: RawApiDocsPage): Promise<void> {
const { camelTitle, methods } = page;
const pageData: Record<string, ApiDocsMethod> = Object.fromEntries(
await Promise.all(
methods.map(async (method) => [method.name, await toMethodData(method)])
)
);
const refreshFunctions: Record<string, string> = Object.fromEntries(
await Promise.all(
methods.map(async (method) => [
method.name,
await toRefreshFunction(method),
])
)
);
const content =
`export default ${JSON.stringify(pageData, undefined, 2)}`.replaceAll(
/"refresh-([^"-]+)-placeholder"/g,
(_, name) => refreshFunctions[name]
);
writeFileSync(
resolve(FILE_PATH_API_DOCS, `${camelTitle}.ts`),
await formatTypescript(content)
);
}
const defaultCommentRegex = /\s+Defaults to `([^`]+)`\..*/;
async function toMethodData(method: RawApiDocsMethod): Promise<ApiDocsMethod> {
const { name, signatures, source } = method;
const signatureData = required(signatures.at(-1), 'method signature');
const {
deprecated,
description,
since,
parameters,
remarks,
returns,
throws,
signature,
examples,
seeAlsos,
} = signatureData;
const { filePath, line } = source;
let formattedSignature = await formatTypescript(signature);
formattedSignature = formattedSignature.trim();
// eslint-disable-next-line @typescript-eslint/require-await
const refresh = async () => ['refresh', name, 'placeholder'];
// This is a placeholder to be replaced by the actual refresh function code
// If we put the actual code here, it would be a string and not executable
refresh.toJSON = () => `refresh-${name}-placeholder`;
/* Target order, omitted to improve diff to old files
return {
name,
deprecated: mdToHtml(deprecated),
description: mdToHtml(description),
remark: remarks.length === 0 ? undefined : mdToHtml(remarks.join('\n')),
since,
parameters: parameters.map((param) => ({
...param,
type: param.type.text,
default:
param.default ?? defaultCommentRegex.exec(param.description)?.[1],
description: mdToHtml(param.description.replace(defaultCommentRegex, '')),
})),
returns: returns.text,
throws: throws.length === 0 ? undefined : mdToHtml(throws.join('\n'), true),
// signature: codeToHtml(signature),
examples: codeToHtml([signature, ...examples].join('\n')),
seeAlsos: seeAlsos.map((seeAlso) => mdToHtml(seeAlso, true)),
sourcePath: sourcePath.replace(/:(\d+):\d+/g, '#L$1'),
};
*/
return {
name,
description: mdToHtml(description),
remark: remarks.length === 0 ? undefined : mdToHtml(remarks.join('\n')),
parameters: parameters.map((param) => ({
...param,
type: param.type.text,
default: param.default ?? extractSummaryDefault(param.description),
description: mdToHtml(param.description.replace(defaultCommentRegex, '')),
})),
since,
sourcePath: `${filePath}#L${line}`,
throws: throws.length === 0 ? undefined : mdToHtml(throws.join('\n'), true),
returns: returns.text,
signature: codeToHtml(formattedSignature),
examples: codeToHtml(examples.join('\n')),
refresh,
deprecated: mdToHtml(deprecated),
seeAlsos: seeAlsos.map((seeAlso) => mdToHtml(seeAlso, true)),
};
}
export function extractSummaryDefault(description: string): string | undefined {
return defaultCommentRegex.exec(description)?.[1];
}
export async function toRefreshFunction(
method: RawApiDocsMethod
): Promise<string> {
const { name, signatures } = method;
const signatureData = required(signatures.at(-1), 'method signature');
const { examples } = signatureData;
const exampleCode = examples.join('\n');
if (!/^\w*faker\w*\./im.test(exampleCode)) {
// No recordable faker calls in examples
return 'undefined';
}
const exampleLines = exampleCode
.replaceAll(/ ?\/\/.*$/gm, '') // Remove comments
.replaceAll(/^import .*$/gm, '') // Remove imports
.replaceAll(
// record results of faker calls
/^(\w*faker\w*\..+(?:(?:.|\n..)*\n[^ ])?\)(?:\.\w+)?);?$/gim,
`try { result.push($1); } catch (error: unknown) { result.push(error instanceof Error ? error.name : 'Error'); }\n`
);
const fullMethod = `async (): Promise<unknown[]> => {
await enableFaker();
faker.seed();
faker.setDefaultRefDate();
const result: unknown[] = [];
${exampleLines}
return result;
}`;
try {
const formattedMethod = await formatTypescript(fullMethod);
return formattedMethod.replace(/;\s+$/, ''); // Remove trailing semicolon
} catch (error: unknown) {
console.error(
'Failed to format refresh function for',
name,
fullMethod,
error
);
return 'undefined';
}
}
|