fix rest types, collectors update, improve types (#266)

* feat: ctx types, delete threads cache, cache.channels.threads, changes to collectors, fix rest types

* fix: use apithreadchannel instead

* feat: revert threads relationship, fix collectors

* fix: cache thread when creating

* fix: unused

* feat: entitlement trasnformer

* fix: non-null assertion

* fix: circular?

* fix: collector onStop reason type

* fix: types

* feat: onPass method

* fix: undefined value
This commit is contained in:
MARCROCK22 2024-09-27 23:08:50 -04:00 committed by GitHub
parent 455ed12b0e
commit 13b8a32d42
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
58 changed files with 610 additions and 682 deletions

View File

@ -1,5 +1,5 @@
{ {
"$schema": "https://biomejs.dev/schemas/1.9.0/schema.json", "$schema": "https://biomejs.dev/schemas/1.9.2/schema.json",
"vcs": { "vcs": {
"enabled": true, "enabled": true,
"clientKind": "git", "clientKind": "git",

View File

@ -20,10 +20,10 @@
"author": "MARCROCK22", "author": "MARCROCK22",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@biomejs/biome": "1.9.1", "@biomejs/biome": "1.9.2",
"@commitlint/cli": "^19.5.0", "@commitlint/cli": "^19.5.0",
"@commitlint/config-conventional": "^19.5.0", "@commitlint/config-conventional": "^19.5.0",
"@types/node": "^22.5.5", "@types/node": "^22.6.1",
"husky": "^9.1.6", "husky": "^9.1.6",
"lint-staged": "^15.2.10", "lint-staged": "^15.2.10",
"typescript": "^5.6.2" "typescript": "^5.6.2"

100
pnpm-lock.yaml generated
View File

@ -9,17 +9,17 @@ importers:
.: .:
devDependencies: devDependencies:
'@biomejs/biome': '@biomejs/biome':
specifier: 1.9.1 specifier: 1.9.2
version: 1.9.1 version: 1.9.2
'@commitlint/cli': '@commitlint/cli':
specifier: ^19.5.0 specifier: ^19.5.0
version: 19.5.0(@types/node@22.5.5)(typescript@5.6.2) version: 19.5.0(@types/node@22.6.1)(typescript@5.6.2)
'@commitlint/config-conventional': '@commitlint/config-conventional':
specifier: ^19.5.0 specifier: ^19.5.0
version: 19.5.0 version: 19.5.0
'@types/node': '@types/node':
specifier: ^22.5.5 specifier: ^22.6.1
version: 22.5.5 version: 22.6.1
husky: husky:
specifier: ^9.1.6 specifier: ^9.1.6
version: 9.1.6 version: 9.1.6
@ -44,55 +44,55 @@ packages:
resolution: {integrity: sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==} resolution: {integrity: sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==}
engines: {node: '>=6.9.0'} engines: {node: '>=6.9.0'}
'@biomejs/biome@1.9.1': '@biomejs/biome@1.9.2':
resolution: {integrity: sha512-Ps0Rg0zg3B1zpx+zQHMz5b0n0PBNCAaXttHEDTVrJD5YXR6Uj3T+abTDgeS3wsu4z5i2whqcE1lZxGyWH4bZYg==} resolution: {integrity: sha512-4j2Gfwft8Jqp1X0qLYvK4TEy4xhTo4o6rlvJPsjPeEame8gsmbGQfOPBkw7ur+7/Z/f0HZmCZKqbMvR7vTXQYQ==}
engines: {node: '>=14.21.3'} engines: {node: '>=14.21.3'}
hasBin: true hasBin: true
'@biomejs/cli-darwin-arm64@1.9.1': '@biomejs/cli-darwin-arm64@1.9.2':
resolution: {integrity: sha512-js0brHswq/BoeKgfSEUJYOjUOlML6p65Nantti+PsoQ61u9+YVGIZ7325LK7iUpDH8KVJT+Bx7K2b/6Q//W1Pw==} resolution: {integrity: sha512-rbs9uJHFmhqB3Td0Ro+1wmeZOHhAPTL3WHr8NtaVczUmDhXkRDWScaxicG9+vhSLj1iLrW47itiK6xiIJy6vaA==}
engines: {node: '>=14.21.3'} engines: {node: '>=14.21.3'}
cpu: [arm64] cpu: [arm64]
os: [darwin] os: [darwin]
'@biomejs/cli-darwin-x64@1.9.1': '@biomejs/cli-darwin-x64@1.9.2':
resolution: {integrity: sha512-2zVyjUg5rN0k8XrytkubQWLbp2r/AS5wPhXs4vgVjvqbLnzo32EGX8p61gzroF2dH9DCUCfskdrigCGqNdEbpg==} resolution: {integrity: sha512-BlfULKijNaMigQ9GH9fqJVt+3JTDOSiZeWOQtG/1S1sa8Lp046JHG3wRJVOvekTPL9q/CNFW1NVG8J0JN+L1OA==}
engines: {node: '>=14.21.3'} engines: {node: '>=14.21.3'}
cpu: [x64] cpu: [x64]
os: [darwin] os: [darwin]
'@biomejs/cli-linux-arm64-musl@1.9.1': '@biomejs/cli-linux-arm64-musl@1.9.2':
resolution: {integrity: sha512-L/JmXKvhsZ1lTgqOr3tWkzuY/NRppdIscHeC9aaiR72WjnBgJS94mawl9BWmGB3aWBc0q6oSDWnBS7617EMMmA==} resolution: {integrity: sha512-ZATvbUWhNxegSALUnCKWqetTZqrK72r2RsFD19OK5jXDj/7o1hzI1KzDNG78LloZxftrwr3uI9SqCLh06shSZw==}
engines: {node: '>=14.21.3'} engines: {node: '>=14.21.3'}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
'@biomejs/cli-linux-arm64@1.9.1': '@biomejs/cli-linux-arm64@1.9.2':
resolution: {integrity: sha512-QgxwfnG+r2aer5RNGR67Ey91Tv7xXW8E9YckHhwuyWjdLEvKWkrSJrhVG/6ub0kVvTSNkYOuT/7/jMOFBuUbRA==} resolution: {integrity: sha512-T8TJuSxuBDeQCQzxZu2o3OU4eyLumTofhCxxFd3+aH2AEWVMnH7Z/c3QP1lHI5RRMBP9xIJeMORqDQ5j+gVZzw==}
engines: {node: '>=14.21.3'} engines: {node: '>=14.21.3'}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
'@biomejs/cli-linux-x64-musl@1.9.1': '@biomejs/cli-linux-x64-musl@1.9.2':
resolution: {integrity: sha512-gY+eFLIAW45v3WicQHicvjRfA0ntMZHx7h937bXwBMFNFoKmB6rMi6+fKQ6/hiS6juhsFxZdZIz20m15s49J6A==} resolution: {integrity: sha512-CjPM6jT1miV5pry9C7qv8YJk0FIZvZd86QRD3atvDgfgeh9WQU0k2Aoo0xUcPdTnoz0WNwRtDicHxwik63MmSg==}
engines: {node: '>=14.21.3'} engines: {node: '>=14.21.3'}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
'@biomejs/cli-linux-x64@1.9.1': '@biomejs/cli-linux-x64@1.9.2':
resolution: {integrity: sha512-F0INygtzI2L2n2R1KtYHGr3YWDt9Up1zrUluwembM+iJ1dXN3qzlSb7deFUsSJm4FaIPriqs6Xa56ukdQW6UeQ==} resolution: {integrity: sha512-T0cPk3C3Jr2pVlsuQVTBqk2qPjTm8cYcTD9p/wmR9MeVqui1C/xTVfOIwd3miRODFMrJaVQ8MYSXnVIhV9jTjg==}
engines: {node: '>=14.21.3'} engines: {node: '>=14.21.3'}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
'@biomejs/cli-win32-arm64@1.9.1': '@biomejs/cli-win32-arm64@1.9.2':
resolution: {integrity: sha512-7Jahxar3OB+aTPOgXisMJmMKMsjcK+UmdlG3UIOQjzN/ZFEsPV+GT3bfrVjZDQaCw/zes0Cqd7VTWFjFTC/+MQ==} resolution: {integrity: sha512-2x7gSty75bNIeD23ZRPXyox6Z/V0M71ObeJtvQBhi1fgrvPdtkEuw7/0wEHg6buNCubzOFuN9WYJm6FKoUHfhg==}
engines: {node: '>=14.21.3'} engines: {node: '>=14.21.3'}
cpu: [arm64] cpu: [arm64]
os: [win32] os: [win32]
'@biomejs/cli-win32-x64@1.9.1': '@biomejs/cli-win32-x64@1.9.2':
resolution: {integrity: sha512-liSRWjWzFhyG7s1jg/Bbv9FL+ha/CEd5tFO3+dFIJNplL4TnvAivtyfRVi/tu/pNjISbV1k9JwdBewtAKAgA0w==} resolution: {integrity: sha512-JC3XvdYcjmu1FmAehVwVV0SebLpeNTnO2ZaMdGCSOdS7f8O9Fq14T2P1gTG1Q29Q8Dt1S03hh0IdVpIZykOL8g==}
engines: {node: '>=14.21.3'} engines: {node: '>=14.21.3'}
cpu: [x64] cpu: [x64]
os: [win32] os: [win32]
@ -169,8 +169,8 @@ packages:
'@types/conventional-commits-parser@5.0.0': '@types/conventional-commits-parser@5.0.0':
resolution: {integrity: sha512-loB369iXNmAZglwWATL+WRe+CRMmmBPtpolYzIebFaX4YA3x+BEfLqhUAV9WanycKI3TG1IMr5bMJDajDKLlUQ==} resolution: {integrity: sha512-loB369iXNmAZglwWATL+WRe+CRMmmBPtpolYzIebFaX4YA3x+BEfLqhUAV9WanycKI3TG1IMr5bMJDajDKLlUQ==}
'@types/node@22.5.5': '@types/node@22.6.1':
resolution: {integrity: sha512-Xjs4y5UPO/CLdzpgR6GirZJx36yScjh73+2NlLlkFRSoQN8B0DpfXPdZGnvVmLRLOsqDpOfTNv7D9trgGhmOIA==} resolution: {integrity: sha512-V48tCfcKb/e6cVUigLAaJDAILdMP0fUW6BidkPK4GpGjXcfbnoHasCZDwz3N3yVt5we2RHm4XTQCpv0KJz9zqw==}
JSONStream@1.3.5: JSONStream@1.3.5:
resolution: {integrity: sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==} resolution: {integrity: sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==}
@ -741,46 +741,46 @@ snapshots:
js-tokens: 4.0.0 js-tokens: 4.0.0
picocolors: 1.1.0 picocolors: 1.1.0
'@biomejs/biome@1.9.1': '@biomejs/biome@1.9.2':
optionalDependencies: optionalDependencies:
'@biomejs/cli-darwin-arm64': 1.9.1 '@biomejs/cli-darwin-arm64': 1.9.2
'@biomejs/cli-darwin-x64': 1.9.1 '@biomejs/cli-darwin-x64': 1.9.2
'@biomejs/cli-linux-arm64': 1.9.1 '@biomejs/cli-linux-arm64': 1.9.2
'@biomejs/cli-linux-arm64-musl': 1.9.1 '@biomejs/cli-linux-arm64-musl': 1.9.2
'@biomejs/cli-linux-x64': 1.9.1 '@biomejs/cli-linux-x64': 1.9.2
'@biomejs/cli-linux-x64-musl': 1.9.1 '@biomejs/cli-linux-x64-musl': 1.9.2
'@biomejs/cli-win32-arm64': 1.9.1 '@biomejs/cli-win32-arm64': 1.9.2
'@biomejs/cli-win32-x64': 1.9.1 '@biomejs/cli-win32-x64': 1.9.2
'@biomejs/cli-darwin-arm64@1.9.1': '@biomejs/cli-darwin-arm64@1.9.2':
optional: true optional: true
'@biomejs/cli-darwin-x64@1.9.1': '@biomejs/cli-darwin-x64@1.9.2':
optional: true optional: true
'@biomejs/cli-linux-arm64-musl@1.9.1': '@biomejs/cli-linux-arm64-musl@1.9.2':
optional: true optional: true
'@biomejs/cli-linux-arm64@1.9.1': '@biomejs/cli-linux-arm64@1.9.2':
optional: true optional: true
'@biomejs/cli-linux-x64-musl@1.9.1': '@biomejs/cli-linux-x64-musl@1.9.2':
optional: true optional: true
'@biomejs/cli-linux-x64@1.9.1': '@biomejs/cli-linux-x64@1.9.2':
optional: true optional: true
'@biomejs/cli-win32-arm64@1.9.1': '@biomejs/cli-win32-arm64@1.9.2':
optional: true optional: true
'@biomejs/cli-win32-x64@1.9.1': '@biomejs/cli-win32-x64@1.9.2':
optional: true optional: true
'@commitlint/cli@19.5.0(@types/node@22.5.5)(typescript@5.6.2)': '@commitlint/cli@19.5.0(@types/node@22.6.1)(typescript@5.6.2)':
dependencies: dependencies:
'@commitlint/format': 19.5.0 '@commitlint/format': 19.5.0
'@commitlint/lint': 19.5.0 '@commitlint/lint': 19.5.0
'@commitlint/load': 19.5.0(@types/node@22.5.5)(typescript@5.6.2) '@commitlint/load': 19.5.0(@types/node@22.6.1)(typescript@5.6.2)
'@commitlint/read': 19.5.0 '@commitlint/read': 19.5.0
'@commitlint/types': 19.5.0 '@commitlint/types': 19.5.0
tinyexec: 0.3.0 tinyexec: 0.3.0
@ -827,7 +827,7 @@ snapshots:
'@commitlint/rules': 19.5.0 '@commitlint/rules': 19.5.0
'@commitlint/types': 19.5.0 '@commitlint/types': 19.5.0
'@commitlint/load@19.5.0(@types/node@22.5.5)(typescript@5.6.2)': '@commitlint/load@19.5.0(@types/node@22.6.1)(typescript@5.6.2)':
dependencies: dependencies:
'@commitlint/config-validator': 19.5.0 '@commitlint/config-validator': 19.5.0
'@commitlint/execute-rule': 19.5.0 '@commitlint/execute-rule': 19.5.0
@ -835,7 +835,7 @@ snapshots:
'@commitlint/types': 19.5.0 '@commitlint/types': 19.5.0
chalk: 5.3.0 chalk: 5.3.0
cosmiconfig: 9.0.0(typescript@5.6.2) cosmiconfig: 9.0.0(typescript@5.6.2)
cosmiconfig-typescript-loader: 5.0.0(@types/node@22.5.5)(cosmiconfig@9.0.0(typescript@5.6.2))(typescript@5.6.2) cosmiconfig-typescript-loader: 5.0.0(@types/node@22.6.1)(cosmiconfig@9.0.0(typescript@5.6.2))(typescript@5.6.2)
lodash.isplainobject: 4.0.6 lodash.isplainobject: 4.0.6
lodash.merge: 4.6.2 lodash.merge: 4.6.2
lodash.uniq: 4.5.0 lodash.uniq: 4.5.0
@ -888,9 +888,9 @@ snapshots:
'@types/conventional-commits-parser@5.0.0': '@types/conventional-commits-parser@5.0.0':
dependencies: dependencies:
'@types/node': 22.5.5 '@types/node': 22.6.1
'@types/node@22.5.5': '@types/node@22.6.1':
dependencies: dependencies:
undici-types: 6.19.8 undici-types: 6.19.8
@ -993,9 +993,9 @@ snapshots:
meow: 12.1.1 meow: 12.1.1
split2: 4.2.0 split2: 4.2.0
cosmiconfig-typescript-loader@5.0.0(@types/node@22.5.5)(cosmiconfig@9.0.0(typescript@5.6.2))(typescript@5.6.2): cosmiconfig-typescript-loader@5.0.0(@types/node@22.6.1)(cosmiconfig@9.0.0(typescript@5.6.2))(typescript@5.6.2):
dependencies: dependencies:
'@types/node': 22.5.5 '@types/node': 22.6.1
cosmiconfig: 9.0.0(typescript@5.6.2) cosmiconfig: 9.0.0(typescript@5.6.2)
jiti: 1.21.6 jiti: 1.21.6
typescript: 5.6.2 typescript: 5.6.2

View File

@ -36,72 +36,60 @@ import type {
RESTPutAPIApplicationRoleConnectionMetadataResult, RESTPutAPIApplicationRoleConnectionMetadataResult,
RESTPutAPIGuildApplicationCommandsPermissionsResult, RESTPutAPIGuildApplicationCommandsPermissionsResult,
} from '../../types'; } from '../../types';
import type { RestArguments, RestArgumentsNoBody } from '../api';
import type { ProxyRequestMethod } from '../Router';
import type { RestArguments } from '../api';
export interface ApplicationRoutes { export interface ApplicationRoutes {
applications: (id: string) => { applications: (id: string) => {
guilds: (id: string) => { guilds: (id: string) => {
commands: { commands: {
get( get(
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIApplicationGuildCommandsQuery>, args?: RestArgumentsNoBody<RESTGetAPIApplicationGuildCommandsQuery>,
): Promise<RESTGetAPIApplicationGuildCommandsResult>; ): Promise<RESTGetAPIApplicationGuildCommandsResult>;
post( post(
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIApplicationGuildCommandsJSONBody>, args: RestArguments<RESTPostAPIApplicationGuildCommandsJSONBody>,
): Promise<RESTPostAPIApplicationGuildCommandsResult>; ): Promise<RESTPostAPIApplicationGuildCommandsResult>;
put( put(
args?: RestArguments<ProxyRequestMethod.Put, RESTPutAPIApplicationGuildCommandsJSONBody>, args?: RestArguments<RESTPutAPIApplicationGuildCommandsJSONBody>,
): Promise<RESTPutAPIApplicationGuildCommandsResult>; ): Promise<RESTPutAPIApplicationGuildCommandsResult>;
permissions: { permissions: {
get( get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildApplicationCommandsPermissionsResult>;
args?: RestArguments<ProxyRequestMethod.Get>,
): Promise<RESTGetAPIGuildApplicationCommandsPermissionsResult>;
}; };
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIApplicationGuildCommandResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIApplicationGuildCommandResult>;
patch( patch(
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIApplicationGuildCommandJSONBody>, args: RestArguments<RESTPatchAPIApplicationGuildCommandJSONBody>,
): Promise<RESTPatchAPIApplicationGuildCommandResult>; ): Promise<RESTPatchAPIApplicationGuildCommandResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<never>; delete(args?: RestArgumentsNoBody): Promise<never>;
permissions: { permissions: {
get( get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildApplicationCommandsPermissionsResult>;
args?: RestArguments<ProxyRequestMethod.Get>,
): Promise<RESTGetAPIGuildApplicationCommandsPermissionsResult>;
put( put(
args?: RestArguments<ProxyRequestMethod.Put, RESTPutAPIApplicationCommandPermissionsJSONBody>, args?: RestArguments<RESTPutAPIApplicationCommandPermissionsJSONBody>,
): Promise<RESTPutAPIGuildApplicationCommandsPermissionsResult>; ): Promise<RESTPutAPIGuildApplicationCommandsPermissionsResult>;
}; };
}; };
}; };
}; };
commands: { commands: {
get( get(args?: RestArgumentsNoBody<RESTGetAPIApplicationCommandsQuery>): Promise<RESTGetAPIApplicationCommandsResult>;
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIApplicationCommandsQuery>, post(args: RestArguments<RESTPostAPIApplicationCommandsJSONBody>): Promise<RESTPostAPIApplicationCommandsResult>;
): Promise<RESTGetAPIApplicationCommandsResult>; put(args?: RestArguments<RESTPutAPIApplicationCommandsJSONBody>): Promise<RESTPutAPIApplicationCommandsResult>;
post(
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIApplicationCommandsJSONBody>,
): Promise<RESTPostAPIApplicationCommandsResult>;
put(
args?: RestArguments<ProxyRequestMethod.Put, RESTPutAPIApplicationCommandsJSONBody>,
): Promise<RESTPutAPIApplicationCommandsResult>;
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIApplicationCommandResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIApplicationCommandResult>;
patch( patch(
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIApplicationCommandJSONBody>, args: RestArguments<RESTPatchAPIApplicationCommandJSONBody>,
): Promise<RESTPatchAPIApplicationCommandResult>; ): Promise<RESTPatchAPIApplicationCommandResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<never>; delete(args?: RestArgumentsNoBody): Promise<never>;
}; };
}; };
'role-connections': { 'role-connections': {
metadata: { metadata: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIApplicationRoleConnectionMetadataResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIApplicationRoleConnectionMetadataResult>;
put( put(
args: RestArguments<ProxyRequestMethod.Put, RESTPutAPIApplicationRoleConnectionMetadataJSONBody>, args: RestArguments<RESTPutAPIApplicationRoleConnectionMetadataJSONBody>,
): Promise<RESTPutAPIApplicationRoleConnectionMetadataResult>; ): Promise<RESTPutAPIApplicationRoleConnectionMetadataResult>;
}; };
}; };
@ -109,38 +97,29 @@ export interface ApplicationRoutes {
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIApplicationEmojiResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIApplicationEmojiResult>;
patch( patch(args?: RestArguments<RESTPatchAPIApplicationEmojiJSONBody>): Promise<RESTPatchAPIApplicationEmojiResult>;
args?: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIApplicationEmojiJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIApplicationEmojiResult>;
): Promise<RESTPatchAPIApplicationEmojiResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIApplicationEmojiResult>;
}; };
get( get(
args?: RestArguments<ProxyRequestMethod.Get, Pick<RESTGetAPIApplicationEmojiResult, 'id'>>, args?: RestArgumentsNoBody<Pick<RESTGetAPIApplicationEmojiResult, 'id'>>,
): Promise<RESTGetAPIApplicationEmojisResult>; ): Promise<RESTGetAPIApplicationEmojisResult>;
post( post(args?: RestArguments<RESTPostAPIApplicationEmojiJSONBody>): Promise<RESTPostAPIApplicationEmojiResult>;
args?: RestArguments<ProxyRequestMethod.Post, RESTPostAPIApplicationEmojiJSONBody>,
): Promise<RESTPostAPIApplicationEmojiResult>;
}; };
entitlements: { entitlements: {
get( get(args?: RestArgumentsNoBody<RESTGetAPIEntitlementsQuery>): Promise<RESTGetAPIEntitlementsResult>;
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIEntitlementsQuery>, post(args: RestArguments<RESTPostAPIEntitlementBody>): Promise<RESTPostAPIEntitlementResult>;
): Promise<RESTGetAPIEntitlementsResult>;
post(
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIEntitlementBody>,
): Promise<RESTPostAPIEntitlementResult>;
( (
id: string, id: string,
): { ): {
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<never>; delete(args?: RestArgumentsNoBody): Promise<never>;
consume: { consume: {
post(args?: RestArguments<ProxyRequestMethod.Post>): Promise<never>; post(args?: RestArgumentsNoBody): Promise<never>;
}; };
}; };
}; };
skus: { skus: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPISKUsResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPISKUsResult>;
}; };
}; };
} }

