Skip to content

Commit

Permalink
feat(docgen): proper event parsing for typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
iCrawl committed Jun 10, 2022
1 parent 0415300 commit d4b41dd
Show file tree
Hide file tree
Showing 15 changed files with 113 additions and 140 deletions.
22 changes: 12 additions & 10 deletions packages/docgen/src/documentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class Documentation {
case 'Class': {
this.classes.set(item.name, new DocumentedClass(item, config));
if (item.children) {
this.parse(item.children, item.name);
this.parse(item.children, item);
}
break;
}
Expand All @@ -51,7 +51,7 @@ export class Documentation {
case 'Enumeration':
this.typedefs.set(item.name, new DocumentedTypeDef(item, config));
if (item.children) {
this.parse(item.children, item.name);
this.parse(item.children, item);
}
break;

Expand Down Expand Up @@ -101,7 +101,7 @@ export class Documentation {
}
}

public parse(items: ChildTypes[] | DeclarationReflection[], memberOf = '') {
public parse(items: ChildTypes[] | DeclarationReflection[], p?: DeclarationReflection) {
if (this.config.typescript) {
const it = items as DeclarationReflection[];

Expand All @@ -114,24 +114,26 @@ export class Documentation {
break;
}
case 'Method': {
const event = p?.groups?.find((group) => group.title === 'Events');
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if ((event?.children as unknown as number[])?.includes(member.id)) {
item = new DocumentedEvent(member, this.config);
break;
}
item = new DocumentedMethod(member, this.config);
break;
}
case 'Property': {
item = new DocumentedMember(member, this.config);
break;
}
case 'Event': {
item = new DocumentedEvent(member, this.config);
break;
}
default: {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
console.warn(`- Unknown documentation kind "${member.kindString}" - \n${JSON.stringify(member)}\n`);
}
}

const parent = this.classes.get(memberOf) ?? this.interfaces.get(memberOf);
const parent = this.classes.get(p!.name) ?? this.interfaces.get(p!.name);
if (parent) {
if (item) {
parent.add(item);
Expand All @@ -154,8 +156,8 @@ export class Documentation {
path: dirname(member.sources?.[0]?.fileName ?? ''),
};

if (memberOf) {
info.push(`member of "${memberOf}"`);
if (p!.name) {
info.push(`member of "${p!.name}"`);
}
if (meta) {
info.push(
Expand Down
48 changes: 46 additions & 2 deletions packages/docgen/src/types/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import type { DeclarationReflection, SignatureReflection } from 'typedoc';
import { DocumentedItemMeta } from './item-meta.js';
import { DocumentedItem } from './item.js';
import { DocumentedParam } from './param.js';
import { DocumentedVarType } from './var-type.js';
import type { Event } from '../interfaces/index.js';
import { parseType } from '../util/parseType.js';

export class DocumentedEvent extends DocumentedItem<Event | DeclarationReflection> {
public override serializer() {
Expand All @@ -23,11 +25,27 @@ export class DocumentedEvent extends DocumentedItem<Event | DeclarationReflectio
.map((t) => t.content.find((c) => c.kind === 'text')?.text.trim())
: undefined;

// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const examples = signature.comment?.blockTags?.filter((t) => t.tag === '@example').length
? signature.comment.blockTags
.filter((t) => t.tag === '@example')
.map((t) => t.content.reduce((prev, curr) => (prev += curr.text), '').trim())
: undefined;

return {
name: signature.name,
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
name: signature.parameters?.[0]?.type?.value,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/prefer-nullish-coalescing
description: signature.comment?.summary?.reduce((prev, curr) => (prev += curr.text), '').trim() || undefined,
see,
access:
data.flags.isPrivate ||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
signature.comment?.blockTags?.some((t) => t.tag === '@private' || t.tag === '@internal')
? 'private'
: undefined,
examples,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
deprecated: signature.comment?.blockTags?.some((t) => t.tag === '@deprecated')
? signature.comment.blockTags
Expand All @@ -37,8 +55,34 @@ export class DocumentedEvent extends DocumentedItem<Event | DeclarationReflectio
: undefined,
// @ts-expect-error
params: signature.parameters
? (signature as SignatureReflection).parameters?.map((p) => new DocumentedParam(p, this.config).serialize())
? (signature as SignatureReflection).parameters
?.slice(1)
.map((p) => new DocumentedParam(p, this.config).serialize())
: undefined,
returns: signature.type
? [
new DocumentedVarType(
{
names: [parseType(signature.type)],
description:
signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((t) => t.tag === '@returns')
?.content.reduce((prev, curr) => (prev += curr.text), '')
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
.trim() || undefined,
},
this.config,
).serialize(),
]
: undefined,
returnsDescription:
signature.comment?.blockTags
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
?.find((t) => t.tag === '@returns')
?.content.reduce((prev, curr) => (prev += curr.text), '')
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
.trim() || undefined,
meta,
};
}
Expand Down
4 changes: 2 additions & 2 deletions packages/voice/__tests__/SpeakingMap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ describe('SpeakingMap', () => {
const starts: string[] = [];
const ends: string[] = [];

speaking.on('start', (userId) => void starts.push(userId));
speaking.on('end', (userId) => void ends.push(userId));
speaking.on('start', (userId: string) => void starts.push(userId));
speaking.on('end', (userId: string) => void ends.push(userId));

for (let i = 0; i < 10; i++) {
speaking.onPacket(userId);
Expand Down
1 change: 0 additions & 1 deletion packages/voice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
"@types/ws": "^8.5.3",
"discord-api-types": "^0.33.5",
"prism-media": "^1.3.2",
"tiny-typed-emitter": "^2.1.0",
"tslib": "^2.4.0",
"ws": "^8.8.0"
},
Expand Down
19 changes: 3 additions & 16 deletions packages/voice/src/VoiceConnection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/* eslint-disable @typescript-eslint/prefer-ts-expect-error */
import { EventEmitter } from 'node:events';
import type { GatewayVoiceServerUpdateDispatchData, GatewayVoiceStateUpdateDispatchData } from 'discord-api-types/v10';
import { TypedEmitter } from 'tiny-typed-emitter';
import type { CreateVoiceConnectionOptions } from '.';
import {
getVoiceConnection,
Expand All @@ -15,7 +14,7 @@ import type { VoiceWebSocket, VoiceUDPSocket } from './networking';
import { Networking, NetworkingState, NetworkingStatusCode } from './networking/Networking';
import { VoiceReceiver } from './receive';
import type { DiscordGatewayAdapterImplementerMethods } from './util/adapter';
import { Awaited, noop } from './util/util';
import { noop } from './util/util';

/**
* The various status codes a voice connection can hold at any one time.
Expand Down Expand Up @@ -162,21 +161,10 @@ export type VoiceConnectionState =
| VoiceConnectionReadyState
| VoiceConnectionDestroyedState;

export type VoiceConnectionEvents = {
error: (error: Error) => Awaited<void>;
debug: (message: string) => Awaited<void>;
stateChange: (oldState: VoiceConnectionState, newState: VoiceConnectionState) => Awaited<void>;
} & {
[status in VoiceConnectionStatus]: (
oldState: VoiceConnectionState,
newState: VoiceConnectionState & { status: status },
) => Awaited<void>;
};

/**
* A connection to the voice server of a Guild, can be used to play audio in voice channels.
*/
export class VoiceConnection extends TypedEmitter<VoiceConnectionEvents> {
export class VoiceConnection extends EventEmitter {
/**
* The number of consecutive rejoin attempts. Initially 0, and increments for each rejoin.
* When a connection is successfully established, it resets to 0.
Expand Down Expand Up @@ -673,7 +661,6 @@ export class VoiceConnection extends TypedEmitter<VoiceConnectionEvents> {
*
* @param subscription - The removed subscription
*/
// @ts-ignore
private onSubscriptionRemoved(subscription: PlayerSubscription) {
if (this.state.status !== VoiceConnectionStatus.Destroyed && this.state.subscription === subscription) {
this.state = {
Expand Down
32 changes: 11 additions & 21 deletions packages/voice/src/audio/AudioPlayer.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
/* eslint-disable @typescript-eslint/prefer-ts-expect-error */
import { TypedEmitter } from 'tiny-typed-emitter';
import EventEmitter from 'node:events';
import { AudioPlayerError } from './AudioPlayerError';
import type { AudioResource } from './AudioResource';
import { PlayerSubscription } from './PlayerSubscription';
import { addAudioPlayer, deleteAudioPlayer } from '../DataStore';
import { VoiceConnection, VoiceConnectionStatus } from '../VoiceConnection';
import { Awaited, noop } from '../util/util';
import { noop } from '../util/util';

// The Opus "silent" frame
export const SILENCE_FRAME = Buffer.from([0xf8, 0xff, 0xfe]);
Expand Down Expand Up @@ -151,18 +151,14 @@ export type AudioPlayerState =
| AudioPlayerPlayingState
| AudioPlayerPausedState;

export type AudioPlayerEvents = {
error: (error: AudioPlayerError) => Awaited<void>;
debug: (message: string) => Awaited<void>;
stateChange: (oldState: AudioPlayerState, newState: AudioPlayerState) => Awaited<void>;
subscribe: (subscription: PlayerSubscription) => Awaited<void>;
unsubscribe: (subscription: PlayerSubscription) => Awaited<void>;
} & {
[status in AudioPlayerStatus]: (
oldState: AudioPlayerState,
newState: AudioPlayerState & { status: status },
) => Awaited<void>;
};
export interface AudioPlayer extends EventEmitter {
/**
* Emitted when there is an error emitted from the audio resource played by the audio player
*
* @event
*/
on: (event: 'error', listener: (error: AudioPlayerError) => void) => this;
}

/**
* Stringifies an AudioPlayerState instance.
Expand All @@ -187,7 +183,7 @@ function stringifyState(state: AudioPlayerState) {
* The AudioPlayer drives the timing of playback, and therefore is unaffected by voice connections
* becoming unavailable. Its behavior in these scenarios can be configured.
*/
export class AudioPlayer extends TypedEmitter<AudioPlayerEvents> {
export class AudioPlayer extends EventEmitter {
/**
* The state that the AudioPlayer is in.
*/
Expand Down Expand Up @@ -372,12 +368,6 @@ export class AudioPlayer extends TypedEmitter<AudioPlayerEvents> {
// state if the resource is still being used.
const onStreamError = (error: Error) => {
if (this.state.status !== AudioPlayerStatus.Idle) {
/**
* Emitted when there is an error emitted from the audio resource played by the audio player
*
* @event AudioPlayer#error
* @type {AudioPlayerError}
*/
this.emit('error', new AudioPlayerError(error, this.state.resource));
}

Expand Down
1 change: 0 additions & 1 deletion packages/voice/src/audio/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ export {
AudioPlayerPausedState,
AudioPlayerPlayingState,
CreateAudioPlayerOptions,
AudioPlayerEvents,
} from './AudioPlayer';

export { AudioPlayerError } from './AudioPlayerError';
Expand Down
1 change: 0 additions & 1 deletion packages/voice/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export {
VoiceConnectionDisconnectReason,
VoiceConnectionReadyState,
VoiceConnectionSignallingState,
VoiceConnectionEvents,
} from './VoiceConnection';

export { JoinConfig, getVoiceConnection, getVoiceConnections, getGroups } from './DataStore';
28 changes: 14 additions & 14 deletions packages/voice/src/networking/Networking.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
/* eslint-disable @typescript-eslint/method-signature-style */
import { EventEmitter } from 'node:events';
import { VoiceOpcodes } from 'discord-api-types/voice/v4';
import { TypedEmitter } from 'tiny-typed-emitter';
import type { CloseEvent } from 'ws';
import { VoiceUDPSocket } from './VoiceUDPSocket';
import { VoiceWebSocket } from './VoiceWebSocket';
import * as secretbox from '../util/Secretbox';
import { Awaited, noop } from '../util/util';
import { noop } from '../util/util';

// The number of audio channels required by Discord
const CHANNELS = 2;
Expand Down Expand Up @@ -150,11 +151,16 @@ export interface ConnectionData {
*/
const nonce = Buffer.alloc(24);

export interface NetworkingEvents {
debug: (message: string) => Awaited<void>;
error: (error: Error) => Awaited<void>;
stateChange: (oldState: NetworkingState, newState: NetworkingState) => Awaited<void>;
close: (code: number) => Awaited<void>;
export interface Networking extends EventEmitter {
/**
* Debug event for Networking.
*
* @event
*/
on(event: 'debug', listener: (message: string) => void): this;
on(event: 'error', listener: (error: Error) => void): this;
on(event: 'stateChange', listener: (oldState: NetworkingState, newState: NetworkingState) => void): this;
on(event: 'close', listener: (code: number) => void): this;
}

/**
Expand Down Expand Up @@ -195,7 +201,7 @@ function randomNBit(n: number) {
/**
* Manages the networking required to maintain a voice connection and dispatch audio packets
*/
export class Networking extends TypedEmitter<NetworkingEvents> {
export class Networking extends EventEmitter {
private _state: NetworkingState;

/**
Expand Down Expand Up @@ -274,12 +280,6 @@ export class Networking extends TypedEmitter<NetworkingEvents> {
this._state = newState;
this.emit('stateChange', oldState, newState);

/**
* Debug event for Networking.
*
* @event Networking#debug
* @type {string}
*/
this.debug?.(`state change:\nfrom ${stringifyState(oldState)}\nto ${stringifyState(newState)}`);
}

Expand Down
12 changes: 2 additions & 10 deletions packages/voice/src/networking/VoiceUDPSocket.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { createSocket, Socket } from 'node:dgram';
import { EventEmitter } from 'node:events';
import { isIPv4 } from 'node:net';
import { TypedEmitter } from 'tiny-typed-emitter';
import type { Awaited } from '../util/util';

/**
* Stores an IP address and port. Used to store socket details for the local client as well as
Expand All @@ -17,13 +16,6 @@ interface KeepAlive {
timestamp: number;
}

export interface VoiceUDPSocketEvents {
error: (error: Error) => Awaited<void>;
close: () => Awaited<void>;
debug: (message: string) => Awaited<void>;
message: (message: Buffer) => Awaited<void>;
}

/**
* Parses the response from Discord to aid with local IP discovery.
*
Expand Down Expand Up @@ -61,7 +53,7 @@ const MAX_COUNTER_VALUE = 2 ** 32 - 1;
/**
* Manages the UDP networking for a voice connection.
*/
export class VoiceUDPSocket extends TypedEmitter<VoiceUDPSocketEvents> {
export class VoiceUDPSocket extends EventEmitter {
/**
* The underlying network Socket for the VoiceUDPSocket.
*/
Expand Down
Loading

0 comments on commit d4b41dd

Please sign in to comment.