-
Notifications
You must be signed in to change notification settings - Fork 897
/
docgen.ts
388 lines (359 loc) · 10.4 KB
/
docgen.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
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { spawn } from 'child-process-promise';
import { mapWorkspaceToPackages } from '../release/utils/workspace';
import { projectRoot } from '../utils';
import fs from 'fs';
import glob from 'glob';
import { join } from 'path';
import * as yargs from 'yargs';
/**
* Add to devsite files to alert anyone trying to make a documentation fix
* to the generated files.
*/
const GOOGLE3_HEADER = `
{% comment %}
DO NOT EDIT THIS FILE!
This is generated by the JS SDK team, and any local changes will be
overwritten. Changes should be made in the source code at
https://github.com/firebase/firebase-js-sdk
{% endcomment %}
`;
const tmpDir = `${projectRoot}/temp`;
const EXCLUDED_PACKAGES = [
'app-compat',
'util',
'rules-unit-testing',
'data-connect'
];
/**
* When ordering functions, will prioritize these first params at
* the top, in order.
*/
const PREFERRED_PARAMS = [
'app',
'analyticsInstance',
'appCheckInstance',
'db',
'firestore',
'functionsInstance',
'installations',
'messaging',
'performance',
'remoteConfig',
'storage',
'vertexAI'
];
let authApiReportOriginal: string;
let authApiConfigOriginal: string;
yargs
.command(
'$0',
'generate standard reference docs',
{
skipBuild: {
type: 'boolean',
default: false
}
},
_argv => generateDocs(/* forDevsite */ false, _argv.skipBuild)
)
.command(
'devsite',
'generate reference docs for devsite',
{
skipBuild: {
type: 'boolean',
default: false
}
},
_argv => generateDocs(/* forDevsite */ true, _argv.skipBuild)
)
.command('toc', 'generate devsite TOC', {}, _argv => generateToc())
.option('skipBuild', {
describe:
'Skip yarn build and api-report - only do this if you have already generated the most up to date .api.json files',
type: 'boolean'
})
.demandCommand()
.help().argv;
process.on('exit', cleanup);
process.on('SIGINT', cleanup);
function cleanup() {
try {
// Restore original auth api-extractor.json contents.
if (authApiReportOriginal) {
console.log(`Restoring original auth api-extractor.json contents.`);
fs.writeFileSync(
`${projectRoot}/packages/auth/api-extractor.json`,
authApiConfigOriginal
);
}
// Restore original auth.api.md
if (authApiConfigOriginal) {
console.log(`Restoring original auth.api.md contents.`);
fs.writeFileSync(
`${projectRoot}/common/api-review/auth.api.md`,
authApiReportOriginal
);
}
for (const excludedPackage of EXCLUDED_PACKAGES) {
if (fs.existsSync(`${projectRoot}/temp/${excludedPackage}.skip`)) {
console.log(
`Restoring json files for excluded package: ${excludedPackage}.`
);
fs.renameSync(
`${projectRoot}/temp/${excludedPackage}.skip`,
`${projectRoot}/temp/${excludedPackage}.api.json`
);
}
}
} catch (e) {
console.error(
'Error cleaning up files on exit - ' +
'check for temp modifications to md and json files.'
);
console.error(e);
}
}
async function generateToc() {
console.log(`Temporarily renaming excluded packages' json files.`);
for (const excludedPackage of EXCLUDED_PACKAGES) {
if (fs.existsSync(`${projectRoot}/temp/${excludedPackage}.api.json`)) {
fs.renameSync(
`${projectRoot}/temp/${excludedPackage}.api.json`,
`${projectRoot}/temp/${excludedPackage}.skip`
);
}
}
try {
await spawn(
'yarn',
[
'api-documenter-devsite',
'toc',
'--input',
'temp',
'--output',
'docs-devsite',
'-p',
'/docs/reference/js',
'-j'
],
{ stdio: 'inherit' }
);
// The toc on the devsite must be named _toc.yaml
await spawn('mv', ['docs-devsite/toc.yaml', 'docs-devsite/_toc.yaml'], {
stdio: 'inherit'
});
} finally {
cleanup();
}
}
// create *.api.json files
async function generateDocs(
forDevsite: boolean = false,
skipBuild: boolean = false
) {
const outputFolder = forDevsite ? 'docs-devsite' : 'docs';
const command = forDevsite ? 'api-documenter-devsite' : 'api-documenter';
console.log(`Temporarily modifying auth api-extractor.json for docgen.`);
// Use a special d.ts file for auth for doc gen only.
authApiConfigOriginal = fs.readFileSync(
`${projectRoot}/packages/auth/api-extractor.json`,
'utf8'
);
// Save original auth.md as well.
authApiReportOriginal = fs.readFileSync(
`${projectRoot}/common/api-review/auth.api.md`,
'utf8'
);
const authApiConfigModified = authApiConfigOriginal.replace(
`"mainEntryPointFilePath": "<projectFolder>/dist/esm2017/index.d.ts"`,
`"mainEntryPointFilePath": "<projectFolder>/dist/esm2017/index.doc.d.ts"`
);
try {
fs.writeFileSync(
`${projectRoot}/packages/auth/api-extractor.json`,
authApiConfigModified
);
if (skipBuild) {
await spawn('yarn', ['api-report'], {
stdio: 'inherit'
});
} else {
// api-report is run as part of every build
await spawn(
'yarn',
[
'lerna',
'run',
'--scope',
'@firebase/*',
'--ignore',
'@firebase/*-compat',
'build'
],
{
stdio: 'inherit'
}
);
}
} finally {
console.log(`Restoring original auth api-extractor.json contents.`);
// Restore original auth api-extractor.json contents.
fs.writeFileSync(
`${projectRoot}/packages/auth/api-extractor.json`,
authApiConfigOriginal
);
// Restore original auth.api.md
fs.writeFileSync(
`${projectRoot}/common/api-review/auth.api.md`,
authApiReportOriginal
);
}
if (fs.existsSync(tmpDir)) {
console.log(`Removing old json temp dir: ${tmpDir}.`);
fs.rmSync(tmpDir, { recursive: true, force: true });
}
fs.mkdirSync(tmpDir);
// TODO: Throw error if path doesn't exist once all packages add markdown support.
const apiJsonDirectories = (
await mapWorkspaceToPackages([`${projectRoot}/packages/*`])
)
.map(path => `${path}/temp`)
.filter(path => fs.existsSync(path));
for (const dir of apiJsonDirectories) {
const paths = await new Promise<string[]>(resolve =>
glob(`${dir}/*.api.json`, (err, paths) => {
if (err) throw err;
resolve(paths);
})
);
if (paths.length === 0) {
throw Error(`*.api.json file is missing in ${dir}`);
}
// there will be only 1 api.json file
const fileName = paths[0].split('/').pop();
fs.copyFileSync(paths[0], `${tmpDir}/${fileName}`);
}
await spawn(
'yarn',
[
command,
'markdown',
'--input',
'temp',
'--output',
outputFolder,
'--project',
'js',
'--sort-functions',
PREFERRED_PARAMS.join(',')
],
{ stdio: 'inherit' }
);
if (forDevsite) {
const mdFiles = fs.readdirSync(join(projectRoot, outputFolder));
for (const mdFile of mdFiles) {
const fullPath = join(projectRoot, outputFolder, mdFile);
const content = fs.readFileSync(fullPath, 'utf-8');
fs.writeFileSync(
fullPath,
content.replace('\n# ', `\n${GOOGLE3_HEADER}\n# `)
);
}
}
await moveRulesUnitTestingDocs(outputFolder, command);
await removeExcludedDocs(outputFolder);
await removeExcludedPackageEntries(outputFolder);
}
/**
* Remove markdown files generated for excluded packages.
*/
async function removeExcludedDocs(mainDocsFolder: string) {
console.log('Removing excluded docs from', EXCLUDED_PACKAGES.join(', '));
for (const excludedPackage of EXCLUDED_PACKAGES) {
const excludedMdFiles = await new Promise<string[]>(resolve =>
glob(`${mainDocsFolder}/${excludedPackage}.*`, (err, paths) => {
if (err) throw err;
resolve(paths);
})
);
for (const excludedMdFile of excludedMdFiles) {
fs.unlinkSync(excludedMdFile);
}
}
}
/**
* Remove lines from index.md that link to excluded packages.
*/
async function removeExcludedPackageEntries(mainDocsFolder: string) {
console.log(`Removing ${EXCLUDED_PACKAGES.join(', ')} from index page.`);
const indexText = fs.readFileSync(`${mainDocsFolder}/index.md`, 'utf-8');
const indexTextLines = indexText.split('\n');
const newIndexTextLines = indexTextLines.filter(line => {
for (const excludedPackage of EXCLUDED_PACKAGES) {
if (line.includes(`[@firebase/${excludedPackage}]`)) {
return false;
}
}
return true;
});
fs.writeFileSync(
`${mainDocsFolder}/index.md`,
newIndexTextLines.join('\n'),
'utf-8'
);
}
// Create a docs-rut folder and move rules-unit-testing docs into it.
async function moveRulesUnitTestingDocs(
mainDocsFolder: string,
command: string
) {
const rulesOutputFolder = `${projectRoot}/docs-rut`;
console.log('Moving RUT docs to their own folder:', rulesOutputFolder);
if (!fs.existsSync(rulesOutputFolder)) {
fs.mkdirSync(rulesOutputFolder);
}
const rulesDocPaths = await new Promise<string[]>(resolve =>
glob(`${mainDocsFolder}/rules-unit-testing.*`, (err, paths) => {
if (err) throw err;
resolve(paths);
})
);
// Move rules-unit-testing docs into the new folder.
// These paths also need to be adjusted to point to a sibling directory.
for (const sourcePath of rulesDocPaths) {
let destinationPath = sourcePath.replace(mainDocsFolder, rulesOutputFolder);
const originalText = fs.readFileSync(sourcePath, 'utf-8');
const jsReferencePath = '/docs/reference/js';
let alteredPathText = originalText.replace(
/\.\/database/g,
`${jsReferencePath}/database`
);
alteredPathText = alteredPathText.replace(
/\.\/storage/g,
`${jsReferencePath}/storage`
);
alteredPathText = alteredPathText.replace(
/\.\/firestore/g,
`${jsReferencePath}/firestore`
);
fs.writeFileSync(destinationPath, alteredPathText);
}
}