View File

@ -56,22 +56,19 @@ import type {
RESTPutAPIChannelRecipientResult, RESTPutAPIChannelRecipientResult,
RESTPutAPIChannelThreadMembersResult, RESTPutAPIChannelThreadMembersResult,
} from '../../types'; } from '../../types';
import type { ProxyRequestMethod } from '../Router'; import type { RestArguments, RestArgumentsNoBody } from '../api';
import type { RestArguments } from '../api';
export interface ChannelRoutes { export interface ChannelRoutes {
channels(id: string): { channels(id: string): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIChannelResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIChannelResult>;
patch( patch(args: RestArguments<RESTPatchAPIChannelJSONBody>): Promise<RESTPatchAPIChannelResult>;
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIChannelJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIChannelResult>;
): Promise<RESTPatchAPIChannelResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIChannelResult>;
users: (id: '@me') => { users: (id: '@me') => {
threads: { threads: {
archived: { archived: {
private: { private: {
get( get(
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIChannelThreadsArchivedQuery>, args?: RestArgumentsNoBody<RESTGetAPIChannelThreadsArchivedQuery>,
): Promise<RESTGetAPIChannelUsersThreadsArchivedResult>; ): Promise<RESTGetAPIChannelUsersThreadsArchivedResult>;
}; };
}; };
@ -79,154 +76,127 @@ export interface ChannelRoutes {
}; };
'thread-members': { 'thread-members': {
get( get(
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIChannelThreadMembersQuery>, args?: RestArgumentsNoBody<RESTGetAPIChannelThreadMembersQuery>,
): Promise<RESTGetAPIChannelThreadMembersResult>; ): Promise<RESTGetAPIChannelThreadMembersResult>;
( (
id: '@me', id: '@me',
): { ): {
put(args?: RestArguments<ProxyRequestMethod.Put>): Promise<RESTPutAPIChannelThreadMembersResult>; put(args?: RestArgumentsNoBody): Promise<RESTPutAPIChannelThreadMembersResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIChannelThreadMembersResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIChannelThreadMembersResult>;
}; };
( (
id: string, id: string,
): { ): {
get( get(
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIChannelThreadMemberQuery>, args?: RestArgumentsNoBody<RESTGetAPIChannelThreadMemberQuery>,
): Promise<RESTGetAPIChannelThreadMemberResult>; ): Promise<RESTGetAPIChannelThreadMemberResult>;
put(args?: RestArguments<ProxyRequestMethod.Put>): Promise<RESTPutAPIChannelThreadMembersResult>; put(args?: RestArgumentsNoBody): Promise<RESTPutAPIChannelThreadMembersResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIChannelThreadMembersResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIChannelThreadMembersResult>;
}; };
}; };
threads: { threads: {
post( post(
args: RestArguments< args: RestArguments<RESTPostAPIChannelThreadsJSONBody | RESTPostAPIGuildForumThreadsJSONBody>,
ProxyRequestMethod.Post,
RESTPostAPIChannelThreadsJSONBody | RESTPostAPIGuildForumThreadsJSONBody
>,
): Promise<RESTPostAPIChannelThreadsResult>; ): Promise<RESTPostAPIChannelThreadsResult>;
archived: { archived: {
public: { public: {
get( get(
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIChannelThreadsArchivedQuery>, args?: RestArgumentsNoBody<RESTGetAPIChannelThreadsArchivedQuery>,
): Promise<RESTGetAPIChannelThreadsArchivedPublicResult>; ): Promise<RESTGetAPIChannelThreadsArchivedPublicResult>;
}; };
private: { private: {
get( get(
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIChannelThreadsArchivedQuery>, args?: RestArgumentsNoBody<RESTGetAPIChannelThreadsArchivedQuery>,
): Promise<RESTGetAPIChannelThreadsArchivedPrivateResult>; ): Promise<RESTGetAPIChannelThreadsArchivedPrivateResult>;
}; };
}; };
}; };
recipients: (id: string) => { recipients: (id: string) => {
put( put(args?: RestArguments<RESTPutAPIChannelRecipientJSONBody>): Promise<RESTPutAPIChannelRecipientResult>;
args?: RestArguments<ProxyRequestMethod.Put, RESTPutAPIChannelRecipientJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIChannelRecipientResult>;
): Promise<RESTPutAPIChannelRecipientResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIChannelRecipientResult>;
}; };
pins: { pins: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIChannelPinsResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIChannelPinsResult>;
( (
id: string, id: string,
): { ): {
put(args?: RestArguments<ProxyRequestMethod.Put>): Promise<RESTPutAPIChannelPinResult>; put(args?: RestArgumentsNoBody): Promise<RESTPutAPIChannelPinResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIChannelPinResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIChannelPinResult>;
}; };
}; };
followers: { followers: {
post( post(args: RestArguments<RESTPostAPIChannelFollowersJSONBody>): Promise<RESTPostAPIChannelFollowersResult>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIChannelFollowersJSONBody>,
): Promise<RESTPostAPIChannelFollowersResult>;
}; };
permissions: (id: string) => { permissions: (id: string) => {
put( put(args?: RestArguments<RESTPutAPIChannelPermissionJSONBody>): Promise<RESTPutAPIChannelPermissionResult>;
args?: RestArguments<ProxyRequestMethod.Put, RESTPutAPIChannelPermissionJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIChannelPermissionResult>;
): Promise<RESTPutAPIChannelPermissionResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIChannelPermissionResult>;
}; };
invites: { invites: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIChannelInvitesResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIChannelInvitesResult>;
post( post(args: RestArguments<RESTPostAPIChannelInviteJSONBody>): Promise<RESTPostAPIChannelInviteResult>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIChannelInviteJSONBody>,
): Promise<RESTPostAPIChannelInviteResult>;
}; };
messages: { messages: {
get( get(args?: RestArgumentsNoBody<RESTGetAPIChannelMessagesQuery>): Promise<RESTGetAPIChannelMessagesResult>;
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIChannelMessagesQuery>, post(args: RestArguments<RESTPostAPIChannelMessageJSONBody>): Promise<RESTPostAPIChannelMessageResult>;
): Promise<RESTGetAPIChannelMessagesResult>;
post(
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIChannelMessageJSONBody>,
): Promise<RESTPostAPIChannelMessageResult>;
'bulk-delete': { 'bulk-delete': {
post( post(
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIChannelMessagesBulkDeleteJSONBody>, args: RestArguments<RESTPostAPIChannelMessagesBulkDeleteJSONBody>,
): Promise<RESTPostAPIChannelMessagesBulkDeleteResult>; ): Promise<RESTPostAPIChannelMessagesBulkDeleteResult>;
}; };
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIChannelMessageResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIChannelMessageResult>;
patch( patch(args: RestArguments<RESTPatchAPIChannelMessageJSONBody>): Promise<RESTPatchAPIChannelMessageResult>;
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIChannelMessageJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIChannelMessageResult>;
): Promise<RESTPatchAPIChannelMessageResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIChannelMessageResult>;
threads: { threads: {
post( post(
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIChannelMessagesThreadsJSONBody>, args: RestArguments<RESTPostAPIChannelMessagesThreadsJSONBody>,
): Promise<RESTPostAPIChannelMessagesThreadsResult>; ): Promise<RESTPostAPIChannelMessagesThreadsResult>;
}; };
crosspost: { crosspost: {
post(args: RestArguments<ProxyRequestMethod.Post>): Promise<RESTPostAPIChannelMessageCrosspostResult>; post(args: RestArgumentsNoBody): Promise<RESTPostAPIChannelMessageCrosspostResult>;
}; };
reactions: { reactions: {
delete( delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIChannelAllMessageReactionsResult>;
args?: RestArguments<ProxyRequestMethod.Delete>,
): Promise<RESTDeleteAPIChannelAllMessageReactionsResult>;
( (
emoji: string, emoji: string,
): { ): {
get( get(
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIChannelMessageReactionUsersQuery>, args?: RestArgumentsNoBody<RESTGetAPIChannelMessageReactionUsersQuery>,
): Promise<RESTGetAPIChannelMessageReactionUsersResult>; ): Promise<RESTGetAPIChannelMessageReactionUsersResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIChannelMessageReactionResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIChannelMessageReactionResult>;
( (
id: '@me', id: '@me',
): { ): {
put(args?: RestArguments<ProxyRequestMethod.Put>): Promise<RESTPutAPIChannelMessageReactionResult>; put(args?: RestArgumentsNoBody): Promise<RESTPutAPIChannelMessageReactionResult>;
delete( delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIChannelMessageReactionResult>;
args?: RestArguments<ProxyRequestMethod.Delete>,
): Promise<RESTDeleteAPIChannelMessageReactionResult>;
}; };
( (
id: string, id: string,
): { ): {
delete( delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIChannelMessageReactionResult>;
args?: RestArguments<ProxyRequestMethod.Delete>,
): Promise<RESTDeleteAPIChannelMessageReactionResult>;
}; };
}; };
}; };
}; };
}; };
typing: { typing: {
post(args?: RestArguments<ProxyRequestMethod.Post>): Promise<RESTPostAPIChannelTypingResult>; post(args?: RestArgumentsNoBody): Promise<RESTPostAPIChannelTypingResult>;
}; };
webhooks: { webhooks: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildWebhooksResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildWebhooksResult>;
post( post(args: RestArguments<RESTPostAPIChannelWebhookJSONBody>): Promise<RESTPostAPIChannelWebhookResult>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIChannelWebhookJSONBody>,
): Promise<RESTPostAPIChannelWebhookResult>;
}; };
'voice-status': { 'voice-status': {
put(args: RestArguments<ProxyRequestMethod.Put, { status: string | null }>): Promise<never>; put(args: RestArguments<{ status: string | null }>): Promise<never>;
}; };
polls(messageId: string): { polls(messageId: string): {
answers(id: ValidAnswerId): { answers(id: ValidAnswerId): {
get( get(args?: RestArgumentsNoBody<RESTGetAPIPollAnswerVotersQuery>): Promise<RESTGetAPIPollAnswerVotersResult>;
args?: RestArguments<ProxyRequestMethod.Get, never, RESTGetAPIPollAnswerVotersQuery>,
): Promise<RESTGetAPIPollAnswerVotersResult>;
}; };
expire: { expire: {
post(args?: RestArguments<ProxyRequestMethod.Post>): Promise<RESTPostAPIPollExpireResult>; post(args?: RestArgumentsNoBody): Promise<RESTPostAPIPollExpireResult>;
}; };
}; };
}; };

View File

@ -1,12 +1,11 @@
import type { RESTGetAPIGatewayBotResult, RESTGetAPIGatewayResult } from '../../types'; import type { RESTGetAPIGatewayBotResult, RESTGetAPIGatewayResult } from '../../types';
import type { ProxyRequestMethod } from '../Router'; import type { RestArgumentsNoBody } from '../api';
import type { RestArguments } from '../api';
export interface GatewayRoutes { export interface GatewayRoutes {
gateway: { gateway: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGatewayResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGatewayResult>;
bot: { bot: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGatewayBotResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGatewayBotResult>;
}; };
}; };
} }

View File

