fix: unsafe embed builder field normalization (#7418)

This commit is contained in:
Suneet Tipirneni
2022-02-07 05:52:10 -05:00
committed by GitHub
parent a921ec7dc5
commit b936103395
4 changed files with 22 additions and 9 deletions

View File

@@ -1,15 +1,12 @@
import type { APIMessageComponent, ComponentType } from 'discord-api-types/v9';
import type { JSONEncodable } from '../util/jsonEncodable';
/**
* Represents a discord component
*/
export interface Component {
export interface Component extends JSONEncodable<APIMessageComponent> {
/**
* The type of this component
*/
readonly type: ComponentType;
/**
* Converts this component to an API-compatible JSON object
*/
toJSON: () => APIMessageComponent;
}

View File

@@ -28,3 +28,5 @@ export * from './interactions/slashCommands/options/user';
export * as ContextMenuCommandAssertions from './interactions/contextMenuCommands/Assertions';
export * from './interactions/contextMenuCommands/ContextMenuCommandBuilder';
export * from './util/jsonEncodable';

View File

@@ -8,7 +8,7 @@ import type {
APIEmbedThumbnail,
APIEmbedVideo,
} from 'discord-api-types/v9';
import { Embed } from './Embed';
import type { JSONEncodable } from '../../util/jsonEncodable';
export interface AuthorOptions {
name: string;
@@ -21,7 +21,7 @@ export interface FooterOptions {
iconURL?: string;
}
export class UnsafeEmbed implements APIEmbed {
export class UnsafeEmbed implements APIEmbed, JSONEncodable<APIEmbed> {
/**
* An array of fields of this embed
*/
@@ -126,7 +126,7 @@ export class UnsafeEmbed implements APIEmbed {
* @param fields The fields to add
*/
public addFields(...fields: APIEmbedField[]): this {
this.fields.push(...Embed.normalizeFields(...fields));
this.fields.push(...UnsafeEmbed.normalizeFields(...fields));
return this;
}
@@ -138,7 +138,7 @@ export class UnsafeEmbed implements APIEmbed {
* @param fields The replacing field objects
*/
public spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {
this.fields.splice(index, deleteCount, ...Embed.normalizeFields(...fields));
this.fields.splice(index, deleteCount, ...UnsafeEmbed.normalizeFields(...fields));
return this;
}

View File

@@ -0,0 +1,14 @@
export interface JSONEncodable<T> {
/**
* Transforms this object to its JSON format
*/
toJSON: () => T;
}
/**
* Indicates if an object is encodable or not.
* @param maybeEncodable The object to check against
*/
export function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable<unknown> {
return maybeEncodable !== null && typeof maybeEncodable === 'object' && 'toJSON' in maybeEncodable;
}