-
Notifications
You must be signed in to change notification settings - Fork 924
/
Copy pathMarkdownDocumenterHelpers.ts
450 lines (407 loc) · 12.9 KB
/
MarkdownDocumenterHelpers.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
/**
* @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 {
DocPlainText,
DocLinkTag,
TSDocConfiguration,
DocParagraph,
DocNode,
DocBlock,
DocComment,
DocSection,
DocCodeSpan,
StandardTags,
DocNodeKind
} from '@microsoft/tsdoc';
import {
ApiItem,
ApiItemKind,
ApiParameterListMixin,
ApiPackage,
ApiReleaseTagMixin,
ReleaseTag,
ApiDocumentedItem,
ApiEntryPoint,
ApiStaticMixin,
ApiEnum
} from 'api-extractor-model-me';
import { DocEmphasisSpan } from '../nodes/DocEmphasisSpan';
import { DocHeading } from '../nodes/DocHeading';
import { DocTable } from '../nodes/DocTable';
import { Utilities } from '../utils/Utilities';
import { PackageName } from '@rushstack/node-core-library';
import { DocNoteBox } from '../nodes/DocNoteBox';
import { DocTableRow } from '../nodes/DocTableRow';
import { DocTableCell } from '../nodes/DocTableCell';
import { createHash } from 'crypto';
export function getLinkForApiItem(
apiItem: ApiItem,
addFileNameSuffix: boolean
) {
const fileName = getFilenameForApiItem(apiItem, addFileNameSuffix);
const headingAnchor = getHeadingAnchorForApiItem(apiItem);
return `./${fileName}#${headingAnchor}`;
}
export function getFilenameForApiItem(
apiItem: ApiItem,
addFileNameSuffix: boolean
): string {
if (apiItem.kind === ApiItemKind.Model) {
return 'index.md';
}
let baseName: string = '';
let multipleEntryPoints: boolean = false;
for (const hierarchyItem of apiItem.getHierarchy()) {
// For overloaded methods, add a suffix such as "MyClass.myMethod_2".
let qualifiedName: string = Utilities.getSafeFilenameForName(
hierarchyItem.displayName
);
if (ApiParameterListMixin.isBaseClassOf(hierarchyItem)) {
if (hierarchyItem.overloadIndex > 1) {
// Subtract one for compatibility with earlier releases of API Documenter.
// (This will get revamped when we fix GitHub issue #1308)
qualifiedName += `_${hierarchyItem.overloadIndex - 1}`;
}
}
switch (hierarchyItem.kind) {
case ApiItemKind.Model:
break;
case ApiItemKind.EntryPoint:
const packageName: string = hierarchyItem.parent!.displayName;
let entryPointName: string = PackageName.getUnscopedName(packageName);
if (multipleEntryPoints) {
entryPointName = `${PackageName.getUnscopedName(packageName)}/${
hierarchyItem.displayName
}`;
}
baseName = Utilities.getSafeFilenameForName(entryPointName);
break;
case ApiItemKind.Package:
baseName = Utilities.getSafeFilenameForName(
PackageName.getUnscopedName(hierarchyItem.displayName)
);
if ((hierarchyItem as ApiPackage).entryPoints.length > 1) {
multipleEntryPoints = true;
}
break;
case ApiItemKind.Namespace:
baseName += '.' + qualifiedName;
if (addFileNameSuffix) {
baseName += '_n';
}
break;
case ApiItemKind.Class:
case ApiItemKind.Interface:
baseName += '.' + qualifiedName;
break;
}
}
return baseName + '.md';
}
// TODO: handle namespace?
export function getHeadingAnchorForApiItem(apiItem: ApiItem): string {
const scopedName: string = lowercaseAndRemoveSymbols(
apiItem.getScopedNameWithinPackage()
);
switch (apiItem.kind) {
case ApiItemKind.Function:
return lowercaseAndRemoveSymbols(getFunctionOverloadAnchor(apiItem));
case ApiItemKind.Variable:
return `${scopedName}`;
case ApiItemKind.TypeAlias:
return `${scopedName}`;
case ApiItemKind.Enum:
return `${scopedName}`;
case ApiItemKind.Method:
case ApiItemKind.MethodSignature:
return `${scopedName}`;
case ApiItemKind.Property:
case ApiItemKind.PropertySignature:
return `${scopedName}`;
case ApiItemKind.Constructor:
case ApiItemKind.ConstructSignature:
return `${scopedName}`;
case ApiItemKind.Class:
return `${scopedName}_class`;
case ApiItemKind.Interface:
return `${scopedName}_interface`;
case ApiItemKind.Model:
return `api-reference`;
case ApiItemKind.Namespace:
return `${scopedName}_namespace`;
case ApiItemKind.Package:
const unscopedPackageName: string = lowercaseAndRemoveSymbols(
PackageName.getUnscopedName(apiItem.displayName)
);
return `${unscopedPackageName}_package`;
case ApiItemKind.EntryPoint:
const packageName: string = apiItem.parent!.displayName;
return lowercaseAndRemoveSymbols(
`${packageName}${apiItem.displayName && '/' + apiItem.displayName}`
);
case ApiItemKind.EnumMember:
return `${scopedName}_enummember`;
default:
throw new Error(
'Unsupported API item kind:3 ' + apiItem.kind + apiItem.displayName
);
}
}
/**
* Generates a unique link for a function. Example: "getArea_paramhashhere"
*/
function getFunctionOverloadAnchor(apiItem: ApiItem): string {
if (
ApiParameterListMixin.isBaseClassOf(apiItem) &&
apiItem.parameters.length > 0
) {
// Create a sha256 hash from the parameter names and types.
const hash = createHash('sha256');
apiItem.parameters.forEach(param =>
hash.update(`${param.name}:${param.parameterTypeExcerpt.text}`)
);
// Use the first 7 characters of the hash for an easier to read URL.
const paramHash = hash.digest('hex').substring(0, 7);
// Suffix the API item name with the paramHash to generate a unique
// anchor for function overloads
return apiItem.getScopedNameWithinPackage() + '_' + paramHash;
}
return apiItem.getScopedNameWithinPackage();
}
function lowercaseAndRemoveSymbols(input: string): string {
return input.replace(/[\.()]/g, '').toLowerCase();
}
export function createBetaWarning(configuration: TSDocConfiguration): DocNode {
const betaWarning: string =
'This API is provided as a preview for developers and may change' +
' based on feedback that we receive. Do not use this API in a production environment.';
return new DocNoteBox({ configuration }, [
new DocParagraph({ configuration }, [
new DocPlainText({ configuration, text: betaWarning })
])
]);
}
export function createRemarksSection(
apiItem: ApiItem,
configuration: TSDocConfiguration
): DocNode[] {
const nodes: DocNode[] = [];
if (apiItem instanceof ApiDocumentedItem) {
const tsdocComment: DocComment | undefined = apiItem.tsdocComment;
if (tsdocComment) {
// Write the @remarks block
if (tsdocComment.remarksBlock) {
nodes.push(...tsdocComment.remarksBlock.content.nodes);
}
}
}
return nodes;
}
export function createExampleSection(
apiItem: ApiItem,
configuration: TSDocConfiguration
): DocNode[] {
const nodes: DocNode[] = [];
if (apiItem instanceof ApiDocumentedItem) {
const tsdocComment: DocComment | undefined = apiItem.tsdocComment;
if (tsdocComment) {
// Write the @example blocks
const exampleBlocks: DocBlock[] = tsdocComment.customBlocks.filter(
x =>
x.blockTag.tagNameWithUpperCase ===
StandardTags.example.tagNameWithUpperCase
);
let exampleNumber: number = 1;
for (const exampleBlock of exampleBlocks) {
const heading: string =
exampleBlocks.length > 1 ? `Example ${exampleNumber}` : 'Example';
nodes.push(new DocHeading({ configuration, title: heading, level: 2 }));
nodes.push(...exampleBlock.content.nodes);
++exampleNumber;
}
}
}
return nodes;
}
export function createTitleCell(
apiItem: ApiItem,
configuration: TSDocConfiguration,
addFileNameSuffix: boolean
): DocTableCell {
return new DocTableCell({ configuration }, [
new DocParagraph({ configuration }, [
new DocLinkTag({
configuration,
tagName: '@link',
linkText: Utilities.getConciseSignature(apiItem),
urlDestination: getLinkForApiItem(apiItem, addFileNameSuffix)
})
])
]);
}
/**
* This generates a DocTableCell for an ApiItem. This includes the summary section, and release
* annotations for public preview APIs.
*
* @remarks
* We mostly assume that the input is an ApiDocumentedItem, but it's easier to perform this as a runtime
* check than to have each caller perform a type cast.
*/
export function createDescriptionCell(
apiItem: ApiItem,
configuration: TSDocConfiguration
): DocTableCell {
const section: DocSection = new DocSection({ configuration });
if (ApiReleaseTagMixin.isBaseClassOf(apiItem)) {
if (apiItem.releaseTag === ReleaseTag.Beta) {
section.appendNodesInParagraph([
new DocEmphasisSpan({ configuration, bold: true, italic: true }, [
new DocPlainText({ configuration, text: '(Public Preview)' })
]),
new DocPlainText({ configuration, text: ' ' })
]);
}
}
if (apiItem instanceof ApiDocumentedItem) {
if (apiItem.tsdocComment !== undefined) {
appendAndMergeSection(section, apiItem.tsdocComment.summarySection);
}
}
return new DocTableCell({ configuration }, section.nodes);
}
export function createModifiersCell(
apiItem: ApiItem,
configuration: TSDocConfiguration
): DocTableCell {
const section: DocSection = new DocSection({ configuration });
if (ApiStaticMixin.isBaseClassOf(apiItem)) {
if (apiItem.isStatic) {
section.appendNodeInParagraph(
new DocCodeSpan({ configuration, code: 'static' })
);
}
}
return new DocTableCell({ configuration }, section.nodes);
}
function appendAndMergeSection(
output: DocSection,
docSection: DocSection
): void {
let firstNode: boolean = true;
for (const node of docSection.nodes) {
if (firstNode) {
if (node.kind === DocNodeKind.Paragraph) {
output.appendNodesInParagraph(node.getChildNodes());
firstNode = false;
continue;
}
}
firstNode = false;
output.appendNode(node);
}
}
export function createThrowsSection(
apiItem: ApiItem,
configuration: TSDocConfiguration,
parentHeadingLevel: number
): DocNode[] {
const output: DocNode[] = [];
if (apiItem instanceof ApiDocumentedItem) {
const tsdocComment: DocComment | undefined = apiItem.tsdocComment;
if (tsdocComment) {
// Write the @throws blocks
const throwsBlocks: DocBlock[] = tsdocComment.customBlocks.filter(
x =>
x.blockTag.tagNameWithUpperCase ===
StandardTags.throws.tagNameWithUpperCase
);
if (throwsBlocks.length > 0) {
const heading: string = 'Exceptions';
output.push(
new DocHeading({
configuration,
title: heading,
level: parentHeadingLevel + 1
})
);
for (const throwsBlock of throwsBlocks) {
output.push(...throwsBlock.content.nodes);
}
}
}
}
return output;
}
export function createEntryPointTitleCell(
apiItem: ApiEntryPoint,
configuration: TSDocConfiguration,
addFileNameSuffix: boolean
): DocTableCell {
return new DocTableCell({ configuration }, [
new DocParagraph({ configuration }, [
new DocLinkTag({
configuration,
tagName: '@link',
linkText: `/${apiItem.displayName}`,
urlDestination: getLinkForApiItem(apiItem, addFileNameSuffix)
})
])
]);
}
/**
* GENERATE PAGE: ENUM
*/
export function createEnumTables(
apiEnum: ApiEnum,
configuration: TSDocConfiguration
): DocNode[] {
const output: DocNode[] = [];
const enumMembersTable: DocTable = new DocTable({
configuration,
headerTitles: ['Member', 'Value', 'Description']
});
for (const apiEnumMember of apiEnum.members) {
enumMembersTable.addRow(
new DocTableRow({ configuration }, [
new DocTableCell({ configuration }, [
new DocParagraph({ configuration }, [
new DocPlainText({
configuration,
text: Utilities.getConciseSignature(apiEnumMember)
})
])
]),
new DocTableCell({ configuration }, [
new DocParagraph({ configuration }, [
new DocCodeSpan({
configuration,
code: apiEnumMember.initializerExcerpt.text
})
])
]),
createDescriptionCell(apiEnumMember, configuration)
])
);
}
if (enumMembersTable.rows.length > 0) {
output.push(
new DocHeading({ configuration, title: 'Enumeration Members' })
);
output.push(enumMembersTable);
}
return output;
}