@ -117,274 +117,233 @@ import type {
RESTPutAPIGuildMemberRoleResult, RESTPutAPIGuildMemberRoleResult,
RESTPutAPIGuildTemplateSyncResult, RESTPutAPIGuildTemplateSyncResult,
} from '../../types'; } from '../../types';
import type { ProxyRequestMethod } from '../Router'; import type { RestArguments, RestArgumentsNoBody } from '../api';
import type { RestArguments } from '../api';
import type { RawFile } from '../shared'; import type { RawFile } from '../shared';
export interface GuildRoutes { export interface GuildRoutes {
guilds: { guilds: {
post(args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIGuildsJSONBody>): Promise<RESTPostAPIGuildsResult>; post(args: RestArguments<RESTPostAPIGuildsJSONBody>): Promise<RESTPostAPIGuildsResult>;
templates(code: string): { templates(code: string): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPITemplateResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPITemplateResult>;
post( post(args: RestArguments<RESTPostAPITemplateCreateGuildJSONBody>): Promise<RESTPostAPITemplateCreateGuildResult>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPITemplateCreateGuildJSONBody>,
): Promise<RESTPostAPITemplateCreateGuildResult>;
}; };
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIGuildQuery>): Promise<RESTGetAPIGuildResult>; get(args?: RestArgumentsNoBody<RESTGetAPIGuildQuery>): Promise<RESTGetAPIGuildResult>;
patch(args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildJSONBody>): Promise<RESTPatchAPIGuildResult>; patch(args: RestArguments<RESTPatchAPIGuildJSONBody>): Promise<RESTPatchAPIGuildResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIGuildResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIGuildResult>;
webhooks: { webhooks: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildWebhooksResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildWebhooksResult>;
}; };
preview: { preview: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildPreviewResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildPreviewResult>;
}; };
'audit-logs': { 'audit-logs': {
get(args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIAuditLogQuery>): Promise<RESTGetAPIAuditLogResult>; get(args?: RestArgumentsNoBody<RESTGetAPIAuditLogQuery>): Promise<RESTGetAPIAuditLogResult>;
}; };
'auto-moderation': { 'auto-moderation': {
rules: { rules: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIAutoModerationRulesResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIAutoModerationRulesResult>;
post( post(
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIAutoModerationRuleJSONBody>, args: RestArguments<RESTPostAPIAutoModerationRuleJSONBody>,
): Promise<RESTPostAPIAutoModerationRuleResult>; ): Promise<RESTPostAPIAutoModerationRuleResult>;
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIAutoModerationRuleResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIAutoModerationRuleResult>;
patch( patch(
args: RestArguments<ProxyRequestMethod.Post, RESTPatchAPIAutoModerationRuleJSONBody>, args: RestArguments<RESTPatchAPIAutoModerationRuleJSONBody>,
): Promise<RESTPatchAPIAutoModerationRuleResult>; ): Promise<RESTPatchAPIAutoModerationRuleResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIAutoModerationRuleResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIAutoModerationRuleResult>;
}; };
}; };
}; };
channels: { channels: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildChannelsResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildChannelsResult>;
post( post(args: RestArguments<RESTPostAPIGuildChannelJSONBody>): Promise<RESTPostAPIGuildChannelResult>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIGuildChannelJSONBody>,
): Promise<RESTPostAPIGuildChannelResult>;
patch( patch(
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildChannelPositionsJSONBody>, args: RestArguments<RESTPatchAPIGuildChannelPositionsJSONBody>,
): Promise<RESTPatchAPIGuildChannelPositionsResult>; ): Promise<RESTPatchAPIGuildChannelPositionsResult>;
}; };
members: { members: {
get( get(args?: RestArgumentsNoBody<RESTGetAPIGuildMembersQuery>): Promise<RESTGetAPIGuildMembersResult>;
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIGuildMembersQuery>,
): Promise<RESTGetAPIGuildMembersResult>;
search: { search: {
get( get(
args: RestArguments<ProxyRequestMethod.Get, RESTGetAPIGuildMembersSearchQuery>, args: RestArgumentsNoBody<RESTGetAPIGuildMembersSearchQuery>,
): Promise<RESTGetAPIGuildMembersSearchResult>; ): Promise<RESTGetAPIGuildMembersSearchResult>;
}; };
'@me': { '@me': {
patch( patch(args: RestArguments<RESTPatchAPICurrentGuildMemberJSONBody>): Promise<RESTGetAPIGuildMemberResult>;
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPICurrentGuildMemberJSONBody>,
): Promise<RESTGetAPIGuildMemberResult>;
}; };
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildMemberResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildMemberResult>;
put( put(args?: RestArguments<RESTPutAPIGuildMemberJSONBody>): Promise<RESTPutAPIGuildMemberResult>;
args?: RestArguments<ProxyRequestMethod.Put, RESTPutAPIGuildMemberJSONBody>, patch(args: RestArguments<RESTPatchAPIGuildMemberJSONBody>): Promise<RESTPatchAPIGuildMemberResult>;
): Promise<RESTPutAPIGuildMemberResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIGuildMemberResult>;
patch(
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildMemberJSONBody>,
): Promise<RESTPatchAPIGuildMemberResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIGuildMemberResult>;
roles(id: string): { roles(id: string): {
put(args?: RestArguments<ProxyRequestMethod.Put>): Promise<RESTPutAPIGuildMemberRoleResult>; put(args?: RestArgumentsNoBody): Promise<RESTPutAPIGuildMemberRoleResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIGuildMemberRoleResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIGuildMemberRoleResult>;
}; };
}; };
}; };
threads: { threads: {
active: { active: {
get( get(
args?: RestArguments<ProxyRequestMethod.Get>, args?: RestArgumentsNoBody,
): Promise<Identify<RESTGetAPIGuildThreadsResult & { threads: Partial<APIThreadChannel> }>>; ): Promise<Identify<RESTGetAPIGuildThreadsResult & { threads: Partial<APIThreadChannel> }>>;
}; };
}; };
roles: { roles: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildRolesResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildRolesResult>;
post( post(args: RestArguments<RESTPostAPIGuildRoleJSONBody>): Promise<RESTPostAPIGuildRoleResult>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIGuildRoleJSONBody>,
): Promise<RESTPostAPIGuildRoleResult>;
patch( patch(
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildRolePositionsJSONBody>, args: RestArguments<RESTPatchAPIGuildRolePositionsJSONBody>,
): Promise<RESTPatchAPIGuildRolePositionsResult>; ): Promise<RESTPatchAPIGuildRolePositionsResult>;
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildRoleResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildRoleResult>;
patch( patch(args: RestArguments<RESTPatchAPIGuildRoleJSONBody>): Promise<RESTPatchAPIGuildRoleResult>;
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildRoleJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIGuildRoleResult>;
): Promise<RESTPatchAPIGuildRoleResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIGuildRoleResult>;
}; };
}; };
bans: { bans: {
get(args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIGuildBansQuery>): Promise<RESTGetAPIGuildBansResult>; get(args?: RestArgumentsNoBody<RESTGetAPIGuildBansQuery>): Promise<RESTGetAPIGuildBansResult>;
( (
userId: string, userId: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildBanResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildBanResult>;
put( put(args?: RestArguments<RESTPutAPIGuildBanJSONBody | undefined>): Promise<RESTPutAPIGuildBanResult>;
args?: RestArguments<ProxyRequestMethod.Put, RESTPutAPIGuildBanJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIGuildBanResult>;
): Promise<RESTPutAPIGuildBanResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIGuildBanResult>;
}; };
}; };
'bulk-bans': { 'bulk-bans': {
post( post(args: RestArguments<RESTPostAPIGuildBulkBanJSONBody>): Promise<RESTPostAPIGuildBulkBanResult>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIGuildBulkBanJSONBody>,
): Promise<RESTPostAPIGuildBulkBanResult>;
}; };
mfa: { mfa: {
post( post(args: RestArguments<RESTPostAPIGuildsMFAJSONBody>): Promise<RESTPostAPIGuildsMFAResult>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIGuildsMFAJSONBody>,
): Promise<RESTPostAPIGuildsMFAResult>;
}; };
prune: { prune: {
get( get(args: RestArgumentsNoBody<RESTGetAPIGuildPruneCountQuery>): Promise<RESTGetAPIGuildPruneCountResult>;
args: RestArguments<ProxyRequestMethod.Get, RESTGetAPIGuildPruneCountQuery>, post(args: RestArguments<RESTPostAPIGuildPruneJSONBody>): Promise<RESTPostAPIGuildPruneResult>;
): Promise<RESTGetAPIGuildPruneCountResult>;
post(
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIGuildPruneJSONBody>,
): Promise<RESTPostAPIGuildPruneResult>;
}; };
regions: { regions: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildVoiceRegionsResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildVoiceRegionsResult>;
}; };
invites: { invites: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildInvitesResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildInvitesResult>;
}; };
widget: { widget: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildWidgetSettingsResult>; get(args?: RestArgumentsNoBody<{ style?: string }>): Promise<RESTGetAPIGuildWidgetSettingsResult>;
patch( patch(
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildWidgetSettingsJSONBody>, args: RestArguments<RESTPatchAPIGuildWidgetSettingsJSONBody>,
): Promise<RESTPatchAPIGuildWidgetSettingsResult>; ): Promise<RESTPatchAPIGuildWidgetSettingsResult>;
}; };
'widget.json': { 'widget.json': {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildWidgetJSONResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildWidgetJSONResult>;
}; };
'widget.png': { 'widget.png': {
get( get(args?: RestArgumentsNoBody<RESTGetAPIGuildWidgetImageQuery>): Promise<RESTGetAPIGuildWidgetImageResult>;
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIGuildWidgetImageQuery>,
): Promise<RESTGetAPIGuildWidgetImageResult>;
}; };
integrations: { integrations: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildIntegrationsResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildIntegrationsResult>;
( (
id: string, id: string,
): { ): {
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIGuildIntegrationResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIGuildIntegrationResult>;
}; };
}; };
'vanity-url': { 'vanity-url': {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildVanityUrlResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildVanityUrlResult>;
}; };
'welcome-screen': { 'welcome-screen': {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildWelcomeScreenResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildWelcomeScreenResult>;
patch( patch(
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildWelcomeScreenJSONBody>, args: RestArguments<RESTPatchAPIGuildWelcomeScreenJSONBody>,
): Promise<RESTPatchAPIGuildWelcomeScreenResult>; ): Promise<RESTPatchAPIGuildWelcomeScreenResult>;
}; };
// onboarding: { // onboarding: {
// get(args:RestArguments<ProxyRequestMethod.Get,boarding>); // get(args:RestArgumentsNoBody<boarding>);
// } // }
emojis: { emojis: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildEmojisResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildEmojisResult>;
post( post(args: RestArguments<RESTPostAPIGuildEmojiJSONBody>): Promise<RESTPostAPIGuildEmojiResult>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIGuildEmojiJSONBody>,
): Promise<RESTPostAPIGuildEmojiResult>;
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildEmojiResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildEmojiResult>;
patch( patch(args: RestArguments<RESTPatchAPIGuildEmojiJSONBody>): Promise<RESTPatchAPIGuildEmojiResult>;
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildEmojiJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIGuildEmojiResult>;
): Promise<RESTPatchAPIGuildEmojiResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIGuildEmojiResult>;
}; };
}; };
'voice-states': { 'voice-states': {
'@me': { '@me': {
patch( patch(
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildVoiceStateCurrentMemberJSONBody>, args: RestArguments<RESTPatchAPIGuildVoiceStateCurrentMemberJSONBody>,
): Promise<RESTPatchAPIGuildVoiceStateCurrentMemberResult>; ): Promise<RESTPatchAPIGuildVoiceStateCurrentMemberResult>;
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPICurrentUserVoiceState>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPICurrentUserVoiceState>;
}; };
( (
userId: string, userId: string,
): { ): {
patch( patch(
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildVoiceStateUserJSONBody>, args: RestArguments<RESTPatchAPIGuildVoiceStateUserJSONBody>,
): Promise<RESTPatchAPIGuildVoiceStateUserResult>; ): Promise<RESTPatchAPIGuildVoiceStateUserResult>;
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIUserVoiceState>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIUserVoiceState>;
}; };
}; };
stickers: { stickers: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildStickersResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildStickersResult>;
post( post(
args: RestArguments< args: RestArguments<
ProxyRequestMethod.Post,
Omit<RESTPostAPIGuildStickerFormDataBody, 'file'>, Omit<RESTPostAPIGuildStickerFormDataBody, 'file'>,
object,
OmitInsert<RawFile, 'key', { key: 'file' }>[] OmitInsert<RawFile, 'key', { key: 'file' }>[]
>, >,
): Promise<RESTPostAPIGuildStickerResult>; ): Promise<RESTPostAPIGuildStickerResult>;
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildStickerResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildStickerResult>;
patch( patch(args: RestArguments<RESTPatchAPIGuildStickerJSONBody>): Promise<RESTPatchAPIGuildStickerResult>;
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildStickerJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIGuildStickerResult>;
): Promise<RESTPatchAPIGuildStickerResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIGuildStickerResult>;
}; };
}; };
'scheduled-events': { 'scheduled-events': {
get( get(
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIGuildScheduledEventsQuery>, args?: RestArgumentsNoBody<RESTGetAPIGuildScheduledEventsQuery>,
): Promise<RESTGetAPIGuildScheduledEventsResult>; ): Promise<RESTGetAPIGuildScheduledEventsResult>;
post( post(
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIGuildScheduledEventJSONBody>, args: RestArguments<RESTPostAPIGuildScheduledEventJSONBody>,
): Promise<RESTPostAPIGuildScheduledEventResult>; ): Promise<RESTPostAPIGuildScheduledEventResult>;
( (
id: string, id: string,
): { ): {
get( get(
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIGuildScheduledEventQuery>, args?: RestArgumentsNoBody<RESTGetAPIGuildScheduledEventQuery>,
): Promise<RESTGetAPIGuildScheduledEventResult>; ): Promise<RESTGetAPIGuildScheduledEventResult>;
patch( patch(
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildScheduledEventJSONBody>, args: RestArguments<RESTPatchAPIGuildScheduledEventJSONBody>,
): Promise<RESTPatchAPIGuildScheduledEventResult>; ): Promise<RESTPatchAPIGuildScheduledEventResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIGuildScheduledEventResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIGuildScheduledEventResult>;
users: { users: {
get( get(
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIGuildScheduledEventUsersQuery>, args?: RestArgumentsNoBody<RESTGetAPIGuildScheduledEventUsersQuery>,
): Promise<RESTGetAPIGuildScheduledEventUsersResult>; ): Promise<RESTGetAPIGuildScheduledEventUsersResult>;
}; };
}; };
}; };
templates: { templates: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIGuildTemplatesResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIGuildTemplatesResult>;
post( post(args: RestArguments<RESTPostAPIGuildTemplatesJSONBody>): Promise<RESTPostAPIGuildTemplatesResult>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIGuildTemplatesJSONBody>,
): Promise<RESTPostAPIGuildTemplatesResult>;
( (
code: string, code: string,
): { ): {
put(args?: RestArguments<ProxyRequestMethod.Put>): Promise<RESTPutAPIGuildTemplateSyncResult>; put(args?: RestArgumentsNoBody): Promise<RESTPutAPIGuildTemplateSyncResult>;
patch( patch(args: RestArguments<RESTPatchAPIGuildTemplateJSONBody>): Promise<RESTPatchAPIGuildTemplateResult>;
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIGuildTemplateJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIGuildTemplateResult>;
): Promise<RESTPatchAPIGuildTemplateResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIGuildTemplateResult>;
}; };
}; };
}; };

View File

@ -12,14 +12,15 @@ import type { WebhookRoutes } from './webhooks';
export * from './cdn'; export * from './cdn';
export type APIRoutes = ApplicationRoutes & export interface APIRoutes
ChannelRoutes & extends ApplicationRoutes,
GatewayRoutes & ChannelRoutes,
GuildRoutes & GatewayRoutes,
InteractionRoutes & GuildRoutes,
InviteRoutes & InteractionRoutes,
StageInstanceRoutes & InviteRoutes,
StickerRoutes & StageInstanceRoutes,
UserRoutes & StickerRoutes,
VoiceRoutes & UserRoutes,
WebhookRoutes; VoiceRoutes,
WebhookRoutes {}

View File

@ -1,9 +1,9 @@
import type { OmitInsert } from '../../common';
import type { import type {
RESTPostAPIInteractionCallbackJSONBody, RESTPostAPIInteractionCallbackJSONBody,
RESTPostAPIInteractionCallbackQuery, RESTPostAPIInteractionCallbackQuery,
RESTPostAPIInteractionCallbackResult, RESTPostAPIInteractionCallbackResult,
} from '../../types'; } from '../../types';
import type { ProxyRequestMethod } from '../Router';
import type { RestArguments } from '../api'; import type { RestArguments } from '../api';
export interface InteractionRoutes { export interface InteractionRoutes {
@ -11,24 +11,18 @@ export interface InteractionRoutes {
callback: { callback: {
post( post(
args: RestArguments< args: RestArguments<
ProxyRequestMethod.Post,
RESTPostAPIInteractionCallbackJSONBody, RESTPostAPIInteractionCallbackJSONBody,
Omit<RESTPostAPIInteractionCallbackQuery, 'with_response'> & { with_response: true } OmitInsert<RESTPostAPIInteractionCallbackQuery, 'with_response', { with_response: true }>
>, >,
): Promise<RESTPostAPIInteractionCallbackResult>; ): Promise<RESTPostAPIInteractionCallbackResult>;
post( post(
args: RestArguments< args: RestArguments<
ProxyRequestMethod.Post,
RESTPostAPIInteractionCallbackJSONBody, RESTPostAPIInteractionCallbackJSONBody,
Omit<RESTPostAPIInteractionCallbackQuery, 'with_response'> & { with_response: false } OmitInsert<RESTPostAPIInteractionCallbackQuery, 'with_response', { with_response: false }>
>, >,
): Promise<undefined>; ): Promise<undefined>;
post( post(
args: RestArguments< args: RestArguments<RESTPostAPIInteractionCallbackJSONBody, RESTPostAPIInteractionCallbackQuery>,
ProxyRequestMethod.Post,
RESTPostAPIInteractionCallbackJSONBody,
RESTPostAPIInteractionCallbackQuery
>,
): Promise<RESTPostAPIInteractionCallbackResult | undefined>; ): Promise<RESTPostAPIInteractionCallbackResult | undefined>;
}; };
}; };

View File

@ -1,10 +1,9 @@
import type { RESTDeleteAPIInviteResult, RESTGetAPIInviteQuery, RESTGetAPIInviteResult } from '../../types'; import type { RESTDeleteAPIInviteResult, RESTGetAPIInviteQuery, RESTGetAPIInviteResult } from '../../types';
import type { ProxyRequestMethod } from '../Router'; import type { RestArguments, RestArgumentsNoBody } from '../api';
import type { RestArguments } from '../api';
export interface InviteRoutes { export interface InviteRoutes {
invites(id: string): { invites(id: string): {
get(args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPIInviteQuery>): Promise<RESTGetAPIInviteResult>; get(args?: RestArguments<RESTGetAPIInviteQuery>): Promise<RESTGetAPIInviteResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIInviteResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIInviteResult>;
}; };
} }

View File

@ -3,16 +3,13 @@ import type {
RESTGetAPISKUSubscriptionsQuery, RESTGetAPISKUSubscriptionsQuery,
RESTGetAPISKUSubscriptionsResult, RESTGetAPISKUSubscriptionsResult,
} from '../../types'; } from '../../types';
import type { ProxyRequestMethod } from '../Router'; import type { RestArguments, RestArgumentsNoBody } from '../api';
import type { RestArguments } from '../api';
export interface SKuRoutes { export interface SKuRoutes {
skus(id: string): { skus(id: string): {
get: ( get: (args?: RestArguments<RESTGetAPISKUSubscriptionsQuery>) => Promise<RESTGetAPISKUSubscriptionsResult>;
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPISKUSubscriptionsQuery>,
) => Promise<RESTGetAPISKUSubscriptionsResult>;
subscriptions(id: string): { subscriptions(id: string): {
get: (args?: RestArguments<ProxyRequestMethod.Get>) => Promise<RESTGetAPISKUSubscriptionResult>; get: (args?: RestArgumentsNoBody) => Promise<RESTGetAPISKUSubscriptionResult>;
}; };
}; };
} }

