feat: mainlib docs on new website (#9930)

* fix(ExceptText): don't display import("d..-types/v10"). in return type

* Squashed 'packages/api-extractor-model/' content from commit 39ecb196c

git-subtree-dir: packages/api-extractor-model
git-subtree-split: 39ecb196ca210bdf84ba6c9cadb1bb93571849d7

* Squashed 'packages/api-extractor/' content from commit 341ad6c51

git-subtree-dir: packages/api-extractor
git-subtree-split: 341ad6c51b01656d4f73b74ad4bdb3095f9262c4

* feat(api-extractor): add api-extractor and -model

* fix: package.json docs script

* fix(SourcLink): use <> instead of function syntax

* fix: make packages private

* fix: rest params showing in docs, added labels

* fix: missed two files

* feat: merge docs.json from docgen and docs.api.json

* fix: cpy-cli & pnpm-lock

* fix: increase icon size

* fix: icon size again

* feat: run both docs on mainlib

* chore: website fixes

* fix: more website fixes

* fix: tests and dev database script

* chore: comment out old docs

* fix: increase max fetch cache

* fix: env should always be a string

* fix: try to reapply patches

* fix: remove prepare for docgen

* fix: temporary cosmetic fixes

* fix: horizontal scroll

* feat: generate index for new docs

---------

Co-authored-by: Noel <buechler.noel@outlook.com>
This commit is contained in:
Qjuh
2023-11-08 10:16:54 +01:00
committed by GitHub
parent f713e47b0a
commit da455bceea
63 changed files with 1877 additions and 253 deletions

View File

@@ -1,4 +1,4 @@
# @microsoft/api-extractor-model
# @discordjs/api-extractor-model
Use this library to read and write \*.api.json files as defined by the [API Extractor](https://api-extractor.com/) tool.
These files are used to generate a documentation website for your TypeScript package. The files store the
@@ -60,7 +60,7 @@ a namespace containing static members of the class.
## Links
- [CHANGELOG.md](https://github.com/microsoft/rushstack/blob/main/libraries/api-extractor-model/CHANGELOG.md) - Find
- [CHANGELOG.md](https://github.com/discordjs/discord.js/blob/main/packages/api-extractor-model/CHANGELOG.md) - Find
out what's new in the latest version
- [API Reference](https://rushstack.io/pages/api/api-extractor-model/)

View File

@@ -58,12 +58,13 @@ export type { Constructor, PropertiesOf } from './mixins/Mixin.js';
// model
export { type IApiCallSignatureOptions, ApiCallSignature } from './model/ApiCallSignature.js';
export { type IApiClassOptions, ApiClass } from './model/ApiClass.js';
export { type IApiClassOptions, ApiClass, type IExcerptTokenRangeWithTypeParameters } from './model/ApiClass.js';
export { type IApiConstructorOptions, ApiConstructor } from './model/ApiConstructor.js';
export { type IApiConstructSignatureOptions, ApiConstructSignature } from './model/ApiConstructSignature.js';
export { type IApiEntryPointOptions, ApiEntryPoint } from './model/ApiEntryPoint.js';
export { type IApiEnumOptions, ApiEnum } from './model/ApiEnum.js';
export { type IApiEnumMemberOptions, ApiEnumMember, EnumMemberOrder } from './model/ApiEnumMember.js';
export { type IApiEventOptions, ApiEvent } from './model/ApiEvent.js';
export { type IApiFunctionOptions, ApiFunction } from './model/ApiFunction.js';
export { type IApiIndexSignatureOptions, ApiIndexSignature } from './model/ApiIndexSignature.js';
export { type IApiInterfaceOptions, ApiInterface } from './model/ApiInterface.js';

View File

@@ -8,6 +8,7 @@ import { ApiParameterListMixin } from '../mixins/ApiParameterListMixin.js';
import type { Constructor, PropertiesOf } from '../mixins/Mixin.js';
import type { ApiModel } from '../model/ApiModel.js';
import type { ApiPackage } from '../model/ApiPackage.js';
import type { DocgenJson } from '../model/Deserializer';
import type { DeserializerContext } from '../model/DeserializerContext.js';
/**
@@ -24,6 +25,7 @@ export enum ApiItemKind {
EntryPoint = 'EntryPoint',
Enum = 'Enum',
EnumMember = 'EnumMember',
Event = 'Event',
Function = 'Function',
IndexSignature = 'IndexSignature',
Interface = 'Interface',
@@ -111,6 +113,12 @@ export class ApiItem {
return deserializerModule.Deserializer.deserialize(context, jsonObject);
}
public static deserializeDocgen(jsonObject: DocgenJson, _package: string): ApiItem {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports, @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
const deserializerModule: typeof import('../model/Deserializer') = require('../model/Deserializer');
return deserializerModule.Deserializer.deserializeDocgen(jsonObject, _package);
}
/**
* @virtual
*/

View File

@@ -3,6 +3,7 @@
import type { DeclarationReference } from '@microsoft/tsdoc/lib-commonjs/beta/DeclarationReference.js';
import { InternalError } from '@rushstack/node-core-library';
import type { ApiDeclaredItem } from '../index.js';
import {
ApiItem,
apiItem_onParentChanged,
@@ -36,6 +37,11 @@ export interface IApiItemContainerJson extends IApiItemJson {
preserveMemberOrder?: boolean;
}
interface IMappedTypeParameters {
item: ApiItem;
mappedTypeParameters: Map<string, string>;
}
const _members: unique symbol = Symbol('ApiItemContainerMixin._members');
const _membersSorted: unique symbol = Symbol('ApiItemContainerMixin._membersSorted');
const _membersByContainerKey: unique symbol = Symbol('ApiItemContainerMixin._membersByContainerKey');
@@ -299,23 +305,76 @@ export function ApiItemContainerMixin<TBaseClass extends IApiItemConstructor>(
}
}
// The Deserializer class is coupled with a ton of other classes, so we delay loading it
// to avoid ES5 circular imports.
// *eslint-disable-next-line @typescript-eslint/consistent-type-imports, @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
// const deserializerModule: typeof import('../model/Deserializer') = require('../model/Deserializer');
const membersByName: Map<string, ApiItem[]> = new Map();
const membersByKind: Map<ApiItemKind, ApiItem[]> = new Map();
const toVisit: ApiItem[] = [];
let next: ApiItem | undefined = this;
const toVisit: IMappedTypeParameters[] = [];
let next: IMappedTypeParameters | undefined = { item: this, mappedTypeParameters: new Map() };
while (next) {
const membersToAdd: ApiItem[] = [];
while (next?.item) {
const membersToAdd: ApiItem[] = []; /*
const typeParams = next.mappedTypeParameters;
const context: DeserializerContext = {
apiJsonFilename: '',
toolPackage: '',
toolVersion: '',
versionToDeserialize: ApiJsonSchemaVersion.LATEST,
tsdocConfiguration: new TSDocConfiguration(),
}; */
// For each member, check to see if we've already seen a member with the same name
// previously in the inheritance tree. If so, we know we won't inherit it, and thus
// do not add it to our `membersToAdd` array.
for (const member of next.members) {
for (const member of next.item.members) {
// We add the to-be-added members to an intermediate array instead of immediately
// to the maps themselves to support method overloads with the same name.
if (ApiNameMixin.isBaseClassOf(member)) {
if (!membersByName.has(member.name)) {
// This was supposed to replace type parameters with their assigned values in inheritance, but doesn't work yet
/*
if (
ApiTypeParameterListMixin.isBaseClassOf(member) &&
member.typeParameters.some((param) => typeParams.has(param.name))
) {
const jsonObject: Partial<IApiItemJson> = {};
member.serializeInto(jsonObject);
member = deserializerModule.Deserializer.deserialize(context, {
...jsonObject,
typeParameters: (jsonObject as IApiTypeParameterListMixinJson).typeParameters.map(
({ typeParameterName, constraintTokenRange, defaultTypeTokenRange }) => ({
typeParameterName: typeParams.get(typeParameterName) ?? typeParameterName,
defaultTypeTokenRange,
constraintTokenRange,
}),
),
} as IApiTypeParameterListMixinJson);
}
if (ApiReturnTypeMixin.isBaseClassOf(member)) {
const jsonObject: Partial<IApiItemJson> = {};
member.serializeInto(jsonObject);
member = deserializerModule.Deserializer.deserialize(context, {
...(jsonObject as IApiReturnTypeMixinJson),
excerptTokens: (jsonObject as IApiDeclaredItemJson).excerptTokens.map((token) =>
token.kind === ExcerptTokenKind.Content
? {
kind: ExcerptTokenKind.Content,
text: [...typeParams.keys()].reduce(
(tok, typ) => tok.replaceAll(new RegExp(`\b${typ}\b`, 'g'), typeParams.get(typ)!),
token.text,
),
}
: token,
),
} as IApiReturnTypeMixinJson);
member[apiItem_onParentChanged](next.item);
} // */
membersToAdd.push(member);
}
} else if (!membersByKind.has(member.kind)) {
@@ -336,18 +395,18 @@ export function ApiItemContainerMixin<TBaseClass extends IApiItemConstructor>(
}
// Interfaces can extend multiple interfaces, so iterate through all of them.
const extendedItems: ApiItem[] = [];
const extendedItems: IMappedTypeParameters[] = [];
let extendsTypes: readonly HeritageType[] | undefined;
switch (next.kind) {
switch (next.item.kind) {
case ApiItemKind.Class: {
const apiClass: ApiClass = next as ApiClass;
const apiClass: ApiClass = next.item as ApiClass;
extendsTypes = apiClass.extendsType ? [apiClass.extendsType] : [];
break;
}
case ApiItemKind.Interface: {
const apiInterface: ApiInterface = next as ApiInterface;
const apiInterface: ApiInterface = next.item as ApiInterface;
extendsTypes = apiInterface.extendsTypes;
break;
}
@@ -359,7 +418,7 @@ export function ApiItemContainerMixin<TBaseClass extends IApiItemConstructor>(
if (extendsTypes === undefined) {
messages.push({
messageId: FindApiItemsMessageId.UnsupportedKind,
text: `Unable to analyze references of API item ${next.displayName} because it is of unsupported kind ${next.kind}`,
text: `Unable to analyze references of API item ${next.item.displayName} because it is of unsupported kind ${next.item.kind}`,
});
maybeIncompleteResult = true;
next = toVisit.shift();
@@ -387,7 +446,7 @@ export function ApiItemContainerMixin<TBaseClass extends IApiItemConstructor>(
if (!firstReferenceToken) {
messages.push({
messageId: FindApiItemsMessageId.ExtendsClauseMissingReference,
text: `Unable to analyze extends clause ${extendsType.excerpt.text} of API item ${next.displayName} because no canonical reference was found`,
text: `Unable to analyze extends clause ${extendsType.excerpt.text} of API item ${next.item.displayName} because no canonical reference was found`,
});
maybeIncompleteResult = true;
continue;
@@ -397,7 +456,7 @@ export function ApiItemContainerMixin<TBaseClass extends IApiItemConstructor>(
if (!apiModel) {
messages.push({
messageId: FindApiItemsMessageId.NoAssociatedApiModel,
text: `Unable to analyze references of API item ${next.displayName} because it is not associated with an ApiModel`,
text: `Unable to analyze references of API item ${next.item.displayName} because it is not associated with an ApiModel`,
});
maybeIncompleteResult = true;
continue;
@@ -413,13 +472,24 @@ export function ApiItemContainerMixin<TBaseClass extends IApiItemConstructor>(
if (!apiItem) {
messages.push({
messageId: FindApiItemsMessageId.DeclarationResolutionFailed,
text: `Unable to resolve declaration reference within API item ${next.displayName}: ${apiItemResult.errorMessage}`,
text: `Unable to resolve declaration reference within API item ${next.item.displayName}: ${apiItemResult.errorMessage}`,
});
maybeIncompleteResult = true;
continue;
}
extendedItems.push(apiItem);
const mappedTypeParameters: Map<string, string> = new Map();
if (
(apiItem.kind === ApiItemKind.Class || apiItem.kind === ApiItemKind.Interface) &&
next.item.kind === ApiItemKind.Class
) {
for (const [index, typeParameter] of extendsType.typeParameters.entries()) {
const key = (apiItem as ApiClass | ApiInterface).typeParameters[index]?.name ?? '';
mappedTypeParameters.set(key, typeParameter);
}
}
extendedItems.push({ item: apiItem, mappedTypeParameters });
}
// For classes, this array will only have one item. For interfaces, there may be multiple items. Sort the array
@@ -440,7 +510,9 @@ export function ApiItemContainerMixin<TBaseClass extends IApiItemConstructor>(
//
// interface FooBar extends Foo, Bar {}
// ```
extendedItems.sort((x: ApiItem, y: ApiItem) => x.getSortKey().localeCompare(y.getSortKey()));
extendedItems.sort((x: IMappedTypeParameters, y: IMappedTypeParameters) =>
x.item.getSortKey().localeCompare(y.item.getSortKey()),
);
toVisit.push(...extendedItems);
next = toVisit.shift();

View File

@@ -147,7 +147,11 @@ export class Excerpt {
this.tokenRange.endIndex > this.tokens.length ||
this.tokenRange.startIndex > this.tokenRange.endIndex
) {
throw new Error('Invalid token range');
throw new Error(
`Invalid token range. length:${this.tokens.length}, start:${this.tokenRange.startIndex}, end:${
this.tokenRange.endIndex
}, ${this.tokens.map((token) => token.text)}`,
);
}
this.spannedTokens = this.tokens.slice(this.tokenRange.startIndex, this.tokenRange.endIndex);

View File

@@ -39,8 +39,12 @@ export interface IApiClassOptions
IApiDeclaredItemOptions,
IApiTypeParameterListMixinOptions,
IApiExportedMixinOptions {
extendsTokenRange: IExcerptTokenRange | undefined;
implementsTokenRanges: IExcerptTokenRange[];
extendsTokenRange: IExcerptTokenRangeWithTypeParameters | undefined;
implementsTokenRanges: IExcerptTokenRangeWithTypeParameters[];
}
export interface IExcerptTokenRangeWithTypeParameters extends IExcerptTokenRange {
typeParameters: string[];
}
export interface IApiClassJson
@@ -48,8 +52,8 @@ export interface IApiClassJson
IApiAbstractMixinJson,
IApiTypeParameterListMixinJson,
IApiExportedMixinJson {
extendsTokenRange?: IExcerptTokenRange;
implementsTokenRanges: IExcerptTokenRange[];
extendsTokenRange?: IExcerptTokenRangeWithTypeParameters | undefined;
implementsTokenRanges: IExcerptTokenRangeWithTypeParameters[];
}
/**
@@ -81,13 +85,18 @@ export class ApiClass extends ApiItemContainerMixin(
super(options);
if (options.extendsTokenRange) {
this.extendsType = new HeritageType(this.buildExcerpt(options.extendsTokenRange));
this.extendsType = new HeritageType(
this.buildExcerpt(options.extendsTokenRange),
options.extendsTokenRange.typeParameters,
);
} else {
this.extendsType = undefined;
}
for (const implementsTokenRange of options.implementsTokenRanges) {
this._implementsTypes.push(new HeritageType(this.buildExcerpt(implementsTokenRange)));
this._implementsTypes.push(
new HeritageType(this.buildExcerpt(implementsTokenRange), implementsTokenRange.typeParameters),
);
}
}
@@ -138,10 +147,16 @@ export class ApiClass extends ApiItemContainerMixin(
// Note that JSON does not support the "undefined" value, so we simply omit the field entirely if it is undefined
if (this.extendsType) {
jsonObject.extendsTokenRange = this.extendsType.excerpt.tokenRange;
jsonObject.extendsTokenRange = {
...this.extendsType.excerpt.tokenRange,
typeParameters: this.extendsType.typeParameters,
};
}
jsonObject.implementsTokenRanges = this.implementsTypes.map((x) => x.excerpt.tokenRange);
jsonObject.implementsTokenRanges = this.implementsTypes.map((x) => ({
...x.excerpt.tokenRange,
typeParameters: x.typeParameters,
}));
}
/**

View File

@@ -0,0 +1,72 @@
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import { DeclarationReference, type Component } from '@microsoft/tsdoc/lib-commonjs/beta/DeclarationReference.js';
import { type IApiDeclaredItemOptions, ApiDeclaredItem } from '../items/ApiDeclaredItem.js';
import { ApiItemKind, Navigation, Meaning } from '../items/ApiItem.js';
import { type IApiNameMixinOptions, ApiNameMixin } from '../mixins/ApiNameMixin.js';
import { type IApiParameterListMixinOptions, ApiParameterListMixin } from '../mixins/ApiParameterListMixin.js';
import { type IApiReleaseTagMixinOptions, ApiReleaseTagMixin } from '../mixins/ApiReleaseTagMixin.js';
/**
* Constructor options for {@link ApiEvent}.
*
* @public
*/
export interface IApiEventOptions
extends IApiNameMixinOptions,
IApiParameterListMixinOptions,
IApiReleaseTagMixinOptions,
IApiDeclaredItemOptions {}
/**
* Represents a TypeScript event declaration that belongs to an `ApiClass`.
*
* @remarks
*
* This is part of the {@link ApiModel} hierarchy of classes, which are serializable representations of
* API declarations.
*
* `ApiEvent` represents a emittable event such as the `ready` event in this example:
*
* ```ts
* export class Cliet extends EventEmitter {
* on(event: 'ready', ...args: [Client]): this { }
* }
* ```
* @public
*/
export class ApiEvent extends ApiNameMixin(ApiParameterListMixin(ApiReleaseTagMixin(ApiDeclaredItem))) {
public constructor(options: IApiEventOptions) {
super(options);
}
public static getContainerKey(name: string, overloadIndex: number): string {
return `${name}|${ApiItemKind.Event}|${overloadIndex}`;
}
/**
* @override
*/
public override get kind(): ApiItemKind {
return ApiItemKind.Event;
}
/**
* @override
*/
public override get containerKey(): string {
return ApiEvent.getContainerKey(this.name, this.overloadIndex);
}
/**
* @beta @override
*/
public override buildCanonicalReference(): DeclarationReference {
const nameComponent: Component = DeclarationReference.parseComponent(this.name);
return (this.parent ? this.parent.canonicalReference : DeclarationReference.empty())
.addNavigationStep(Navigation.Members as any, nameComponent)
.withMeaning(Meaning.Member as any)
.withOverloadIndex(this.overloadIndex);
}
}

View File

@@ -25,7 +25,7 @@ import {
type IApiTypeParameterListMixinJson,
ApiTypeParameterListMixin,
} from '../mixins/ApiTypeParameterListMixin.js';
import type { IExcerptTokenRange } from '../mixins/Excerpt.js';
import type { IExcerptTokenRangeWithTypeParameters } from './ApiClass.js';
import type { DeserializerContext } from './DeserializerContext.js';
import { HeritageType } from './HeritageType.js';
@@ -41,7 +41,7 @@ export interface IApiInterfaceOptions
IApiReleaseTagMixinOptions,
IApiDeclaredItemOptions,
IApiExportedMixinOptions {
extendsTokenRanges: IExcerptTokenRange[];
extendsTokenRanges: IExcerptTokenRangeWithTypeParameters[];
}
export interface IApiInterfaceJson
@@ -51,7 +51,7 @@ export interface IApiInterfaceJson
IApiReleaseTagMixinJson,
IApiDeclaredItemJson,
IApiExportedMixinJson {
extendsTokenRanges: IExcerptTokenRange[];
extendsTokenRanges: IExcerptTokenRangeWithTypeParameters[];
}
/**
@@ -79,7 +79,7 @@ export class ApiInterface extends ApiItemContainerMixin(
super(options);
for (const extendsTokenRange of options.extendsTokenRanges) {
this._extendsTypes.push(new HeritageType(this.buildExcerpt(extendsTokenRange)));
this._extendsTypes.push(new HeritageType(this.buildExcerpt(extendsTokenRange), extendsTokenRange.typeParameters));
}
}
@@ -127,7 +127,10 @@ export class ApiInterface extends ApiItemContainerMixin(
public override serializeInto(jsonObject: Partial<IApiInterfaceJson>): void {
super.serializeInto(jsonObject);
jsonObject.extendsTokenRanges = this.extendsTypes.map((x) => x.excerpt.tokenRange);
jsonObject.extendsTokenRanges = this.extendsTypes.map((x) => ({
...x.excerpt.tokenRange,
typeParameters: x.typeParameters,
}));
}
/**

View File

@@ -1,9 +1,24 @@
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import { TSDocConfiguration } from '@microsoft/tsdoc';
import type { IExcerptToken } from '../index.js';
import { ExcerptTokenKind } from '../index.js';
import type { IApiDeclaredItemJson } from '../items/ApiDeclaredItem.js';
import type { IApiDocumentedItemJson } from '../items/ApiDocumentedItem.js';
import { type IApiItemJson, type IApiItemOptions, type ApiItem, ApiItemKind } from '../items/ApiItem.js';
import type { IApiPropertyItemJson } from '../items/ApiPropertyItem.js';
import type { IApiAbstractMixinJson } from '../mixins/ApiAbstractMixin.js';
import type { IApiItemContainerJson } from '../mixins/ApiItemContainerMixin.js';
import type { IApiNameMixinJson } from '../mixins/ApiNameMixin.js';
import type { IApiOptionalMixinJson } from '../mixins/ApiOptionalMixin.js';
import type { IApiParameterListJson, IApiParameterOptions } from '../mixins/ApiParameterListMixin.js';
import type { IApiProtectedMixinJson } from '../mixins/ApiProtectedMixin.js';
import type { IApiReadonlyMixinJson } from '../mixins/ApiReadonlyMixin.js';
import type { IApiReleaseTagMixinJson } from '../mixins/ApiReleaseTagMixin.js';
import type { IApiReturnTypeMixinJson } from '../mixins/ApiReturnTypeMixin.js';
import type { IApiStaticMixinJson } from '../mixins/ApiStaticMixin.js';
import type { IApiTypeParameterListMixinJson } from '../mixins/ApiTypeParameterListMixin.js';
import { ApiCallSignature, type IApiCallSignatureOptions } from './ApiCallSignature.js';
import { ApiClass, type IApiClassOptions, type IApiClassJson } from './ApiClass.js';
import { ApiConstructSignature, type IApiConstructSignatureOptions } from './ApiConstructSignature.js';
@@ -11,6 +26,8 @@ import { ApiConstructor, type IApiConstructorOptions } from './ApiConstructor.js
import { ApiEntryPoint, type IApiEntryPointOptions } from './ApiEntryPoint.js';
import { ApiEnum, type IApiEnumOptions } from './ApiEnum.js';
import { ApiEnumMember, type IApiEnumMemberOptions } from './ApiEnumMember.js';
import type { IApiEventOptions } from './ApiEvent.js';
import { ApiEvent } from './ApiEvent.js';
import { ApiFunction, type IApiFunctionOptions } from './ApiFunction.js';
import { ApiIndexSignature, type IApiIndexSignatureOptions } from './ApiIndexSignature.js';
import { ApiInterface, type IApiInterfaceOptions, type IApiInterfaceJson } from './ApiInterface.js';
@@ -23,7 +40,313 @@ import { ApiProperty, type IApiPropertyOptions } from './ApiProperty.js';
import { ApiPropertySignature, type IApiPropertySignatureOptions } from './ApiPropertySignature.js';
import { ApiTypeAlias, type IApiTypeAliasOptions, type IApiTypeAliasJson } from './ApiTypeAlias.js';
import { ApiVariable, type IApiVariableOptions, type IApiVariableJson } from './ApiVariable.js';
import type { DeserializerContext } from './DeserializerContext.js';
import { ApiJsonSchemaVersion, type DeserializerContext } from './DeserializerContext.js';
type DocgenAccess = 'private' | 'protected' | 'public';
type DocgenScope = 'global' | 'instance' | 'static';
type DocgenDeprecated = boolean | string;
interface DocgenMetaJson {
file: string;
line: number;
path: string;
}
interface DocgenTypeJson {
names?: string[] | undefined;
}
interface DocgenVarJson {
description?: string;
nullable?: boolean;
types?: string[][][];
}
type DocgenVarTypeJson = DocgenVarJson | string[][][];
interface DocgenExceptionJson {
description?: string;
nullable?: boolean;
type: DocgenTypeJson;
}
interface DocgenExternalJson {
description: string;
meta: DocgenMetaJson;
name: string;
see?: string[];
}
interface DocgenTypedefJson {
access?: DocgenAccess;
deprecated?: DocgenDeprecated;
description: string;
meta: DocgenMetaJson;
name: string;
params?: DocgenParamJson[];
props?: DocgenParamJson[];
returns?: DocgenVarTypeJson[];
see?: string[];
type: DocgenVarTypeJson;
}
interface DocgenEventJson {
deprecated?: DocgenDeprecated;
description: string;
meta: DocgenMetaJson;
name: string;
params?: DocgenParamJson[];
see?: string[];
}
interface DocgenParamJson {
default?: string;
description: string;
name: string;
nullable?: boolean;
optional?: boolean;
type: DocgenVarTypeJson;
variable?: string;
}
interface DocgenConstructorJson {
access?: DocgenAccess;
description: string;
name: string;
params?: DocgenParamJson[];
see?: string[];
}
interface DocgenMethodJson {
abstract: boolean;
access?: DocgenAccess;
async?: boolean;
deprecated?: DocgenDeprecated;
description: string;
emits?: string[];
examples?: string[];
generator?: boolean;
implements?: string[];
inherited?: boolean;
inherits?: string;
meta: DocgenMetaJson;
name: string;
params?: DocgenParamJson[];
returns?: DocgenVarTypeJson[];
scope: DocgenScope;
see?: string[];
throws?: DocgenExceptionJson[];
}
interface DocgenPropertyJson {
abstract?: boolean;
access?: DocgenAccess;
default?: string;
deprecated?: DocgenDeprecated;
description: string;
meta: DocgenMetaJson;
name: string;
nullable?: boolean;
props?: DocgenPropertyJson[];
readonly?: boolean;
scope: DocgenScope;
see?: string[];
type: DocgenVarTypeJson;
}
interface DocgenClassJson {
abstract?: boolean;
access?: DocgenAccess;
construct: DocgenConstructorJson;
deprecated?: DocgenDeprecated | string;
description: string;
events?: DocgenEventJson[];
extends?: DocgenVarTypeJson;
implements?: DocgenVarTypeJson;
meta: DocgenMetaJson;
methods?: DocgenMethodJson[];
name: string;
props?: DocgenPropertyJson[];
see?: string[];
}
type DocgenInterfaceJson = DocgenClassJson;
export interface DocgenJson {
classes: DocgenClassJson[];
externals: DocgenExternalJson[];
functions: DocgenMethodJson[];
interfaces: DocgenInterfaceJson[];
meta: {
date: number;
format: number;
generator: string;
};
typedefs: DocgenTypedefJson[];
}
function formatVarType(type: DocgenVarTypeJson): string {
return (Array.isArray(type) ? type : type.types ?? []).map((t1) => t1.map((t2) => t2.join('')).join('')).join(' | ');
}
function getFirstType(type: DocgenVarTypeJson): string {
return (Array.isArray(type) ? type[0]?.[0]?.[0] : type.types?.[0]?.[0]?.[0]) ?? 'unknown';
}
// function mapEvent(_event: DocgenEventJson, _package: string, _parent: DocgenClassJson): void {}
function mapVarType(type: DocgenVarTypeJson, _package: string): IExcerptToken[] {
const mapper = Array.isArray(type) ? type : type.types ?? [];
return mapper.flatMap((typ) =>
typ.reduce<IExcerptToken[]>(
(arr, [_class, symbol]) => [
...arr,
{
kind: ExcerptTokenKind.Reference,
text: _class ?? 'unknown',
canonicalReference: `${_package}!${_class}:class`,
},
{ kind: ExcerptTokenKind.Content, text: symbol ?? '' },
],
[],
),
);
}
function mapProp(
prop: DocgenPropertyJson,
_package: string,
parent: DocgenClassJson | DocgenInterfaceJson,
): IApiNameMixinJson & IApiOptionalMixinJson & IApiPropertyItemJson & IApiReadonlyMixinJson & IApiReleaseTagMixinJson {
const mappedVarType = mapVarType(prop.type, _package);
return {
kind: ApiItemKind.Property,
name: prop.name,
isOptional: Boolean(prop.nullable),
isReadonly: Boolean(prop.readonly),
docComment: `/**\n * ${prop.description}\n${prop.see?.map((see) => ` * @see ${see}\n`).join('') ?? ''}${
prop.readonly ? ' * @readonly\n' : ''
} */`,
excerptTokens: [
{
kind: ExcerptTokenKind.Content,
text: `${prop.access} ${prop.scope === 'static' ? 'static ' : ''}${prop.readonly ? 'readonly ' : ''}${
prop.name
} :`,
},
...mappedVarType,
{
kind: ExcerptTokenKind.Reference,
text: formatVarType(prop.type),
canonicalReference: `${_package}!${getFirstType(prop.type)}:class`,
},
{ kind: ExcerptTokenKind.Content, text: ';' },
],
propertyTypeTokenRange: { startIndex: 1, endIndex: 1 + mappedVarType.length },
canonicalReference: `${_package}!${parent.name}#${prop.name}:member`,
releaseTag: prop.access === 'public' ? 'Public' : 'Internal',
fileLine: prop.meta.line,
fileUrlPath: `${prop.meta.path.slice(`packages/${_package}/`.length)}/${prop.meta.file}`,
};
}
function mapParam(
param: DocgenParamJson,
index: number,
_package: string,
paramTokens: number[],
): IApiParameterOptions {
return {
parameterName: param.name.startsWith('...') ? param.name.slice(3) : param.name,
isOptional: Boolean(param.optional),
isRest: param.name.startsWith('...'),
parameterTypeTokenRange: {
startIndex: 1 + index + paramTokens.slice(0, index).reduce((akk, num) => akk + num, 0),
endIndex: 1 + index + paramTokens.slice(0, index + 1).reduce((akk, num) => akk + num, 0),
},
};
}
interface IApiMethodJson
extends IApiAbstractMixinJson,
IApiDeclaredItemJson,
IApiNameMixinJson,
IApiOptionalMixinJson,
IApiParameterListJson,
IApiProtectedMixinJson,
IApiReleaseTagMixinJson,
IApiReturnTypeMixinJson,
IApiStaticMixinJson,
IApiTypeParameterListMixinJson {}
interface IApiConstructorJson
extends IApiParameterListJson,
IApiProtectedMixinJson,
IApiReleaseTagMixinJson,
IApiDeclaredItemJson {}
function mapMethod(method: DocgenMethodJson, _package: string, parent?: DocgenClassJson): IApiMethodJson {
const excerptTokens: IExcerptToken[] = [];
excerptTokens.push({
kind: ExcerptTokenKind.Content,
text: `${
method.scope === 'global'
? `export function ${method.name}(`
: `${method.access}${method.scope === 'static' ? ' static' : ''} ${method.name}(`
}${
method.params?.length
? `${method.params[0]!.name}${method.params[0]!.nullable || method.params[0]!.optional ? '?' : ''}`
: '): '
}`,
});
const paramTokens: number[] = [];
for (let index = 0; index < (method.params?.length ?? 0) - 1; index++) {
const newTokens = mapVarType(method.params![index]!.type, _package);
paramTokens.push(newTokens.length);
excerptTokens.push(...newTokens);
excerptTokens.push({
kind: ExcerptTokenKind.Content,
text: `, ${method.params![index + 1]!.name}${
method.params![index + 1]!.nullable || method.params![index + 1]!.optional ? '?' : ''
}: `,
});
}
if (method.params?.length) {
const newTokens = mapVarType(method.params[method.params.length - 1]!.type, _package);
paramTokens.push(newTokens.length);
excerptTokens.push(...newTokens);
excerptTokens.push({ kind: ExcerptTokenKind.Content, text: `): ` });
}
const returnTokens = mapVarType(method.returns?.[0] ?? [], _package);
excerptTokens.push(...returnTokens);
excerptTokens.push({ kind: ExcerptTokenKind.Content, text: ';' });
return {
kind: parent ? ApiItemKind.Method : ApiItemKind.Function,
name: method.name,
isAbstract: method.abstract,
isOptional: false,
isProtected: method.access === 'protected',
isStatic: method.scope === 'static',
canonicalReference: `${_package}!${parent ? `${parent.name}!${method.name}:member` : `${method.name}:function`}`,
overloadIndex: 1,
parameters: method.params?.map((param, index) => mapParam(param, index, _package, paramTokens)) ?? [],
releaseTag: method.access === 'public' ? 'Public' : 'Internal',
returnTypeTokenRange: method.returns?.length
? method.params?.length
? { startIndex: 2 + 2 * method.params.length, endIndex: 3 + 2 * method.params.length }
: { startIndex: 1, endIndex: 2 }
: { startIndex: 0, endIndex: 0 },
typeParameters: [],
docComment: `/**\n * ${method.description}\n${
method.params?.map((param) => ` * @param ${param.name} - ${param.description}\n`).join('') ?? ''
}${
method.returns?.length && !Array.isArray(method.returns[0]) ? ` * @returns ${method.returns[0]!.description}` : ''
} */`,
excerptTokens,
fileLine: method.meta.line,
fileUrlPath: `${method.meta.path.slice(`packages/${_package}/`.length)}/${method.meta.file}`,
};
}
export class Deserializer {
public static deserialize(context: DeserializerContext, jsonObject: IApiItemJson): ApiItem {
@@ -51,6 +374,9 @@ export class Deserializer {
case ApiItemKind.EnumMember:
ApiEnumMember.onDeserializeInto(options, context, jsonObject as IApiDeclaredItemJson);
return new ApiEnumMember(options as IApiEnumMemberOptions);
case ApiItemKind.Event:
ApiEvent.onDeserializeInto(options, context, jsonObject as IApiDeclaredItemJson);
return new ApiEvent(options as IApiEventOptions);
case ApiItemKind.Function:
ApiFunction.onDeserializeInto(options, context, jsonObject as IApiDeclaredItemJson);
return new ApiFunction(options as IApiFunctionOptions);
@@ -90,4 +416,162 @@ export class Deserializer {
throw new Error(`Failed to deserialize unsupported API item type ${JSON.stringify(jsonObject.kind)}`);
}
}
public static deserializeDocgen(jsonObject: DocgenJson, _package: string) {
const context: DeserializerContext = {
apiJsonFilename: 'docs.json',
tsdocConfiguration: new TSDocConfiguration(),
versionToDeserialize: ApiJsonSchemaVersion.V_1011,
toolPackage: jsonObject.meta.generator,
toolVersion: jsonObject.meta.format.toString(),
};
let members: (IApiClassJson | IApiInterfaceJson | IApiMethodJson | IApiTypeAliasJson)[] = [];
for (const _class of jsonObject.classes) {
const classMembers: (IApiConstructorJson | IApiMethodJson | IApiPropertyItemJson)[] = [
// ..._class.events.map((event) => mapEvent(event, _package, _class)),
...(_class.props?.map((prop) => mapProp(prop, _package, _class)) ?? []),
...(_class.methods?.map((method) => mapMethod(method, _package, _class)) ?? []),
];
if (_class.construct) {
const excerptTokens: IExcerptToken[] = [
{
kind: ExcerptTokenKind.Content,
text: `${_class.construct.access} constructor(${
_class.construct.params?.length ? `${_class.construct.params[0]?.name}: ` : ');'
}`,
},
];
const paramTokens: number[] = [];
for (let index = 0; index < (_class.construct.params?.length ?? 0) - 1; index++) {
const newTokens = mapVarType(_class.construct.params![index]!.type, _package);
paramTokens.push(newTokens.length);
excerptTokens.push(...newTokens);
excerptTokens.push({
kind: ExcerptTokenKind.Content,
text: `, ${_class.construct.params![index + 1]?.name}: `,
});
}
if (_class.construct.params?.length) {
const newTokens = mapVarType(_class.construct.params[_class.construct.params.length - 1]!.type, _package);
paramTokens.push(newTokens.length);
excerptTokens.push(...newTokens);
excerptTokens.push({ kind: ExcerptTokenKind.Content, text: ');' });
}
classMembers.unshift({
parameters:
_class.construct.params?.map((param, index) => mapParam(param, index, _package, paramTokens)) ?? [],
isProtected: _class.construct.access === 'protected',
releaseTag: _class.construct.access === 'public' ? 'Public' : 'Internal',
docComment: `/*+\n * ${_class.construct.description}\n${
_class.construct.params?.map((param) => ` * @param ${param.name} - ${param.description}\n`).join('') ?? ''
} */`,
excerptTokens,
kind: ApiItemKind.Constructor,
canonicalReference: `${_package}!${_class.name}:constructor`,
overloadIndex: 0,
});
}
const excerptTokens: IExcerptToken[] = [
{
kind: ExcerptTokenKind.Content,
text: `${_class.access === 'public' ? 'export ' : ''}declare class ${_class.name}${
_class.extends ? ' extends ' : _class.implements ? ' implements ' : ''
}`,
},
];
if (_class.extends)
excerptTokens.push({
kind: ExcerptTokenKind.Reference,
text: formatVarType(_class.extends) ?? '',
canonicalReference: `${_package}!${getFirstType(_class.extends) ?? ''}:class`,
});
if (_class.extends && _class.implements)
excerptTokens.push({ kind: ExcerptTokenKind.Content, text: ' implements ' });
if (_class.implements)
excerptTokens.push({
kind: ExcerptTokenKind.Reference,
text: formatVarType(_class.implements) ?? '',
canonicalReference: `${_package}!${getFirstType(_class.implements) ?? ''}:class`,
});
members.push({
members: classMembers,
kind: ApiItemKind.Class,
canonicalReference: `${_package}!${_class.name}:class`,
name: _class.name,
extendsTokenRange: _class.extends ? { startIndex: 1, endIndex: 2, typeParameters: [] } : undefined,
excerptTokens,
implementsTokenRanges: _class.implements
? [{ startIndex: _class.extends ? 3 : 1, endIndex: _class.extends ? 4 : 2, typeParameters: [] }]
: [],
typeParameters: [],
releaseTag: _class.access === 'public' ? 'Public' : 'Internal',
docComment: `/**\n * ${_class.description}\n${_class.see?.map((see) => ` * @see ${see}\n`).join('') ?? ''} */`,
isExported: _class.access === 'public',
isAbstract: Boolean(_class.abstract),
fileLine: _class.meta.line,
fileUrlPath: `${_class.meta.path.slice(`packages/${_package}/`.length)}/${_class.meta.file}`,
});
}
members = [
...members,
...jsonObject.functions.map((_func) => mapMethod(_func, _package)),
...jsonObject.interfaces.map((_interface) => ({
members: [
...(_interface.props?.map((prop) => mapProp(prop, _package, _interface)) ?? []),
...(_interface.methods?.map((method) => mapMethod(method, _package, _interface)) ?? []),
],
kind: ApiItemKind.Interface,
canonicalReference: `${_package}!${_interface.name}:interface`,
name: _interface.name,
extendsTokenRanges: [{ startIndex: 0, endIndex: 0, typeParameters: [] }],
excerptTokens: [
{
kind: ExcerptTokenKind.Content,
text: `${_interface.access === 'public' ? 'export ' : ''}interface ${_interface.name}`,
},
],
typeParameters: [],
releaseTag: _interface.access === 'public' ? 'Public' : 'Internal',
docComment: `/**\n * ${_interface.description}\n${
_interface.see?.map((see) => ` * @see ${see}\n`).join('') ?? ''
} */`,
isExported: _interface.access === 'public',
fileLine: _interface.meta.line,
fileUrlPath: `${_interface.meta.path.slice(`packages/${_package}/`.length)}/${_interface.meta.file}`,
})),
];
const reworkedJson: IApiDocumentedItemJson &
IApiItemContainerJson &
IApiNameMixinJson &
IApiPackageJson & { members: (IApiItemContainerJson & IApiNameMixinJson)[] } = {
projectFolderUrl: `https://github.com/discordjs/discord.js/tree/main/packages/${_package}`,
metadata: { ...context, tsdocConfig: context.tsdocConfiguration, schemaVersion: context.versionToDeserialize },
canonicalReference: `!${_package}`,
kind: ApiItemKind.Package,
name: _package,
members: [
{
members,
name: _package,
kind: ApiItemKind.EntryPoint,
canonicalReference: `${_package}!`,
},
],
docComment: '',
};
return Deserializer.deserialize(context, reworkedJson);
}
}

View File

@@ -38,7 +38,10 @@ export class HeritageType {
*/
public readonly excerpt: Excerpt;
public constructor(excerpt: Excerpt) {
public readonly typeParameters: string[];
public constructor(excerpt: Excerpt, typeParameters: string[]) {
this.excerpt = excerpt;
this.typeParameters = typeParameters;
}
}