View File

@ -6,22 +6,17 @@ import type {
RESTPostAPIStageInstanceJSONBody, RESTPostAPIStageInstanceJSONBody,
RESTPostAPIStageInstanceResult, RESTPostAPIStageInstanceResult,
} from '../../types'; } from '../../types';
import type { ProxyRequestMethod } from '../Router'; import type { RestArguments, RestArgumentsNoBody } from '../api';
import type { RestArguments } from '../api';
export interface StageInstanceRoutes { export interface StageInstanceRoutes {
'stage-instances': { 'stage-instances': {
post( post(args: RestArguments<RESTPostAPIStageInstanceJSONBody>): Promise<RESTPostAPIStageInstanceResult>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPIStageInstanceJSONBody>,
): Promise<RESTPostAPIStageInstanceResult>;
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIStageInstanceResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIStageInstanceResult>;
patch( patch(args: RestArguments<RESTPatchAPIStageInstanceJSONBody>): Promise<RESTPatchAPIStageInstanceResult>;
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIStageInstanceJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIStageInstanceResult>;
): Promise<RESTPatchAPIStageInstanceResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIStageInstanceResult>;
}; };
}; };
} }

View File

@ -1,12 +1,11 @@
import type { RESTGetAPIStickerResult, RESTGetStickerPacksResult } from '../../types'; import type { RESTGetAPIStickerResult, RESTGetStickerPacksResult } from '../../types';
import type { ProxyRequestMethod } from '../Router'; import type { RestArgumentsNoBody } from '../api';
import type { RestArguments } from '../api';
export interface StickerRoutes { export interface StickerRoutes {
stickers(id: string): { stickers(id: string): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIStickerResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIStickerResult>;
}; };
'sticker-packs': { 'sticker-packs': {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetStickerPacksResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetStickerPacksResult>;
}; };
} }

View File

@ -14,51 +14,42 @@ import type {
RESTPutAPICurrentUserApplicationRoleConnectionJSONBody, RESTPutAPICurrentUserApplicationRoleConnectionJSONBody,
RESTPutAPICurrentUserApplicationRoleConnectionResult, RESTPutAPICurrentUserApplicationRoleConnectionResult,
} from '../../types'; } from '../../types';
import type { ProxyRequestMethod } from '../Router'; import type { RestArguments, RestArgumentsNoBody } from '../api';
import type { RestArguments } from '../api';
export interface UserRoutes { export interface UserRoutes {
users: { users: {
( (
id: string, id: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIUserResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIUserResult>;
}; };
( (
id: '@me', id: '@me',
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPICurrentUserResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPICurrentUserResult>;
patch( patch(args: RestArguments<RESTPatchAPICurrentUserJSONBody>): Promise<RESTPatchAPICurrentUserResult>;
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPICurrentUserJSONBody>,
): Promise<RESTPatchAPICurrentUserResult>;
guilds: { guilds: {
get( get(args?: RestArgumentsNoBody<RESTGetAPICurrentUserGuildsQuery>): Promise<RESTGetAPICurrentUserGuildsResult>;
args?: RestArguments<ProxyRequestMethod.Get, RESTGetAPICurrentUserGuildsQuery>,
): Promise<RESTGetAPICurrentUserGuildsResult>;
( (
id: string, id: string,
): { ): {
member: { member: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetCurrentUserGuildMemberResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetCurrentUserGuildMemberResult>;
}; };
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIGuildResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIGuildResult>;
}; };
}; };
channels: { channels: {
post( post(args: RestArguments<RESTPostAPICurrentUserCreateDMChannelJSONBody>): Promise<APIDMChannel>;
args: RestArguments<ProxyRequestMethod.Post, RESTPostAPICurrentUserCreateDMChannelJSONBody>,
): Promise<APIDMChannel>;
}; };
connections: { connections: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPICurrentUserConnectionsResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPICurrentUserConnectionsResult>;
}; };
applications(applicationId: string): { applications(applicationId: string): {
'role-connection': { 'role-connection': {
get( get(args?: RestArgumentsNoBody): Promise<RESTGetAPICurrentUserApplicationRoleConnectionResult>;
args?: RestArguments<ProxyRequestMethod.Get>,
): Promise<RESTGetAPICurrentUserApplicationRoleConnectionResult>;
put( put(
args: RestArguments<ProxyRequestMethod.Put, RESTPutAPICurrentUserApplicationRoleConnectionJSONBody>, args: RestArguments<RESTPutAPICurrentUserApplicationRoleConnectionJSONBody>,
): Promise<RESTPutAPICurrentUserApplicationRoleConnectionResult>; ): Promise<RESTPutAPICurrentUserApplicationRoleConnectionResult>;
}; };
}; };

View File

@ -1,11 +1,10 @@
import type { RESTGetAPIVoiceRegionsResult } from '../../types'; import type { RESTGetAPIVoiceRegionsResult } from '../../types';
import type { ProxyRequestMethod } from '../Router'; import type { RestArgumentsNoBody } from '../api';
import type { RestArguments } from '../api';
export interface VoiceRoutes { export interface VoiceRoutes {
voice: { voice: {
region: { region: {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIVoiceRegionsResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIVoiceRegionsResult>;
}; };
}; };
} }

View File

@ -22,55 +22,38 @@ import type {
RESTPostAPIWebhookWithTokenSlackWaitResult, RESTPostAPIWebhookWithTokenSlackWaitResult,
RESTPostAPIWebhookWithTokenWaitResult, RESTPostAPIWebhookWithTokenWaitResult,
} from '../../types'; } from '../../types';
import type { ProxyRequestMethod } from '../Router'; import type { RestArguments, RestArgumentsNoBody } from '../api';
import type { RestArguments } from '../api';
export interface WebhookRoutes { export interface WebhookRoutes {
webhooks(id: string): { webhooks(id: string): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIWebhookResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIWebhookResult>;
patch( patch(args: RestArguments<RESTPatchAPIWebhookJSONBody>): Promise<RESTPatchAPIWebhookResult>;
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIWebhookJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIWebhookResult>;
): Promise<RESTPatchAPIWebhookResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIWebhookResult>;
( (
token: string, token: string,
): { ): {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIWebhookWithTokenResult>; get(args?: RestArgumentsNoBody): Promise<RESTGetAPIWebhookWithTokenResult>;
patch( patch(args: RestArguments<RESTPatchAPIWebhookWithTokenJSONBody>): Promise<RESTPatchAPIWebhookWithTokenResult>;
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIWebhookWithTokenJSONBody>, delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIWebhookWithTokenResult>;
): Promise<RESTPatchAPIWebhookWithTokenResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIWebhookWithTokenResult>;
post( post(
args: RestArguments< args: RestArguments<RESTPostAPIWebhookWithTokenJSONBody, RESTPostAPIWebhookWithTokenQuery>,
ProxyRequestMethod.Post,
RESTPostAPIWebhookWithTokenJSONBody,
RESTPostAPIWebhookWithTokenQuery
>,
): Promise<RESTPostAPIWebhookWithTokenResult | RESTPostAPIWebhookWithTokenWaitResult>; ): Promise<RESTPostAPIWebhookWithTokenResult | RESTPostAPIWebhookWithTokenWaitResult>;
slack: { slack: {
post( post(
args: RestArguments< args: RestArguments<RESTPostAPIWebhookWithTokenJSONBody, RESTPostAPIWebhookWithTokenSlackQuery>,
ProxyRequestMethod.Post,
RESTPostAPIWebhookWithTokenJSONBody,
RESTPostAPIWebhookWithTokenSlackQuery
>,
): Promise<RESTPostAPIWebhookWithTokenSlackResult | RESTPostAPIWebhookWithTokenSlackWaitResult>; ): Promise<RESTPostAPIWebhookWithTokenSlackResult | RESTPostAPIWebhookWithTokenSlackWaitResult>;
}; };
github: { github: {
post( post(
args: RestArguments< args: RestArguments<RESTPostAPIWebhookWithTokenJSONBody, RESTPostAPIWebhookWithTokenGitHubQuery>,
ProxyRequestMethod.Post,
RESTPostAPIWebhookWithTokenJSONBody,
RESTPostAPIWebhookWithTokenGitHubQuery
>,
): Promise<RESTPostAPIWebhookWithTokenGitHubResult | RESTPostAPIWebhookWithTokenGitHubWaitResult>; ): Promise<RESTPostAPIWebhookWithTokenGitHubResult | RESTPostAPIWebhookWithTokenGitHubWaitResult>;
}; };
messages: (id: (string & {}) | '@original') => { messages: (id: string) => {
get(args?: RestArguments<ProxyRequestMethod.Get>): Promise<RESTGetAPIWebhookWithTokenMessageResult>; get(args?: RestArgumentsNoBody<{ thread_id: string }>): Promise<RESTGetAPIWebhookWithTokenMessageResult>;
patch( patch(
args: RestArguments<ProxyRequestMethod.Patch, RESTPatchAPIWebhookWithTokenMessageJSONBody>, args: RestArguments<RESTPatchAPIWebhookWithTokenMessageJSONBody>,
): Promise<RESTPatchAPIWebhookWithTokenMessageResult>; ): Promise<RESTPatchAPIWebhookWithTokenMessageResult>;
delete(args?: RestArguments<ProxyRequestMethod.Delete>): Promise<RESTDeleteAPIWebhookWithTokenMessageResult>; delete(args?: RestArgumentsNoBody): Promise<RESTDeleteAPIWebhookWithTokenMessageResult>;
}; };
}; };
}; };

View File

@ -1,8 +1,9 @@
import { randomUUID } from 'node:crypto'; import { type UUID, randomUUID } from 'node:crypto';
import { Logger, delay, lazyLoadPackage, snowflakeToTimestamp } from '../common'; import { Logger, delay, lazyLoadPackage, snowflakeToTimestamp } from '../common';
import type { WorkerData } from '../websocket'; import type { WorkerData } from '../websocket';
import type { WorkerSendApiRequest } from '../websocket/discord/worker'; import type { WorkerSendApiRequest } from '../websocket/discord/worker';
import { CDNRouter, type ProxyRequestMethod } from './Router'; import { CDNRouter, Router } from './Router';
import type { APIRoutes } from './Routes';
import { Bucket } from './bucket'; import { Bucket } from './bucket';
import { import {
type ApiHandlerInternalOptions, type ApiHandlerInternalOptions,
@ -18,13 +19,18 @@ import { isBufferLike } from './utils/utils';
let parentPort: import('node:worker_threads').MessagePort; let parentPort: import('node:worker_threads').MessagePort;
let workerData: WorkerData; let workerData: WorkerData;
export interface ApiHandler {
/* @internal */
_proxy_?: APIRoutes;
debugger?: Logger;
}
export class ApiHandler { export class ApiHandler {
options: ApiHandlerInternalOptions; options: ApiHandlerInternalOptions;
globalBlock = false; globalBlock = false;
ratelimits = new Map<string, Bucket>(); ratelimits = new Map<string, Bucket>();
readyQueue: (() => void)[] = []; readyQueue: (() => void)[] = [];
cdn = CDNRouter.createProxy(); cdn = CDNRouter.createProxy();
debugger?: Logger;
workerPromises?: Map<string, { resolve: (value: any) => any; reject: (error: any) => any }>; workerPromises?: Map<string, { resolve: (value: any) => any; reject: (error: any) => any }>;
constructor(options: ApiHandlerOptions) { constructor(options: ApiHandlerOptions) {
@ -52,6 +58,10 @@ export class ApiHandler {
} }
} }
get proxy() {
return (this._proxy_ ??= new Router(this).createProxy());
}
globalUnblock() { globalUnblock() {
this.globalBlock = false; this.globalBlock = false;
let cb: (() => void) | undefined; let cb: (() => void) | undefined;
@ -60,13 +70,13 @@ export class ApiHandler {
} }
} }
#randomUUID(): string { #randomUUID(): UUID {
const uuid = randomUUID(); const uuid = randomUUID();
if (this.workerPromises!.has(uuid)) return this.#randomUUID(); if (this.workerPromises!.has(uuid)) return this.#randomUUID();
return uuid; return uuid;
} }
async request<T = any>( async request<T = unknown>(
method: HttpMethods, method: HttpMethods,
url: `/${string}`, url: `/${string}`,
{ auth = true, ...request }: ApiRequestOptions = {}, { auth = true, ...request }: ApiRequestOptions = {},
@ -412,28 +422,25 @@ export class ApiHandler {
} }
export type RequestOptions = Pick<ApiRequestOptions, 'reason' | 'auth' | 'appendToFormData' | 'token'>; export type RequestOptions = Pick<ApiRequestOptions, 'reason' | 'auth' | 'appendToFormData' | 'token'>;
export type RequestObject<
M extends ProxyRequestMethod,
B = Record<string, any>,
Q = Record<string, any>,
F extends RawFile[] = RawFile[],
> = {
query?: Q;
} & RequestOptions &
(M extends `${ProxyRequestMethod.Get}`
? unknown
: {
body?: B;
files?: F;
});
export type RestArguments< export type RestArguments<
M extends ProxyRequestMethod, B extends Record<string, any> | undefined,
B = any, Q extends never | Record<string, any> = never,
Q extends never | Record<string, any> = any,
F extends RawFile[] = RawFile[], F extends RawFile[] = RawFile[],
> = M extends ProxyRequestMethod.Get > = (
? Q extends never | {
? RequestObject<M, never, B, never> body: B;
: never files?: F;
: RequestObject<M, B, Q, F>; }
| (Q extends never | undefined
? {}
: {
query?: Q;
})
) &
RequestOptions;
export type RestArgumentsNoBody<Q extends never | Record<string, any> = never> = {
query?: Q;
files?: RawFile[];
} & RequestOptions;

View File

@ -184,7 +184,7 @@ export async function resolveAttachmentData(
if (data instanceof AttachmentBuilder) { if (data instanceof AttachmentBuilder) {
if (!data.data.resolvable) if (!data.data.resolvable)
throw new Error('The attachment type has been expressed as attachment but cannot be resolved as one.'); throw new Error('The attachment type has been expressed as attachment but cannot be resolved as one.');
return { data: data.data.resolvable! }; return { data: data.data.resolvable };
} }
switch (type) { switch (type) {

View File

@ -11,7 +11,10 @@ export type ComponentCallback<
T extends ComponentInteraction | StringSelectMenuInteraction = ComponentInteraction | StringSelectMenuInteraction, T extends ComponentInteraction | StringSelectMenuInteraction = ComponentInteraction | StringSelectMenuInteraction,
> = (interaction: T, stop: ComponentStopCallback, refresh: ComponentRefreshCallback) => any; > = (interaction: T, stop: ComponentStopCallback, refresh: ComponentRefreshCallback) => any;
export type ComponentFilterCallback<T = ComponentInteraction> = (interaction: T) => any; export type ComponentFilterCallback<T = ComponentInteraction> = (interaction: T) => any;
export type ComponentStopCallback = (reason?: string, refresh?: ComponentRefreshCallback) => any; export type ComponentStopCallback = (
reason: 'messageDelete' | 'channelDelete' | 'guildDelete' | (string & {}) | undefined,
refresh: ComponentRefreshCallback,
) => any;
export type ComponentRefreshCallback = () => any; export type ComponentRefreshCallback = () => any;
export type ModalSubmitCallback<T = ModalSubmitInteraction> = (interaction: T) => any; export type ModalSubmitCallback<T = ModalSubmitInteraction> = (interaction: T) => any;
export type ButtonLink = Omit<Button, 'setCustomId'>; export type ButtonLink = Omit<Button, 'setCustomId'>;
@ -25,5 +28,6 @@ export interface ListenerOptions {
timeout?: number; timeout?: number;
idle?: number; idle?: number;
filter?: ComponentFilterCallback; filter?: ComponentFilterCallback;
onPass?: ComponentFilterCallback;
onStop?: ComponentStopCallback; onStop?: ComponentStopCallback;
} }

View File

@ -23,7 +23,6 @@ export interface LimitedMemoryAdapterOptions<T> {
role?: ResourceLimitedMemoryAdapter; role?: ResourceLimitedMemoryAdapter;
stage_instance?: ResourceLimitedMemoryAdapter; stage_instance?: ResourceLimitedMemoryAdapter;
sticker?: ResourceLimitedMemoryAdapter; sticker?: ResourceLimitedMemoryAdapter;
thread?: ResourceLimitedMemoryAdapter;
overwrite?: ResourceLimitedMemoryAdapter; overwrite?: ResourceLimitedMemoryAdapter;
message?: ResourceLimitedMemoryAdapter; message?: ResourceLimitedMemoryAdapter;
@ -125,7 +124,6 @@ export class LimitedMemoryAdapter<T> implements Adapter {
case 'role': case 'role':
case 'stage_instance': case 'stage_instance':
case 'sticker': case 'sticker':
case 'thread':
case 'overwrite': case 'overwrite':
case 'message': case 'message':
self.removeToRelationship(namespace, k.split('.')[1]); self.removeToRelationship(namespace, k.split('.')[1]);
@ -221,7 +219,6 @@ export class LimitedMemoryAdapter<T> implements Adapter {
case 'role': case 'role':
case 'stage_instance': case 'stage_instance':
case 'sticker': case 'sticker':
case 'thread':
case 'overwrite': case 'overwrite':
case 'message': case 'message':
for (const keyStorage of this.storage.keys()) { for (const keyStorage of this.storage.keys()) {

14
src/cache/index.ts vendored
View File

@ -13,7 +13,6 @@ import { Presences } from './resources/presence';
import { Roles } from './resources/roles'; import { Roles } from './resources/roles';
import { StageInstances } from './resources/stage-instances'; import { StageInstances } from './resources/stage-instances';
import { Stickers } from './resources/stickers'; import { Stickers } from './resources/stickers';
import { Threads } from './resources/threads';
import { VoiceStates } from './resources/voice-states'; import { VoiceStates } from './resources/voice-states';
import type { InternalOptions, UsingClient } from '../commands'; import type { InternalOptions, UsingClient } from '../commands';
@ -47,7 +46,6 @@ export type GuildBased = 'members' | 'voiceStates';
export type GuildRelated = export type GuildRelated =
| 'emojis' | 'emojis'
| 'roles' | 'roles'
| 'threads'
| 'channels' | 'channels'
| 'stickers' | 'stickers'
| 'presences' | 'presences'
@ -114,7 +112,6 @@ export class Cache {
overwrites?: Overwrites; overwrites?: Overwrites;
roles?: Roles; roles?: Roles;
emojis?: Emojis; emojis?: Emojis;
threads?: Threads;
channels?: Channels; channels?: Channels;
stickers?: Stickers; stickers?: Stickers;
presences?: Presences; presences?: Presences;
@ -165,9 +162,6 @@ export class Cache {
if (!this.disabledCache.presences) { if (!this.disabledCache.presences) {
this.presences = new Presences(this, client); this.presences = new Presences(this, client);
} }
if (!this.disabledCache.threads) {
this.threads = new Threads(this, client);
}
if (!this.disabledCache.stageInstances) { if (!this.disabledCache.stageInstances) {
this.stageInstances = new StageInstances(this, client); this.stageInstances = new StageInstances(this, client);
} }
@ -200,7 +194,6 @@ export class Cache {
this.emojis?.__setClient(client); this.emojis?.__setClient(client);
this.stickers?.__setClient(client); this.stickers?.__setClient(client);
this.presences?.__setClient(client); this.presences?.__setClient(client);
this.threads?.__setClient(client);
this.stageInstances?.__setClient(client); this.stageInstances?.__setClient(client);
this.messages?.__setClient(client); this.messages?.__setClient(client);
this.bans?.__setClient(client); this.bans?.__setClient(client);
@ -282,7 +275,6 @@ export class Cache {
} }
break; break;
case 'roles': case 'roles':
case 'threads':
case 'stickers': case 'stickers':
case 'channels': case 'channels':
case 'presences': case 'presences':
@ -352,7 +344,6 @@ export class Cache {
for (const [type, data, id, guildId] of keys) { for (const [type, data, id, guildId] of keys) {
switch (type) { switch (type) {
case 'roles': case 'roles':
case 'threads':
case 'stickers': case 'stickers':
case 'channels': case 'channels':
case 'presences': case 'presences':
@ -444,7 +435,6 @@ export class Cache {
for (const [type, data, id, guildId] of keys) { for (const [type, data, id, guildId] of keys) {
switch (type) { switch (type) {
case 'roles': case 'roles':
case 'threads':
case 'stickers': case 'stickers':
case 'channels': case 'channels':
case 'presences': case 'presences':
@ -589,11 +579,11 @@ export class Cache {
case 'THREAD_CREATE': case 'THREAD_CREATE':
case 'THREAD_UPDATE': case 'THREAD_UPDATE':
if (event.d.guild_id) await this.threads?.set(event.d.id, event.d.guild_id, event.d); if (event.d.guild_id) await this.channels?.set(event.d.id, event.d.guild_id, event.d);
break; break;
case 'THREAD_DELETE': case 'THREAD_DELETE':
await this.threads?.remove(event.d.id, event.d.guild_id); await this.channels?.remove(event.d.id, event.d.guild_id);
break; break;
case 'USER_UPDATE': case 'USER_UPDATE':

View File

@ -1,11 +1,10 @@
import type { BaseClient } from '../../../client/base';
import type { UsingClient } from '../../../commands'; import type { UsingClient } from '../../../commands';
import { fakePromise } from '../../../common'; import { fakePromise } from '../../../common';
import type { GatewayIntentBits } from '../../../types'; import type { GatewayIntentBits } from '../../../types';
import type { Cache, ReturnCache } from '../../index'; import type { Cache, ReturnCache } from '../../index';
export class GuildRelatedResource<T = any, S = any> { export class GuildRelatedResource<T = any, S = any> {
client!: BaseClient; client!: UsingClient;
namespace = 'base'; namespace = 'base';
constructor( constructor(

View File

@ -54,7 +54,6 @@ export class Guilds extends BaseResource<any, APIGuild | GatewayGuildCreateDispa
this.cache.stickers?.keys(id) ?? [], this.cache.stickers?.keys(id) ?? [],
this.cache.voiceStates?.keys(id) ?? [], this.cache.voiceStates?.keys(id) ?? [],
this.cache.presences?.keys(id) ?? [], this.cache.presences?.keys(id) ?? [],
this.cache.threads?.keys(id) ?? [],
this.cache.stageInstances?.keys(id) ?? [], this.cache.stageInstances?.keys(id) ?? [],
this.cache.bans?.keys(id) ?? [], this.cache.bans?.keys(id) ?? [],
]) ])
@ -80,7 +79,6 @@ export class Guilds extends BaseResource<any, APIGuild | GatewayGuildCreateDispa
this.cache.stickers?.hashId(id), this.cache.stickers?.hashId(id),
this.cache.voiceStates?.hashId(id), this.cache.voiceStates?.hashId(id),
this.cache.presences?.hashId(id), this.cache.presences?.hashId(id),
this.cache.threads?.hashId(id),
this.cache.stageInstances?.hashId(id), this.cache.stageInstances?.hashId(id),
].filter(Boolean) as string[], ].filter(Boolean) as string[],
); );
@ -109,6 +107,10 @@ export class Guilds extends BaseResource<any, APIGuild | GatewayGuildCreateDispa
bulkData.push(['overwrites', channel.permission_overwrites, channel.id, id]); bulkData.push(['overwrites', channel.permission_overwrites, channel.id, id]);
} }
for (const thread of data.threads ?? []) {
bulkData.push(['channels', thread, thread.id, id]);
}
for (const emoji of data.emojis ?? []) { for (const emoji of data.emojis ?? []) {
bulkData.push(['emojis', emoji, emoji.id, id]); bulkData.push(['emojis', emoji, emoji.id, id]);
} }
@ -125,10 +127,6 @@ export class Guilds extends BaseResource<any, APIGuild | GatewayGuildCreateDispa
bulkData.push(['presences', presence, presence.user.id, id]); bulkData.push(['presences', presence, presence.user.id, id]);
} }
for (const thread of data.threads ?? []) {
bulkData.push(['threads', thread, thread.id, id]);
}
for (const instance of data.stage_instances ?? []) { for (const instance of data.stage_instances ?? []) {
bulkData.push(['stageInstances', instance, instance.id, id]); bulkData.push(['stageInstances', instance, instance.id, id]);
} }
@ -170,14 +168,15 @@ export class Guilds extends BaseResource<any, APIGuild | GatewayGuildCreateDispa
for (const channel of data.channels ?? []) { for (const channel of data.channels ?? []) {
bulkData.push(['channels', channel, channel.id, id]); bulkData.push(['channels', channel, channel.id, id]);
}
for (const channel of data.channels ?? []) {
if (channel.permission_overwrites?.length) { if (channel.permission_overwrites?.length) {
bulkData.push(['overwrites', channel.permission_overwrites, channel.id, id]); bulkData.push(['overwrites', channel.permission_overwrites, channel.id, id]);
} }
} }
for (const thread of data.threads ?? []) {
bulkData.push(['channels', thread, thread.id, id]);
}
for (const emoji of data.emojis ?? []) { for (const emoji of data.emojis ?? []) {
bulkData.push(['emojis', emoji, emoji.id, id]); bulkData.push(['emojis', emoji, emoji.id, id]);
} }
@ -194,10 +193,6 @@ export class Guilds extends BaseResource<any, APIGuild | GatewayGuildCreateDispa
bulkData.push(['presences', presence, presence.user.id, id]); bulkData.push(['presences', presence, presence.user.id, id]);
} }
for (const thread of data.threads ?? []) {
bulkData.push(['threads', thread, thread.id, id]);
}
for (const instance of data.stage_instances ?? []) { for (const instance of data.stage_instances ?? []) {
bulkData.push(['stageInstances', instance, instance.id, id]); bulkData.push(['stageInstances', instance, instance.id, id]);
} }

View File

@ -24,7 +24,7 @@ export class Messages extends GuildRelatedResource<any, APIMessage> {
return this.cache.users && rawMessage?.user_id return this.cache.users && rawMessage?.user_id
? fakePromise(this.cache.adapter.get(this.cache.users.hashId(rawMessage.user_id)) as APIUser | undefined).then( ? fakePromise(this.cache.adapter.get(this.cache.users.hashId(rawMessage.user_id)) as APIUser | undefined).then(
user => { user => {
return user ? Transformers.Message(this.client, { ...rawMessage!, author: user }) : undefined; return user ? Transformers.Message(this.client, { ...rawMessage, author: user }) : undefined;
}, },
) )
: undefined; : undefined;
@ -44,7 +44,7 @@ export class Messages extends GuildRelatedResource<any, APIMessage> {
? fakePromise( ? fakePromise(
this.cache.adapter.get(this.cache.users.hashId(rawMessage.user_id)) as APIUser | undefined, this.cache.adapter.get(this.cache.users.hashId(rawMessage.user_id)) as APIUser | undefined,
).then(user => { ).then(user => {
return user ? Transformers.Message(this.client, { ...rawMessage!, author: user }) : undefined; return user ? Transformers.Message(this.client, { ...rawMessage, author: user }) : undefined;
}) })
: undefined; : undefined;
}) })
@ -59,7 +59,7 @@ export class Messages extends GuildRelatedResource<any, APIMessage> {
override values(channel: string): ReturnCache<MessageStructure[]> { override values(channel: string): ReturnCache<MessageStructure[]> {
return fakePromise(super.values(channel) as APIMessageResource[]).then(messages => { return fakePromise(super.values(channel) as APIMessageResource[]).then(messages => {
const hashes: (string | undefined)[] = this.cache.users const hashes: (string | undefined)[] = this.cache.users
? messages.map(x => (x.user_id ? this.cache.users!.hashId(x.user_id) : undefined)) ? messages.map(x => (x.user_id ? this.cache.users?.hashId(x.user_id) : undefined))
: []; : [];
return fakePromise(this.cache.adapter.bulkGet(hashes.filter(Boolean) as string[]) as APIUser[]).then(users => { return fakePromise(this.cache.adapter.bulkGet(hashes.filter(Boolean) as string[]) as APIUser[]).then(users => {
return messages return messages

View File

@ -1,44 +0,0 @@
import type { ReturnCache } from '../..';
import { type ThreadChannelStructure, Transformers } from '../../client/transformers';
import { fakePromise } from '../../common';
import type { APIThreadChannel } from '../../types';
import { GuildRelatedResource } from './default/guild-related';
export class Threads extends GuildRelatedResource<any, APIThreadChannel> {
namespace = 'thread';
//@ts-expect-error
filter(data: APIThreadChannel, id: string, guild_id?: string) {
return true;
}
override get(id: string): ReturnCache<ThreadChannelStructure | undefined> {
return fakePromise(super.get(id)).then(rawThread =>
rawThread ? Transformers.ThreadChannel(this.client, rawThread) : undefined,
);
}
raw(id: string): ReturnCache<APIThreadChannel | undefined> {
return super.get(id);
}
override bulk(ids: string[]): ReturnCache<ThreadChannelStructure[]> {
return fakePromise(super.bulk(ids) as APIThreadChannel[]).then(threads =>
threads.map(rawThread => Transformers.ThreadChannel(this.client, rawThread)),
);
}
bulkRaw(ids: string[]): ReturnCache<APIThreadChannel[]> {
return super.bulk(ids);
}
override values(guild: string): ReturnCache<ThreadChannelStructure[]> {
return fakePromise(super.values(guild) as APIThreadChannel[]).then(threads =>
threads.map(rawThread => Transformers.ThreadChannel(this.client, rawThread)),
);
}
valuesRaw(guild: string): ReturnCache<APIThreadChannel[]> {
return super.values(guild);
}
}

View File

@ -1,5 +1,5 @@
import { join } from 'node:path'; import { join } from 'node:path';
import { type APIRoutes, ApiHandler, Router } from '../api'; import { ApiHandler } from '../api';
import type { Adapter } from '../cache'; import type { Adapter } from '../cache';
import { Cache, MemoryAdapter } from '../cache'; import { Cache, MemoryAdapter } from '../cache';
import type { import type {
@ -57,7 +57,6 @@ import type { MessageStructure } from './transformers';
export class BaseClient { export class BaseClient {
rest!: ApiHandler; rest!: ApiHandler;
proxy!: APIRoutes;
cache!: Cache; cache!: Cache;
applications = new ApplicationShorter(this); applications = new ApplicationShorter(this);
@ -169,6 +168,10 @@ export class BaseClient {
); );
} }
get proxy() {
return this.rest.proxy;
}
set botId(id: string) { set botId(id: string) {
this._botId = id; this._botId = id;
} }
@ -188,7 +191,6 @@ export class BaseClient {
setServices({ rest, cache, langs, middlewares, handleCommand }: ServicesOptions) { setServices({ rest, cache, langs, middlewares, handleCommand }: ServicesOptions) {
if (rest) { if (rest) {
this.rest = rest; this.rest = rest;
this.proxy = new Router(this.rest).createProxy();
} }
if (cache) { if (cache) {
const caches: (keyof Cache['disabledCache'])[] = [ const caches: (keyof Cache['disabledCache'])[] = [
@ -204,7 +206,6 @@ export class BaseClient {
'roles', 'roles',
'stageInstances', 'stageInstances',
'stickers', 'stickers',
'threads',
'users', 'users',
'voiceStates', 'voiceStates',
]; ];
@ -233,8 +234,9 @@ export class BaseClient {
this.middlewares = middlewares; this.middlewares = middlewares;
} }
if (langs) { if (langs) {
if (langs.default) this.langs!.defaultLang = langs.default; this.langs ??= new LangsHandler(this.logger);
if (langs.aliases) this.langs!.aliases = Object.entries(langs.aliases); if (langs.default) this.langs.defaultLang = langs.default;
if (langs.aliases) this.langs.aliases = Object.entries(langs.aliases);
} }
if (handleCommand) this.handleCommand = new handleCommand(this); if (handleCommand) this.handleCommand = new handleCommand(this);
@ -273,7 +275,6 @@ export class BaseClient {
domain: 'https://discord.com', domain: 'https://discord.com',
debug, debug,
}); });
this.proxy = new Router(this.rest).createProxy();
} }
if (this.cache) { if (this.cache) {

View File

@ -30,6 +30,7 @@ import {
Webhook, Webhook,
WebhookMessage, WebhookMessage,
} from '../structures'; } from '../structures';
import { Entitlement } from '../structures/Entitlement';
import { GuildBan } from '../structures/GuildBan'; import { GuildBan } from '../structures/GuildBan';
import type { ChannelType } from '../types'; import type { ChannelType } from '../types';
@ -63,6 +64,7 @@ export type UserStructure = InferCustomStructure<User, 'User'>;
export type VoiceStateStructure = InferCustomStructure<VoiceState, 'VoiceState'>; export type VoiceStateStructure = InferCustomStructure<VoiceState, 'VoiceState'>;
export type WebhookStructure = InferCustomStructure<Webhook, 'Webhook'>; export type WebhookStructure = InferCustomStructure<Webhook, 'Webhook'>;
export type OptionResolverStructure = InferCustomStructure<OptionResolver, 'OptionResolver'>; export type OptionResolverStructure = InferCustomStructure<OptionResolver, 'OptionResolver'>;
export type EntitlementStructure = InferCustomStructure<Entitlement, 'Entitlement'>;
export const Transformers = { export const Transformers = {
AnonymousGuild(...args: ConstructorParameters<typeof AnonymousGuild>): AnonymousGuildStructure { AnonymousGuild(...args: ConstructorParameters<typeof AnonymousGuild>): AnonymousGuildStructure {
@ -157,6 +159,9 @@ export const Transformers = {
OptionResolver(...args: ConstructorParameters<typeof OptionResolver>): OptionResolverStructure { OptionResolver(...args: ConstructorParameters<typeof OptionResolver>): OptionResolverStructure {
return new OptionResolver(...args); return new OptionResolver(...args);
}, },
Entitlement(...args: ConstructorParameters<typeof Entitlement>): EntitlementStructure {
return new Entitlement(...args);
},
}; };
export type InferCustomStructure<T, N extends string> = CustomStructures extends Record<N, infer P> ? P : T; export type InferCustomStructure<T, N extends string> = CustomStructures extends Record<N, infer P> ? P : T;

View File

@ -60,28 +60,46 @@ export class CommandContext<
return this.resolver.fullCommandName; return this.resolver.fullCommandName;
} }
async write<FR extends boolean = false>( async write<WR extends boolean = false>(
body: InteractionCreateBodyRequest, body: InteractionCreateBodyRequest,
fetchReply?: FR, withResponse?: WR,
): Promise<When<FR, WebhookMessageStructure | MessageStructure, void | WebhookMessageStructure | MessageStructure>> { ): Promise<
if (this.interaction) return this.interaction.write(body, fetchReply); When<
WR,
WebhookMessageStructure | When<InferWithPrefix, MessageStructure, never>,
void | WebhookMessageStructure | When<InferWithPrefix, MessageStructure, never>
>
> {
if (this.interaction) return this.interaction.write(body, withResponse);
const options = (this.client as Client | WorkerClient).options?.commands; const options = (this.client as Client | WorkerClient).options?.commands;
return (this.messageResponse = await (this.message! as Message)[ return (this.messageResponse = await (this.message! as Message)[
!this.messageResponse && options?.reply?.(this) ? 'reply' : 'write' !this.messageResponse && options?.reply?.(this) ? 'reply' : 'write'
](body)); ](body)) as never;
} }
async deferReply(ephemeral = false) { async deferReply<WR extends boolean = false>(
if (this.interaction) return this.interaction.deferReply(ephemeral ? MessageFlags.Ephemeral : undefined); ephemeral = false,
withResponse?: WR,
): Promise<
When<
WR,
WebhookMessageStructure | When<InferWithPrefix, MessageStructure, never>,
When<InferWithPrefix, MessageStructure, never> | undefined
>
> {
if (this.interaction)
return this.interaction.deferReply(ephemeral ? MessageFlags.Ephemeral : undefined, withResponse);
const options = (this.client as Client | WorkerClient).options?.commands; const options = (this.client as Client | WorkerClient).options?.commands;
return (this.messageResponse = await (this.message! as Message)[options?.reply?.(this) ? 'reply' : 'write']( return (this.messageResponse = await (this.message! as Message)[options?.reply?.(this) ? 'reply' : 'write'](
options?.deferReplyResponse?.(this) ?? { content: 'Thinking...' }, options?.deferReplyResponse?.(this) ?? { content: 'Thinking...' },
)); )) as never;
} }
async editResponse(body: InteractionMessageUpdateBodyRequest) { async editResponse(
body: InteractionMessageUpdateBodyRequest,
): Promise<When<InferWithPrefix, WebhookMessageStructure | MessageStructure, WebhookMessageStructure>> {
if (this.interaction) return this.interaction.editResponse(body); if (this.interaction) return this.interaction.editResponse(body);
return (this.messageResponse = await this.messageResponse!.edit(body)); return (this.messageResponse = await this.messageResponse!.edit(body)) as never;
} }
deleteResponse() { deleteResponse() {
@ -89,15 +107,21 @@ export class CommandContext<
return this.messageResponse!.delete(); return this.messageResponse!.delete();
} }
editOrReply<FR extends boolean = false>( editOrReply<WR extends boolean = false>(
body: InteractionCreateBodyRequest | InteractionMessageUpdateBodyRequest, body: InteractionCreateBodyRequest | InteractionMessageUpdateBodyRequest,
fetchReply?: FR, withResponse?: WR,
): Promise<When<FR, WebhookMessageStructure | MessageStructure, void | WebhookMessageStructure | MessageStructure>> { ): Promise<
if (this.interaction) return this.interaction.editOrReply(body as InteractionCreateBodyRequest, fetchReply); When<
WR,
WebhookMessageStructure | When<InferWithPrefix, MessageStructure, never>,
void | WebhookMessageStructure | When<InferWithPrefix, MessageStructure, never>
>
> {
if (this.interaction) return this.interaction.editOrReply(body as InteractionCreateBodyRequest, withResponse);
if (this.messageResponse) { if (this.messageResponse) {
return this.editResponse(body); return this.editResponse(body);
} }
return this.write(body as InteractionCreateBodyRequest, fetchReply); return this.write(body as InteractionCreateBodyRequest, withResponse);
} }
async fetchResponse(): Promise< async fetchResponse(): Promise<

View File

@ -42,18 +42,18 @@ export class EntryPointContext<M extends keyof RegisteredMiddlewares = never> ex
return this.command.name; return this.command.name;
} }
write<FR extends boolean = false>( write<WR extends boolean = false>(
body: InteractionCreateBodyRequest, body: InteractionCreateBodyRequest,
fetchReply?: FR, withResponse?: WR,
): Promise<When<FR, WebhookMessageStructure, void | WebhookMessageStructure>> { ): Promise<When<WR, WebhookMessageStructure, void | WebhookMessageStructure>> {
return this.interaction.write(body, fetchReply); return this.interaction.write(body, withResponse);
} }
modal(body: ModalCreateBodyRequest) { modal(body: ModalCreateBodyRequest) {
return this.interaction.modal(body); return this.interaction.modal(body);
} }
deferReply(ephemeral = false) { deferReply<WR extends boolean = false>(ephemeral = false): Promise<When<WR, WebhookMessageStructure, undefined>> {
return this.interaction.deferReply(ephemeral ? MessageFlags.Ephemeral : undefined); return this.interaction.deferReply(ephemeral ? MessageFlags.Ephemeral : undefined);
} }
@ -65,11 +65,11 @@ export class EntryPointContext<M extends keyof RegisteredMiddlewares = never> ex
return this.interaction.deleteResponse(); return this.interaction.deleteResponse();
} }
editOrReply<FR extends boolean = false>( editOrReply<WR extends boolean = false>(
body: InteractionCreateBodyRequest | InteractionMessageUpdateBodyRequest, body: InteractionCreateBodyRequest | InteractionMessageUpdateBodyRequest,
fetchReply?: FR, withResponse?: WR,
): Promise<When<FR, WebhookMessageStructure | MessageStructure, void | WebhookMessageStructure | MessageStructure>> { ): Promise<When<WR, WebhookMessageStructure | MessageStructure, void | WebhookMessageStructure | MessageStructure>> {
return this.interaction.editOrReply(body as InteractionCreateBodyRequest, fetchReply); return this.interaction.editOrReply(body as InteractionCreateBodyRequest, withResponse);
} }
fetchResponse() { fetchResponse() {

View File

@ -67,18 +67,18 @@ export class MenuCommandContext<
return this.command.name; return this.command.name;
} }
write<FR extends boolean = false>( write<WR extends boolean = false>(
body: InteractionCreateBodyRequest, body: InteractionCreateBodyRequest,
fetchReply?: FR, withResponse?: WR,
): Promise<When<FR, WebhookMessageStructure, void | WebhookMessageStructure>> { ): Promise<When<WR, WebhookMessageStructure, void | WebhookMessageStructure>> {
return this.interaction.write(body, fetchReply); return this.interaction.write(body, withResponse);
} }
modal(body: ModalCreateBodyRequest) { modal(body: ModalCreateBodyRequest) {
return this.interaction.modal(body); return this.interaction.modal(body);
} }
deferReply(ephemeral = false) { deferReply<WR extends boolean = false>(ephemeral = false): Promise<When<WR, WebhookMessageStructure, undefined>> {
return this.interaction.deferReply(ephemeral ? MessageFlags.Ephemeral : undefined); return this.interaction.deferReply(ephemeral ? MessageFlags.Ephemeral : undefined);
} }
@ -90,11 +90,11 @@ export class MenuCommandContext<
return this.interaction.deleteResponse(); return this.interaction.deleteResponse();
} }
editOrReply<FR extends boolean = false>( editOrReply<WR extends boolean = false>(
body: InteractionCreateBodyRequest | InteractionMessageUpdateBodyRequest, body: InteractionCreateBodyRequest | InteractionMessageUpdateBodyRequest,
fetchReply?: FR, withResponse?: WR,
): Promise<When<FR, WebhookMessageStructure | MessageStructure, void | WebhookMessageStructure | MessageStructure>> { ): Promise<When<WR, WebhookMessageStructure | MessageStructure, void | WebhookMessageStructure | MessageStructure>> {
return this.interaction.editOrReply(body as InteractionCreateBodyRequest, fetchReply); return this.interaction.editOrReply(body as InteractionCreateBodyRequest, withResponse);
} }
fetchResponse() { fetchResponse() {

View File

@ -345,8 +345,10 @@ export async function resolveEmoji(emoji: EmojiResolvable, cache: Cache): Promis
return fromCache && { animated: fromCache.animated, id: fromCache.id, name: fromCache.name }; return fromCache && { animated: fromCache.animated, id: fromCache.id, name: fromCache.name };
} }
const fromCache = await cache.emojis?.get(emoji.id!); if (emoji.id) {
const fromCache = await cache.emojis?.get(emoji.id);
if (fromCache) return { animated: fromCache.animated, id: fromCache.id, name: fromCache.name }; if (fromCache) return { animated: fromCache.animated, id: fromCache.id, name: fromCache.name };
}
return; return;
} }

View File

@ -1,4 +1,4 @@
import { Entitlement } from '../../structures/Entitlement'; import { Transformers } from '../../client';
import type { import type {
APIEntitlement, APIEntitlement,
RESTGetAPIEntitlementsQuery, RESTGetAPIEntitlementsQuery,
@ -46,7 +46,7 @@ export class ApplicationShorter extends BaseShorter {
return this.client.proxy return this.client.proxy
.applications(applicationId) .applications(applicationId)
.entitlements.get({ query }) .entitlements.get({ query })
.then(et => et.map(e => new Entitlement(this.client, e))); .then(et => et.map(e => Transformers.Entitlement(this.client, e)));
} }
/** /**
@ -67,7 +67,7 @@ export class ApplicationShorter extends BaseShorter {
return this.client.proxy return this.client.proxy
.applications(applicationId) .applications(applicationId)
.entitlements.post({ body }) .entitlements.post({ body })
.then(et => new Entitlement(this.client, et as APIEntitlement)); .then(et => Transformers.Entitlement(this.client, et as APIEntitlement));
} }
/** /**

View File

@ -57,7 +57,7 @@ export class BanShorter extends BaseShorter {
} }
ban = await this.client.proxy.guilds(guildId).bans(userId).get(); ban = await this.client.proxy.guilds(guildId).bans(userId).get();
await this.client.cache.members?.set(ban.user!.id, guildId, ban); await this.client.cache.members?.set(ban.user.id, guildId, ban);
return Transformers.GuildBan(this.client, ban, guildId); return Transformers.GuildBan(this.client, ban, guildId);
} }
@ -78,7 +78,7 @@ export class BanShorter extends BaseShorter {
query, query,
}); });
await this.client.cache.bans?.set( await this.client.cache.bans?.set(
bans.map<[string, APIBan]>(x => [x.user!.id, x]), bans.map<[string, APIBan]>(x => [x.user.id, x]),
guildId, guildId,
); );
return bans.map(m => Transformers.GuildBan(this.client, m, guildId)); return bans.map(m => Transformers.GuildBan(this.client, m, guildId));

View File

@ -50,9 +50,9 @@ export class ChannelShorter extends BaseShorter {
* @returns A Promise that resolves to the deleted channel. * @returns A Promise that resolves to the deleted channel.
*/ */
async delete(id: string, optional: ChannelShorterOptionalParams = { guildId: '@me' }): Promise<AllChannels> { async delete(id: string, optional: ChannelShorterOptionalParams = { guildId: '@me' }): Promise<AllChannels> {
const options = MergeOptions<ChannelShorterOptionalParams>({ guildId: '@me' }, optional); const options = MergeOptions<MakeRequired<ChannelShorterOptionalParams, 'guildId'>>({ guildId: '@me' }, optional);
const res = await this.client.proxy.channels(id).delete({ reason: options.reason }); const res = await this.client.proxy.channels(id).delete({ reason: options.reason });
await this.client.cache.channels?.removeIfNI(BaseChannel.__intent__(options.guildId!), res.id, options.guildId!); await this.client.cache.channels?.removeIfNI(BaseChannel.__intent__(options.guildId), res.id, options.guildId);
return channelFrom(res, this.client); return channelFrom(res, this.client);
} }
@ -70,7 +70,7 @@ export class ChannelShorter extends BaseShorter {
): Promise<AllChannels> { ): Promise<AllChannels> {
const options = MergeOptions<MakeRequired<ChannelShorterOptionalParams, 'guildId'>>({ guildId: '@me' }, optional); const options = MergeOptions<MakeRequired<ChannelShorterOptionalParams, 'guildId'>>({ guildId: '@me' }, optional);
const res = await this.client.proxy.channels(id).patch({ body, reason: options.reason }); const res = await this.client.proxy.channels(id).patch({ body, reason: options.reason });
await this.client.cache.channels?.setIfNI(BaseChannel.__intent__(options.guildId!), res.id, options.guildId!, res); await this.client.cache.channels?.setIfNI(BaseChannel.__intent__(options.guildId), res.id, options.guildId, res);
if (body.permission_overwrites && 'permission_overwrites' in res && res.permission_overwrites) if (body.permission_overwrites && 'permission_overwrites' in res && res.permission_overwrites)
await this.client.cache.overwrites?.setIfNI( await this.client.cache.overwrites?.setIfNI(
BaseChannel.__intent__(options.guildId), BaseChannel.__intent__(options.guildId),

View File

@ -58,12 +58,7 @@ export class GuildShorter extends BaseShorter {
* @returns The generated widget URL. * @returns The generated widget URL.
*/ */
widgetURL(id: string, style?: GuildWidgetStyle) { widgetURL(id: string, style?: GuildWidgetStyle) {
const query = new URLSearchParams(); return this.client.proxy.guilds(id).widget.get({ query: { style } });
if (style) {
query.append('style', style);
}
return this.client.proxy.guilds(id).widget.get({ query });
} }
async edit(guildId: string, body: RESTPatchAPIGuildJSONBody, reason?: string) { async edit(guildId: string, body: RESTPatchAPIGuildJSONBody, reason?: string) {

View File

@ -4,7 +4,7 @@ import type { InteractionMessageUpdateBodyRequest, MessageWebhookCreateBodyReque
import { BaseShorter } from './base'; import { BaseShorter } from './base';
export class InteractionShorter extends BaseShorter { export class InteractionShorter extends BaseShorter {
async reply(id: string, token: string, body: ReplyInteractionBody) { async reply(id: string, token: string, body: ReplyInteractionBody, withResponse = false) {
//@ts-expect-error //@ts-expect-error
const { files, ...rest } = body.data ?? {}; const { files, ...rest } = body.data ?? {};
//@ts-expect-error //@ts-expect-error
@ -22,6 +22,7 @@ export class InteractionShorter extends BaseShorter {
this.client, this.client,
), ),
files: parsedFiles, files: parsedFiles,
query: { with_response: withResponse },
}); });
} }
@ -50,16 +51,16 @@ export class InteractionShorter extends BaseShorter {
return this.editMessage(token, '@original', body); return this.editMessage(token, '@original', body);
} }
deleteResponse(interactionId: string, token: string, messageId: string) { deleteResponse(token: string, messageId: string) {
return this.client.proxy return this.client.proxy
.webhooks(this.client.applicationId)(token) .webhooks(this.client.applicationId)(token)
.messages(messageId) .messages(messageId)
.delete() .delete()
.then(() => this.client.components?.onMessageDelete(messageId === '@original' ? interactionId : messageId)); .then(() => this.client.components?.deleteValue(messageId, 'messageDelete'));
} }
deleteOriginal(interactionId: string, token: string) { deleteOriginal(token: string) {
return this.deleteResponse(interactionId, token, '@original'); return this.deleteResponse(token, '@original');
} }
async followup(token: string, { files, ...body }: MessageWebhookCreateBodyRequest) { async followup(token: string, { files, ...body }: MessageWebhookCreateBodyRequest) {

View File

@ -53,21 +53,20 @@ export class MemberShorter extends BaseShorter {
query, query,
}); });
await this.client.cache.members?.set( await this.client.cache.members?.set(
members.map(x => [x.user!.id, x]), members.map(x => [x.user.id, x] as [string, APIGuildMember]),
guildId, guildId,
); );
return members.map(m => Transformers.GuildMember(this.client, m, m.user!, guildId)); return members.map(m => Transformers.GuildMember(this.client, m, m.user, guildId));
} }
/** /**
* Unbans a member from the guild. * Unbans a member from the guild.
* @param guildId The ID of the guild. * @param guildId The ID of the guild.
* @param memberId The ID of the member to unban. * @param memberId The ID of the member to unban.
* @param body The request body for unbanning the member.
* @param reason The reason for unbanning the member. * @param reason The reason for unbanning the member.
*/ */
async unban(guildId: string, memberId: string, body?: RESTPutAPIGuildBanJSONBody, reason?: string) { async unban(guildId: string, memberId: string, reason?: string) {
await this.client.proxy.guilds(guildId).bans(memberId).delete({ reason, body }); await this.client.proxy.guilds(guildId).bans(memberId).delete({ reason });
} }
/** /**
@ -104,7 +103,7 @@ export class MemberShorter extends BaseShorter {
async edit(guildId: string, memberId: string, body: RESTPatchAPIGuildMemberJSONBody, reason?: string) { async edit(guildId: string, memberId: string, body: RESTPatchAPIGuildMemberJSONBody, reason?: string) {
const member = await this.client.proxy.guilds(guildId).members(memberId).patch({ body, reason }); const member = await this.client.proxy.guilds(guildId).members(memberId).patch({ body, reason });
await this.client.cache.members?.setIfNI('GuildMembers', memberId, guildId, member); await this.client.cache.members?.setIfNI('GuildMembers', memberId, guildId, member);
return Transformers.GuildMember(this.client, member, member.user!, guildId); return Transformers.GuildMember(this.client, member, member.user, guildId);
} }
/** /**
@ -124,9 +123,9 @@ export class MemberShorter extends BaseShorter {
return; return;
} }
await this.client.cache.members?.setIfNI('GuildMembers', member.user!.id, guildId, member); await this.client.cache.members?.setIfNI('GuildMembers', member.user.id, guildId, member);
return Transformers.GuildMember(this.client, member, member.user!, guildId); return Transformers.GuildMember(this.client, member, member.user, guildId);
} }
/** /**
@ -169,8 +168,8 @@ export class MemberShorter extends BaseShorter {
members = await this.client.proxy.guilds(guildId).members.get({ members = await this.client.proxy.guilds(guildId).members.get({
query, query,
}); });
await this.client.cache.members?.set(members.map(x => [x.user!.id, x]) as [string, APIGuildMember][], guildId); await this.client.cache.members?.set(members.map(x => [x.user.id, x]) as [string, APIGuildMember][], guildId);
return members.map(m => Transformers.GuildMember(this.client, m, m.user!, guildId)); return members.map(m => Transformers.GuildMember(this.client, m, m.user, guildId));
} }
/** /**
@ -180,7 +179,7 @@ export class MemberShorter extends BaseShorter {
* @param id The ID of the role to add. * @param id The ID of the role to add.
*/ */
addRole(guildId: string, memberId: string, id: string) { addRole(guildId: string, memberId: string, id: string) {
return this.client.proxy.guilds(guildId).members(memberId).roles(id).put({}); return this.client.proxy.guilds(guildId).members(memberId).roles(id).put();
} }
/** /**
* Removes a role from a guild member. * Removes a role from a guild member.

View File

@ -65,7 +65,7 @@ export class MessageShorter extends BaseShorter {
.delete({ reason }) .delete({ reason })
.then(async () => { .then(async () => {
await this.client.cache.messages?.removeIfNI('GuildMessages', messageId, channelId); await this.client.cache.messages?.removeIfNI('GuildMessages', messageId, channelId);
this.client.components?.onMessageDelete(messageId); this.client.components?.deleteValue(messageId, 'messageDelete');
}); });
} }

View File

@ -28,7 +28,7 @@ export class TemplateShorter extends BaseShorter {
return this.client.proxy return this.client.proxy
.guilds(guildId) .guilds(guildId)
.templates(code) .templates(code)
.put({}) .put()
.then(template => Transformers.GuildTemplate(this.client, template)); .then(template => Transformers.GuildTemplate(this.client, template));
} }

View File

@ -1,6 +1,7 @@
import type { ThreadChannelStructure } from '../../client/transformers'; import type { ThreadChannelStructure } from '../../client/transformers';
import { channelFrom } from '../../structures'; import { channelFrom } from '../../structures';
import type { import type {
APIThreadChannel,
APIThreadMember, APIThreadMember,
RESTGetAPIChannelThreadMembersQuery, RESTGetAPIChannelThreadMembersQuery,
RESTGetAPIChannelThreadsArchivedQuery, RESTGetAPIChannelThreadsArchivedQuery,
@ -29,7 +30,15 @@ export class ThreadShorter extends BaseShorter {
.channels(channelId) .channels(channelId)
.threads.post({ body, reason }) .threads.post({ body, reason })
// When testing this, discord returns the thread object, but in discord api types it does not. // When testing this, discord returns the thread object, but in discord api types it does not.
.then(thread => channelFrom(thread, this.client) as ThreadChannelStructure) .then(async thread => {
await this.client.cache.channels?.setIfNI(
'Guilds',
thread.id,
(thread as APIThreadChannel).guild_id!,
thread,
);
return channelFrom(thread, this.client) as ThreadChannelStructure;
})
); );
} }
@ -44,30 +53,33 @@ export class ThreadShorter extends BaseShorter {
.channels(channelId) .channels(channelId)
.messages(messageId) .messages(messageId)
.threads.post({ body, reason }) .threads.post({ body, reason })
.then(thread => channelFrom(thread, this.client) as ThreadChannelStructure); .then(async thread => {
await this.client.cache.channels?.setIfNI('Guilds', thread.id, (thread as APIThreadChannel).guild_id!, thread);
return channelFrom(thread, this.client) as ThreadChannelStructure;
});
} }
async join(threadId: string) { join(threadId: string) {
return this.client.proxy.channels(threadId)['thread-members']('@me').put(); return this.client.proxy.channels(threadId)['thread-members']('@me').put();
} }
async leave(threadId: string) { leave(threadId: string) {
return this.client.proxy.channels(threadId)['thread-members']('@me').delete(); return this.client.proxy.channels(threadId)['thread-members']('@me').delete();
} }
async lock(threadId: string, locked = true, reason?: string) { lock(threadId: string, locked = true, reason?: string) {
return this.edit(threadId, { locked }, reason).then(x => channelFrom(x, this.client) as ThreadChannelStructure); return this.edit(threadId, { locked }, reason).then(x => channelFrom(x, this.client) as ThreadChannelStructure);
} }
async edit(threadId: string, body: RESTPatchAPIChannelJSONBody, reason?: string) { edit(threadId: string, body: RESTPatchAPIChannelJSONBody, reason?: string) {
return this.client.channels.edit(threadId, body, { reason }); return this.client.channels.edit(threadId, body, { reason });
} }
async removeMember(threadId: string, memberId: string) { removeMember(threadId: string, memberId: string) {
return this.client.proxy.channels(threadId)['thread-members'](memberId).delete(); return this.client.proxy.channels(threadId)['thread-members'](memberId).delete();
} }
async fetchMember<WithMember extends boolean = false>( fetchMember<WithMember extends boolean = false>(
threadId: string, threadId: string,
memberId: string, memberId: string,
with_member: WithMember, with_member: WithMember,
@ -79,11 +91,11 @@ export class ThreadShorter extends BaseShorter {
}) as never; }) as never;
} }
async addMember(threadId: string, memberId: string) { addMember(threadId: string, memberId: string) {
return this.client.proxy.channels(threadId)['thread-members'](memberId).put(); return this.client.proxy.channels(threadId)['thread-members'](memberId).put();
} }
async listMembers<T extends RESTGetAPIChannelThreadMembersQuery = RESTGetAPIChannelThreadMembersQuery>( listMembers<T extends RESTGetAPIChannelThreadMembersQuery = RESTGetAPIChannelThreadMembersQuery>(
threadId: string, threadId: string,
query?: T, query?: T,
): Promise<InferWithMemberOnList<T>> { ): Promise<InferWithMemberOnList<T>> {

View File

@ -146,7 +146,7 @@ export class WebhookShorter extends BaseShorter {
const message = await this.client.proxy const message = await this.client.proxy
.webhooks(webhookId)(token) .webhooks(webhookId)(token)
.messages(messageId) .messages(messageId)
.get({ auth: false, query: { threadId } }); .get({ auth: false, query: threadId ? { thread_id: threadId } : undefined });
return message ? Transformers.WebhookMessage(this.client, message, webhookId, token) : undefined; return message ? Transformers.WebhookMessage(this.client, message, webhookId, token) : undefined;
} }

View File

@ -12,7 +12,9 @@ import type { ModalContext } from './modalcontext';
type COMPONENTS = { type COMPONENTS = {
components: { match: string | string[] | RegExp; callback: ComponentCallback }[]; components: { match: string | string[] | RegExp; callback: ComponentCallback }[];
options?: ListenerOptions; options?: ListenerOptions;
messageId?: string; messageId: string;
channelId: string;
guildId: string | undefined;
idle?: NodeJS.Timeout; idle?: NodeJS.Timeout;
timeout?: NodeJS.Timeout; timeout?: NodeJS.Timeout;
__run: (customId: string | string[] | RegExp, callback: ComponentCallback) => any; __run: (customId: string | string[] | RegExp, callback: ComponentCallback) => any;
@ -20,11 +22,18 @@ type COMPONENTS = {
export type CollectorInteraction = ComponentInteraction | StringSelectMenuInteraction; export type CollectorInteraction = ComponentInteraction | StringSelectMenuInteraction;
export type ComponentCommands = ComponentCommand | ModalCommand; export type ComponentCommands = ComponentCommand | ModalCommand;
export interface CreateComponentCollectorResult {
run<T extends CollectorInteraction = CollectorInteraction>(
customId: string | string[] | RegExp,
callback: ComponentCallback<T>,
): any;
stop(reason?: string): any;
}
export class ComponentHandler extends BaseHandler { export class ComponentHandler extends BaseHandler {
onFail: OnFailCallback = err => this.logger.warn('<Client>.components.onFail', err); onFail: OnFailCallback = err => this.logger.warn('<Client>.components.onFail', err);
readonly values = new Map<string, COMPONENTS>(); readonly values = new Map<string, COMPONENTS>();
// 10 minutes timeout, because discord dont send an event when the user cancel the modal // 10 minutes of timeout by default, because discord doesnt send an event when the user cancels the modal
readonly modals = new LimitedCollection<string, ModalSubmitCallback>({ expire: 60e3 * 10 }); readonly modals = new LimitedCollection<string, ModalSubmitCallback>({ expire: 60e3 * 10 });
readonly commands: ComponentCommands[] = []; readonly commands: ComponentCommands[] = [];
filter = (path: string) => path.endsWith('.js') || (!path.endsWith('.d.ts') && path.endsWith('.ts')); filter = (path: string) => path.endsWith('.js') || (!path.endsWith('.d.ts') && path.endsWith('.ts'));
@ -38,23 +47,22 @@ export class ComponentHandler extends BaseHandler {
createComponentCollector( createComponentCollector(
messageId: string, messageId: string,
channelId: string,
guildId: string | undefined,
options: ListenerOptions = {}, options: ListenerOptions = {},
): { ): CreateComponentCollectorResult {
run<T extends CollectorInteraction = CollectorInteraction>(
customId: string | string[] | RegExp,
callback: ComponentCallback<T>,
): any;
stop(reason?: string): any;
} {
this.values.set(messageId, { this.values.set(messageId, {
components: [], messageId,
channelId,
guildId,
options, options,
components: [],
idle: idle:
options.idle && options.idle > 0 options.idle && options.idle > 0
? setTimeout(() => { ? setTimeout(() => {
this.deleteValue(messageId); this.deleteValue(messageId);
options.onStop?.('idle', () => { options.onStop?.('idle', () => {
this.createComponentCollector(messageId, options); this.createComponentCollector(messageId, channelId, guildId, options);
}); });
}, options.idle) }, options.idle)
: undefined, : undefined,
@ -63,7 +71,7 @@ export class ComponentHandler extends BaseHandler {
? setTimeout(() => { ? setTimeout(() => {
this.deleteValue(messageId); this.deleteValue(messageId);
options.onStop?.('timeout', () => { options.onStop?.('timeout', () => {
this.createComponentCollector(messageId, options); this.createComponentCollector(messageId, channelId, guildId, options);
}); });
}, options.timeout) }, options.timeout)
: undefined, : undefined,
@ -83,7 +91,7 @@ export class ComponentHandler extends BaseHandler {
stop: (reason?: string) => { stop: (reason?: string) => {
this.deleteValue(messageId); this.deleteValue(messageId);
options.onStop?.(reason, () => { options.onStop?.(reason, () => {
this.createComponentCollector(messageId, options); this.createComponentCollector(messageId, channelId, guildId, options);
}); });
}, },
}; };
@ -98,13 +106,15 @@ export class ComponentHandler extends BaseHandler {
}); });
if (!component) return; if (!component) return;
if (row.options?.filter) { if (row.options?.filter) {
if (!(await row.options.filter(interaction))) return; if (!(await row.options.filter(interaction))) return row.options.onPass?.(interaction);
} }
row.idle?.refresh(); row.idle?.refresh();
await component.callback( await component.callback(
interaction, interaction,
reason => { reason => {
row.options?.onStop?.(reason ?? 'stop'); row.options?.onStop?.(reason ?? 'stop', () => {
this.createComponentCollector(row.messageId, row.channelId, row.guildId, row.options);
});
this.deleteValue(id); this.deleteValue(id);
}, },
() => { () => {
@ -143,17 +153,15 @@ export class ComponentHandler extends BaseHandler {
deleteValue(id: string, reason?: string) { deleteValue(id: string, reason?: string) {
const component = this.values.get(id); const component = this.values.get(id);
if (component) { if (component) {
if (reason !== undefined) component.options?.onStop?.(reason); component.options?.onStop?.(reason, () => {
this.createComponentCollector(component.messageId, component.channelId, component.guildId, component.options);
});
clearTimeout(component.timeout); clearTimeout(component.timeout);
clearTimeout(component.idle); clearTimeout(component.idle);
this.values.delete(id); this.values.delete(id);
} }
} }
onMessageDelete(id: string) {
this.deleteValue(id, 'messageDelete');
}
stablishDefaults(component: ComponentCommands) { stablishDefaults(component: ComponentCommands) {
component.props ??= this.client.options.commands?.defaults?.props ?? {}; component.props ??= this.client.options.commands?.defaults?.props ?? {};
const is = component instanceof ModalCommand ? 'modals' : 'components'; const is = component instanceof ModalCommand ? 'modals' : 'components';
@ -222,7 +230,7 @@ export class ComponentHandler extends BaseHandler {
); );
if (!component?.__filePath) return null; if (!component?.__filePath) return null;
delete require.cache[component.__filePath]; delete require.cache[component.__filePath];
const index = this.client.components.commands.findIndex(x => x.__filePath === component.__filePath!); const index = this.client.components.commands.findIndex(x => x.__filePath === component.__filePath);
if (index === -1) return null; if (index === -1) return null;
this.client.components.commands.splice(index, 1); this.client.components.commands.splice(index, 1);
const imported = await magicImport(component.__filePath).then(x => x.default ?? x); const imported = await magicImport(component.__filePath).then(x => x.default ?? x);

View File

@ -12,11 +12,15 @@ import {
} from '../common'; } from '../common';
import type { ClientEvents } from '../events/hooks'; import type { ClientEvents } from '../events/hooks';
import * as RawEvents from '../events/hooks'; import * as RawEvents from '../events/hooks';
import type { import {
GatewayDispatchPayload, type APIThreadChannel,
GatewayMessageCreateDispatch, ChannelType,
GatewayMessageDeleteBulkDispatch, type GatewayChannelDeleteDispatch,
GatewayMessageDeleteDispatch, type GatewayDispatchPayload,
type GatewayGuildDeleteDispatch,
type GatewayMessageDeleteBulkDispatch,
type GatewayMessageDeleteDispatch,
type GatewayThreadDeleteDispatch,
} from '../types'; } from '../types';
import type { ClientEvent, ClientNameEvents, CustomEvents, CustomEventsKeys, EventContext } from './event'; import type { ClientEvent, ClientNameEvents, CustomEvents, CustomEventsKeys, EventContext } from './event';
@ -103,33 +107,78 @@ export class EventHandler extends BaseHandler {
async execute(name: GatewayEvents, ...args: [GatewayDispatchPayload, Client<true> | WorkerClient<true>, number]) { async execute(name: GatewayEvents, ...args: [GatewayDispatchPayload, Client<true> | WorkerClient<true>, number]) {
switch (name) { switch (name) {
case 'MESSAGE_CREATE':
{
const { d: data } = args[0] as GatewayMessageCreateDispatch;
if (args[1].components?.values.has(data.interaction_metadata?.id ?? data.id)) {
args[1].components.values.get(data.interaction_metadata!.id ?? data.id)!.messageId = data.id;
}
}
break;
case 'MESSAGE_DELETE': case 'MESSAGE_DELETE':
{ {
if (!args[1].components?.values.size) break;
const { d: data } = args[0] as GatewayMessageDeleteDispatch; const { d: data } = args[0] as GatewayMessageDeleteDispatch;
const value = [...(args[1].components?.values ?? [])].find(x => x[1].messageId === data.id); const value = args[1].components.values.get(data.id);
if (value) { if (value) {
args[1].components!.onMessageDelete(value[0]); args[1].components.deleteValue(value.messageId, 'messageDelete');
} }
} }
break; break;
case 'MESSAGE_DELETE_BULK': case 'MESSAGE_DELETE_BULK':
{ {
const { d: data } = args[0] as GatewayMessageDeleteBulkDispatch; if (!args[1].components?.values.size) break;
const values = [...(args[1].components?.values ?? [])]; const { d: payload } = args[0] as GatewayMessageDeleteBulkDispatch;
data.ids.forEach(id => { for (const id of payload.ids) {
const value = values.find(x => x[1].messageId === id); const value = args[1].components.values.get(id);
if (value) { if (value) {
args[1].components!.onMessageDelete(value[0]); args[1].components.deleteValue(value.messageId, 'messageDelete');
}
}
}
break;
case 'GUILD_DELETE':
{
if (!args[1].components?.values.size) break;
const { d: payload } = args[0] as GatewayGuildDeleteDispatch;
// ignore unavailable guilds?
if (payload.unavailable) break;
for (const [messageId, value] of args[1].components.values) {
if (value.guildId === payload.id) args[1].components.deleteValue(messageId, 'guildDelete');
}
}
break;
case 'CHANNEL_DELETE':
{
if (!args[1].components?.values.size) break;
const { d: payload } = args[0] as GatewayChannelDeleteDispatch;
if (payload.type === ChannelType.DM || payload.type === ChannelType.GroupDM) {
for (const value of args[1].components.values) {
if (payload.id === value[1].channelId) args[1].components.deleteValue(value[0], 'channelDelete');
}
} else {
if (!payload.guild_id) break;
// this is why we dont recommend to use collectors, use ComponentCommand instead
const channels = await args[1].cache.channels?.valuesRaw(payload.guild_id);
const threads = channels
?.filter(
x =>
[ChannelType.PublicThread, ChannelType.PrivateThread, ChannelType.AnnouncementThread].includes(
x.type,
) && (x as APIThreadChannel).parent_id === payload.id,
)
.map(x => x.id);
for (const value of args[1].components.values) {
const channelId = value[1].channelId;
if (payload.id === channelId || threads?.includes(channelId)) {
args[1].components.deleteValue(value[0], 'channelDelete');
}
}
}
}
break;
case 'THREAD_DELETE':
{
if (!args[1].components?.values.size) break;
const { d: payload } = args[0] as GatewayThreadDeleteDispatch;
for (const value of args[1].components.values) {
if (value[1].channelId === payload.id) {
args[1].components.deleteValue(value[0], 'channelDelete');
}
} }
});
} }
break; break;
} }
@ -166,7 +215,7 @@ export class EventHandler extends BaseHandler {
t: name, t: name,
d: packet, d: packet,
} as GatewayDispatchPayload); } as GatewayDispatchPayload);
await Event.run(hook, client, shardId); await (Event.run as any)(hook, client, shardId);
} catch (e) { } catch (e) {
await this.onFail(name, e); await this.onFail(name, e);
} }

View File

@ -1,15 +1,15 @@
import { Transformers } from '../../client';
import type { UsingClient } from '../../commands'; import type { UsingClient } from '../../commands';
import { Entitlement } from '../../structures/Entitlement';
import type { APIEntitlement } from '../../types'; import type { APIEntitlement } from '../../types';
export const ENTITLEMENT_CREATE = (client: UsingClient, data: APIEntitlement) => { export const ENTITLEMENT_CREATE = (client: UsingClient, data: APIEntitlement) => {
return new Entitlement(client, data); return Transformers.Entitlement(client, data);
}; };
export const ENTITLEMENT_UPDATE = (client: UsingClient, data: APIEntitlement) => { export const ENTITLEMENT_UPDATE = (client: UsingClient, data: APIEntitlement) => {
return new Entitlement(client, data); return Transformers.Entitlement(client, data);
}; };
export const ENTITLEMENT_DELETE = (client: UsingClient, data: APIEntitlement) => { export const ENTITLEMENT_DELETE = (client: UsingClient, data: APIEntitlement) => {
return new Entitlement(client, data); return Transformers.Entitlement(client, data);
}; };

View File

@ -62,7 +62,7 @@ export const GUILD_INTEGRATIONS_UPDATE = (_self: UsingClient, data: GatewayGuild
}; };
export const GUILD_MEMBER_ADD = (self: UsingClient, data: GatewayGuildMemberAddDispatchData) => { export const GUILD_MEMBER_ADD = (self: UsingClient, data: GatewayGuildMemberAddDispatchData) => {
return Transformers.GuildMember(self, data, data.user!, data.guild_id); return Transformers.GuildMember(self, data, data.user, data.guild_id);
}; };
export const GUILD_MEMBER_REMOVE = (self: UsingClient, data: GatewayGuildMemberRemoveDispatchData) => { export const GUILD_MEMBER_REMOVE = (self: UsingClient, data: GatewayGuildMemberRemoveDispatchData) => {
@ -72,7 +72,7 @@ export const GUILD_MEMBER_REMOVE = (self: UsingClient, data: GatewayGuildMemberR
export const GUILD_MEMBERS_CHUNK = (self: UsingClient, data: GatewayGuildMembersChunkDispatchData) => { export const GUILD_MEMBERS_CHUNK = (self: UsingClient, data: GatewayGuildMembersChunkDispatchData) => {
return { return {
...toCamelCase(data), ...toCamelCase(data),
members: data.members.map(x => Transformers.GuildMember(self, x, x.user!, data.guild_id)), members: data.members.map(x => Transformers.GuildMember(self, x, x.user, data.guild_id)),
}; };
}; };

View File

@ -11,7 +11,7 @@ export const INTEGRATION_CREATE = (self: UsingClient, data: GatewayIntegrationCr
return data.user return data.user
? { ? {
...toCamelCase(data), ...toCamelCase(data),
user: Transformers.User(self, data.user!), user: Transformers.User(self, data.user),
} }
: toCamelCase(data); : toCamelCase(data);
}; };
@ -20,7 +20,7 @@ export const INTEGRATION_UPDATE = (self: UsingClient, data: GatewayIntegrationUp
return data.user return data.user
? { ? {
...toCamelCase(data), ...toCamelCase(data),
user: Transformers.User(self, data.user!), user: Transformers.User(self, data.user),
} }
: toCamelCase(data); : toCamelCase(data);
}; };

View File

@ -34,5 +34,5 @@ export const THREAD_UPDATE = async (
self: UsingClient, self: UsingClient,
data: GatewayThreadUpdateDispatchData, data: GatewayThreadUpdateDispatchData,
): Promise<[thread: ThreadChannelStructure, old?: ThreadChannelStructure]> => { ): Promise<[thread: ThreadChannelStructure, old?: ThreadChannelStructure]> => {
return [Transformers.ThreadChannel(self, data), await self.cache.threads?.get(data.id)]; return [Transformers.ThreadChannel(self, data), (await self.cache.channels?.get(data.id)) as ThreadChannelStructure];
}; };

View File

@ -7,7 +7,7 @@ export const TYPING_START = (self: UsingClient, data: GatewayTypingStartDispatch
return data.member return data.member
? { ? {
...toCamelCase(data), ...toCamelCase(data),
member: Transformers.GuildMember(self, data.member, data.member.user!, data.guild_id!), member: Transformers.GuildMember(self, data.member, data.member.user, data.guild_id!),
} }
: toCamelCase(data); : toCamelCase(data);
}; };

View File

@ -1,3 +1,4 @@
export * from './client';
import { import {
BaseClient, BaseClient,
type BaseClientOptions, type BaseClientOptions,
@ -24,9 +25,6 @@ export * from './langs';
export { ShardManager, WorkerManager } from './websocket/discord'; export { ShardManager, WorkerManager } from './websocket/discord';
// //
export * from './structures'; export * from './structures';
//
export * from './client';
///
/** /**
* Creates an event with the specified data and run function. * Creates an event with the specified data and run function.

View File

@ -121,8 +121,7 @@ export class BaseGuildMember extends DiscordBase {
return { return {
resolve: (resolve: GuildMemberResolvable) => client.members.resolve(guildId, resolve), resolve: (resolve: GuildMemberResolvable) => client.members.resolve(guildId, resolve),
search: (query?: RESTGetAPIGuildMembersSearchQuery) => client.members.search(guildId, query), search: (query?: RESTGetAPIGuildMembersSearchQuery) => client.members.search(guildId, query),
unban: (id: string, body?: RESTPutAPIGuildBanJSONBody, reason?: string) => unban: (id: string, reason?: string) => client.members.unban(guildId, id, reason),
client.members.unban(guildId, id, body, reason),
ban: (id: string, body?: RESTPutAPIGuildBanJSONBody, reason?: string) => ban: (id: string, body?: RESTPutAPIGuildBanJSONBody, reason?: string) =>
client.members.ban(guildId, id, body, reason), client.members.ban(guildId, id, body, reason),
kick: (id: string, reason?: string) => client.members.kick(guildId, id, reason), kick: (id: string, reason?: string) => client.members.kick(guildId, id, reason),

View File

@ -39,11 +39,13 @@ import {
type MessageFlags, type MessageFlags,
type RESTAPIAttachment, type RESTAPIAttachment,
type RESTPostAPIInteractionCallbackJSONBody, type RESTPostAPIInteractionCallbackJSONBody,
type RESTPostAPIInteractionCallbackResult,
} from '../types'; } from '../types';
import type { RawFile } from '../api'; import type { RawFile } from '../api';
import { ActionRow, Embed, Modal, PollBuilder, resolveAttachment, resolveFiles } from '../builders'; import { ActionRow, Embed, Modal, PollBuilder, resolveAttachment, resolveFiles } from '../builders';
import { import {
type EntitlementStructure,
type GuildRoleStructure, type GuildRoleStructure,
type InteractionGuildMemberStructure, type InteractionGuildMemberStructure,
type MessageStructure, type MessageStructure,
@ -69,7 +71,6 @@ import {
} from '../common'; } from '../common';
import { mix } from '../deps/mixer'; import { mix } from '../deps/mixer';
import { type AllChannels, channelFrom } from './'; import { type AllChannels, channelFrom } from './';
import { Entitlement } from './Entitlement';
import { DiscordBase } from './extra/DiscordBase'; import { DiscordBase } from './extra/DiscordBase';
import { PermissionsBitField } from './extra/Permissions'; import { PermissionsBitField } from './extra/Permissions';
@ -100,8 +101,9 @@ export class BaseInteraction<
member!: When<FromGuild, InteractionGuildMemberStructure, undefined>; member!: When<FromGuild, InteractionGuildMemberStructure, undefined>;
channel?: AllChannels; channel?: AllChannels;
message?: MessageStructure; message?: MessageStructure;
replied?: Promise<boolean> | boolean; replied?: Promise<boolean | RESTPostAPIInteractionCallbackResult | undefined> | boolean;
appPermissions?: PermissionsBitField; appPermissions?: PermissionsBitField;
entitlements: EntitlementStructure[];
constructor( constructor(
readonly client: UsingClient, readonly client: UsingClient,
@ -128,7 +130,7 @@ export class BaseInteraction<
} }
this.user = this.member?.user ?? Transformers.User(client, interaction.user!); this.user = this.member?.user ?? Transformers.User(client, interaction.user!);
this.entitlements = interaction.entitlements.map(e => new Entitlement(this.client, e)); this.entitlements = interaction.entitlements.map(e => Transformers.Entitlement(this.client, e));
} }
static transformBodyRequest( static transformBodyRequest(
@ -208,39 +210,54 @@ export class BaseInteraction<
return payload as T; return payload as T;
} }
private async matchReplied(body: ReplyInteractionBody) { private async matchReplied(body: ReplyInteractionBody, withResponse = false) {
if (this.__reply) { if (this.__reply) {
//@ts-expect-error //@ts-expect-error
const { files, ...rest } = body.data ?? {}; const { files, ...rest } = body.data ?? {};
//@ts-expect-error //@ts-expect-error
const data = body.data instanceof Modal ? body.data : rest; const data = body.data instanceof Modal ? body.data : rest;
const parsedFiles = files ? await resolveFiles(files) : undefined; const parsedFiles = files ? await resolveFiles(files) : undefined;
return (this.replied = this.__reply({ await (this.replied = this.__reply({
body: BaseInteraction.transformBodyRequest({ data, type: body.type }, parsedFiles, this.client), body: BaseInteraction.transformBodyRequest({ data, type: body.type }, parsedFiles, this.client),
files: parsedFiles, files: parsedFiles,
}).then(() => (this.replied = true))); }).then(() => (this.replied = true)));
return;
} }
return (this.replied = this.client.interactions.reply(this.id, this.token, body).then(() => (this.replied = true))); const result = await (this.replied = this.client.interactions.reply(this.id, this.token, body, withResponse));
this.replied = true;
return result?.resource?.message
? Transformers.WebhookMessage(this.client, result.resource.message as any, this.id, this.token)
: undefined;
} }
async reply(body: ReplyInteractionBody) { async reply<WR extends boolean = false>(
body: ReplyInteractionBody,
withResponse?: WR,
): Promise<When<WR, WebhookMessageStructure, undefined>> {
if (this.replied) { if (this.replied) {
throw new Error('Interaction already replied'); throw new Error('Interaction already replied');
} }
await this.matchReplied(body); const result = await this.matchReplied(body, withResponse);
// @ts-expect-error // @ts-expect-error
if (body.data instanceof Modal && body.data.__exec) if (body.data instanceof Modal && body.data.__exec)
// @ts-expect-error // @ts-expect-error
this.client.components.modals.set(this.user.id, (body.data as Modal).__exec); this.client.components.modals.set(this.user.id, (body.data as Modal).__exec);
return result as never;
} }
deferReply(flags?: MessageFlags) { deferReply<WR extends boolean = false>(
return this.reply({ flags?: MessageFlags,
withResponse = false,
): Promise<When<WR, WebhookMessageStructure, undefined>> {
return this.reply(
{
type: InteractionResponseType.DeferredChannelMessageWithSource, type: InteractionResponseType.DeferredChannelMessageWithSource,
data: { data: {
flags, flags,
}, },
}); },
withResponse,
) as never;
} }
isButton(): this is ButtonInteraction { isButton(): this is ButtonInteraction {
@ -377,6 +394,7 @@ export class AutocompleteInteraction<FromGuild extends boolean = boolean> extend
declare type: InteractionType.ApplicationCommandAutocomplete; declare type: InteractionType.ApplicationCommandAutocomplete;
declare data: ObjectToLower<APIApplicationCommandAutocompleteInteraction['data']>; declare data: ObjectToLower<APIApplicationCommandAutocompleteInteraction['data']>;
options: OptionResolverStructure; options: OptionResolverStructure;
declare entitlements: EntitlementStructure[];
constructor( constructor(
client: UsingClient, client: UsingClient,
interaction: APIApplicationCommandAutocompleteInteraction, interaction: APIApplicationCommandAutocompleteInteraction,
@ -408,7 +426,7 @@ export class AutocompleteInteraction<FromGuild extends boolean = boolean> extend
} }
/** @intenal */ /** @intenal */
async reply(..._args: unknown[]) { async reply(..._args: unknown[]): Promise<any> {
throw new Error('Cannot use reply in this interaction'); throw new Error('Cannot use reply in this interaction');
} }
} }
@ -427,14 +445,15 @@ export class Interaction<
async write<FR extends boolean = false>( async write<FR extends boolean = false>(
body: InteractionCreateBodyRequest, body: InteractionCreateBodyRequest,
fetchReply?: FR, withResponse?: FR,
): Promise<When<FR, WebhookMessageStructure, void>> { ): Promise<When<FR, WebhookMessageStructure, void>> {
(await this.reply({ return this.reply(
{
type: InteractionResponseType.ChannelMessageWithSource, type: InteractionResponseType.ChannelMessageWithSource,
data: body, data: body,
})) as never; },
if (fetchReply) return this.fetchResponse() as never; withResponse,
return undefined as never; ) as never;
} }
modal(body: ModalCreateBodyRequest) { modal(body: ModalCreateBodyRequest) {
@ -469,7 +488,7 @@ export class Interaction<
} }
deleteMessage(messageId: string) { deleteMessage(messageId: string) {
return this.client.interactions.deleteResponse(this.id, this.token, messageId); return this.client.interactions.deleteResponse(this.token, messageId);
} }
followup(body: MessageWebhookCreateBodyRequest) { followup(body: MessageWebhookCreateBodyRequest) {
@ -568,6 +587,7 @@ export class ComponentInteraction<
declare channel: AllChannels; declare channel: AllChannels;
declare type: InteractionType.MessageComponent; declare type: InteractionType.MessageComponent;
declare message: MessageStructure; declare message: MessageStructure;
declare entitlements: EntitlementStructure[];
update(data: ComponentInteractionMessageUpdate) { update(data: ComponentInteractionMessageUpdate) {
return this.reply({ return this.reply({

View File

@ -61,7 +61,7 @@ export class BaseMessage extends DiscordBase {
} }
createComponentCollector(options?: ListenerOptions) { createComponentCollector(options?: ListenerOptions) {
return this.client.components!.createComponentCollector(this.id, options); return this.client.components!.createComponentCollector(this.id, this.channelId, this.guildId, options);
} }
get url() { get url() {
@ -174,7 +174,7 @@ export class WebhookMessage extends BaseMessage {
} }
fetch() { fetch() {
return this.api.webhooks(this.webhookId)(this.webhookToken).get({ query: this.thread?.id }); return this.api.webhooks(this.webhookId)(this.webhookToken).get();
} }
edit(body: EditMessageWebhook) { edit(body: EditMessageWebhook) {

View File

@ -93,11 +93,11 @@ export class BaseGuild extends DiscordBase<APIPartialGuild> {
*/ */
get shard() { get shard() {
if ('gateway' in this.client) { if ('gateway' in this.client) {
return (this.client.gateway as ShardManager).get(this.shardId!) as never; return (this.client.gateway as ShardManager).get(this.shardId) as never;
} }
if ('shards' in this.client) { if ('shards' in this.client) {
return (this.client as WorkerClient).shards.get(this.shardId!); return (this.client as WorkerClient).shards.get(this.shardId);
} }
return undefined; return undefined;
} }

View File

@ -582,7 +582,7 @@ export interface GatewayGuildCreateDispatchData extends APIGuild {
* *
* See https://discord.com/developers/docs/resources/channel#channel-object * See https://discord.com/developers/docs/resources/channel#channel-object
*/ */
threads: APIChannel[]; threads: APIThreadChannel[];
/** /**
* Presences of the members in the guild, will only include non-offline members if the size is greater than `large_threshold` * Presences of the members in the guild, will only include non-offline members if the size is greater than `large_threshold`
* *

View File

@ -573,7 +573,7 @@ export interface APIMessage {
/** /**
* Sent if a thread was started from this message * Sent if a thread was started from this message
*/ */
thread?: APIChannel; thread?: APIThreadChannel;
/** /**
* Sent if the message contains components like buttons, action rows, or other interactive components * Sent if the message contains components like buttons, action rows, or other interactive components
* *

View File

@ -364,8 +364,8 @@ export class Shard {
calculateSafeRequests(): number { calculateSafeRequests(): number {
const safeRequests = const safeRequests =
this.options.ratelimitOptions!.maxRequestsPerRateLimitTick - this.options.ratelimitOptions.maxRequestsPerRateLimitTick -
Math.ceil(this.options.ratelimitOptions!.rateLimitResetInterval / this.heart.interval) * 2; Math.ceil(this.options.ratelimitOptions.rateLimitResetInterval / this.heart.interval) * 2;
if (safeRequests < 0) { if (safeRequests < 0) {
return 0; return 0;

View File

@ -1,6 +1,6 @@
import cluster, { type Worker as ClusterWorker } from 'node:cluster'; import cluster, { type Worker as ClusterWorker } from 'node:cluster';
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
import { ApiHandler, Logger, Router } from '../..'; import { ApiHandler, Logger } from '../..';
import { type Adapter, MemoryAdapter } from '../../cache'; import { type Adapter, MemoryAdapter } from '../../cache';
import { BaseClient, type InternalRuntimeConfig } from '../../client/base'; import { BaseClient, type InternalRuntimeConfig } from '../../client/base';
import { type MakePartial, MergeOptions, lazyLoadPackage } from '../../common'; import { type MakePartial, MergeOptions, lazyLoadPackage } from '../../common';
@ -15,7 +15,7 @@ export class WorkerManager extends Map<
number, number,
(ClusterWorker | import('node:worker_threads').Worker | { ready: boolean }) & { ready?: boolean } (ClusterWorker | import('node:worker_threads').Worker | { ready: boolean }) & { ready?: boolean }
> { > {
options!: MakePartial<Required<WorkerManagerOptions>, 'adapter'>; options: MakePartial<Required<WorkerManagerOptions>, 'adapter'>;
debugger?: Logger; debugger?: Logger;
connectQueue!: ConnectQueue; connectQueue!: ConnectQueue;
workerQueue: (() => void)[] = []; workerQueue: (() => void)[] = [];
@ -424,7 +424,7 @@ export class WorkerManager extends Map<
domain: 'https://discord.com', domain: 'https://discord.com',
debug: this.options.debug, debug: this.options.debug,
}); });
this.options.info ??= await new Router(this.rest).createProxy().gateway.bot.get(); this.options.info ??= await this.rest.proxy.gateway.bot.get();
this.options.shardEnd ??= this.options.totalShards ?? this.options.info.shards; this.options.shardEnd ??= this.options.totalShards ?? this.options.info.shards;
this.options.totalShards ??= this.options.shardEnd; this.options.totalShards ??= this.options.shardEnd;
this.options = MergeOptions<Required<WorkerManagerOptions>>(WorkerManagerDefaults, this.options); this.options = MergeOptions<Required<WorkerManagerOptions>>(WorkerManagerDefaults, this.options);

View File

@ -30,7 +30,9 @@
}, },
"exclude": [ "exclude": [
"**/lib", "**/lib",
"**/__test__" "**/__test__",
"**/node_modules",
"**/.*/"
], ],
"include": [ "include": [
"src" "src"