@openclaw/discord 2026.11.3 → 2026.11.5-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.setup/{account-inspect-8cCu6uPG.mjs → account-inspect-DGkdWwix.mjs} +1 -1
- package/dist/.setup/{accounts-ljrzXBJi.mjs → accounts-C_25wyxC.mjs} +9 -6
- package/dist/.setup/{active-turn-thread-route-C4tp9noA.mjs → active-turn-thread-route-KvRTAVE3.mjs} +1 -2
- package/dist/.setup/{allow-list-BKqOldGy.mjs → allow-list-BXrS8-R9.mjs} +4 -152
- package/dist/.setup/{api-DqmMUZau.mjs → api-BlBD4ism.mjs} +10 -20
- package/dist/.setup/{approval-handler.runtime-D0qu1um7.mjs → approval-handler.runtime-BGYjX1t9.mjs} +80 -61
- package/dist/.setup/{approval-message-updates-CdurC9Ej.mjs → approval-message-updates-DKsCfxSW.mjs} +2 -2
- package/dist/.setup/{audit-ChorIwio.mjs → audit-5b-FXj9R.mjs} +4 -4
- package/dist/.setup/{channel-ZilgdF5e.mjs → channel-CWwTHWFo.mjs} +134 -202
- package/dist/.setup/channel-access-9cyzozUP.mjs +24 -0
- package/dist/.setup/channel.setup-B3MtmBQG.mjs +238 -0
- package/dist/.setup/{components-Du9NhD8h.mjs → components-YCvQ6YLS.mjs} +209 -430
- package/dist/.setup/components.base-CiS0h_XP.mjs +32 -0
- package/dist/.setup/{config-schema-_uBILpQf.mjs → config-schema-BNKN1cu5.mjs} +6 -7
- package/dist/.setup/{conversation-binding-route-8Ul1KpGF.mjs → conversation-binding-route-kCTw8cij.mjs} +2 -2
- package/dist/.setup/{directory-config-3iVub-3m.mjs → directory-config-Ble81PWH.mjs} +1 -1
- package/dist/.setup/{directory-live-BDVl2DoC.mjs → directory-live-DH3tpS3x.mjs} +52 -57
- package/dist/.setup/{discord-BMD-JiVS.mjs → discord-DGVSguhx.mjs} +1124 -1710
- package/dist/.setup/{doctor-hQKbkNKq.mjs → doctor-eujgbnpZ.mjs} +3 -5
- package/dist/.setup/endpoint-runtime-lf4DeLas.mjs +139 -0
- package/dist/.setup/guilds-eDq22iSM.mjs +22 -0
- package/dist/.setup/{handle-action-B1lmt4ms.mjs → handle-action-CktwmzMz.mjs} +15 -15
- package/dist/.setup/{handle-action.guild-admin-B6g31cwt.mjs → handle-action.guild-admin-WLQ7fRqI.mjs} +5 -5
- package/dist/.setup/listeners-Df8lx3vK.mjs +47 -0
- package/dist/.setup/{live-policy-config-C_Q966Wh.mjs → live-policy-config-DiBVuaU6.mjs} +2 -3
- package/dist/.setup/{message-handler-CkI3yMjL.mjs → message-handler-hhNSioxo.mjs} +154 -115
- package/dist/.setup/{message-handler.preflight-CEfkFV9U.mjs → message-handler.preflight-BZcZE1o-.mjs} +30 -105
- package/dist/.setup/{message-handler.preflight-pluralkit-D5si80_L.mjs → message-handler.preflight-pluralkit-CYZfXXb6.mjs} +9 -22
- package/dist/.setup/{message-handler.process-DsMtetRf.mjs → message-handler.process-B0n-mQ99.mjs} +256 -373
- package/dist/.setup/outbound-payload-BaZmjewa.mjs +447 -0
- package/dist/.setup/{outbound-session-route-BtUpGBTb.mjs → outbound-session-route-Cgx4i9cS.mjs} +139 -86
- package/dist/.setup/{preflight-audio-wWgsZG5F.mjs → preflight-audio-C6QtD6HX.mjs} +1 -5
- package/dist/.setup/{presence-cache-DCeTsL73.mjs → presence-cache-Dq-3nH7R.mjs} +1 -6
- package/dist/.setup/{probe-CBaoCs-c.mjs → probe-DezB-6xz.mjs} +5 -9
- package/dist/.setup/{provider-CI_OLfvz.mjs → provider-BN2bCIUp.mjs} +3440 -4308
- package/dist/.setup/{provider-session.runtime-TWOo_JZx.mjs → provider-session.runtime-Dr_5X43t.mjs} +3 -3
- package/dist/.setup/provider.runtime-BuJpl0Pv.mjs +1 -0
- package/dist/.setup/proxy-fetch-BzXwBAXt.mjs +30 -0
- package/dist/.setup/{realtime-session.runtime-DvfS4vJj.mjs → realtime-session.runtime-BTDWsV4d.mjs} +44 -81
- package/dist/.setup/{receive-recovery-CKvaG2Hf.mjs → receive-recovery-C3Ks4wAQ.mjs} +13 -27
- package/dist/.setup/{resolve-allowlist-common-cIjtqh2F.mjs → resolve-allowlist-common-Bk8Fj6Ik.mjs} +3 -13
- package/dist/.setup/{resolve-channels-Cj5i7hzj.mjs → resolve-channels-Bp8frXvc.mjs} +7 -8
- package/dist/.setup/{resolve-users-BQLbysRB.mjs → resolve-users-Cvcj22sG.mjs} +4 -7
- package/dist/.setup/{runtime-RWnuJgWB.mjs → runtime-BJaCvlmq.mjs} +196 -239
- package/dist/.setup/{runtime-plifsKg9.mjs → runtime-BMgTyuwg.mjs} +6 -6
- package/dist/.setup/{secret-config-contract-z6FhbT8E.mjs → secret-config-contract-B1kE4sDv.mjs} +4 -9
- package/dist/.setup/{send-da6ENJ9f.mjs → send-CVW7V-VZ.mjs} +149 -175
- package/dist/.setup/{send.components-CWZUuGvA.mjs → send.components-C8YXdnO_.mjs} +59 -71
- package/dist/.setup/{send.outbound-qZ3iK3Vq.mjs → send.outbound-Uzcmh3Yd.mjs} +76 -129
- package/dist/.setup/{send.receipt-C18khRYH.mjs → send.receipt-NZDOTZBU.mjs} +30 -32
- package/dist/.setup/{send.shared-CnlMgoqQ.mjs → send.shared-a_6Oeyg1.mjs} +38 -115
- package/dist/.setup/{sender-identity-DgbJykq0.mjs → sender-identity-76HFb8eK.mjs} +3 -9
- package/dist/.setup/setup-plugin-api-BExhGEhL.mjs +2 -0
- package/dist/.setup/shared-interactive-DmzaoKOM.mjs +316 -0
- package/dist/.setup/{shared-CY5vJM48.mjs → shared-yDUSExm2.mjs} +8 -11
- package/dist/.setup/{subagent-hooks-CIu2TFz3.mjs → subagent-hooks-CDkdHQyy.mjs} +1 -1
- package/dist/.setup/{system-events-DCOLXkwS.mjs → system-events-yfWz150v.mjs} +2 -2
- package/dist/.setup/{target-resolver-CApivu3G.mjs → target-resolver-BOOzqxxM.mjs} +3 -3
- package/dist/.setup/{thread-bindings-DcvT_JgI.mjs → thread-bindings-zce4cpu_.mjs} +12 -20
- package/dist/.setup/{thread-bindings.manager-5Sh7yedN.mjs → thread-bindings.manager-NywKzUtc.mjs} +22 -42
- package/dist/.setup/{thread-bindings.session-updates-BMdJeJMc.mjs → thread-bindings.session-updates-D0j7oh8S.mjs} +11 -18
- package/dist/.setup/{threading-CzjFeUSe.mjs → threading-DodLYDt-.mjs} +68 -105
- package/dist/.setup/{timeouts-CuNARfyw.mjs → timeouts-cIxzatmv.mjs} +1 -1
- package/dist/.setup/{transcripts-source-8RDQrSVb.mjs → transcripts-source-ie9GBWaU.mjs} +110 -179
- package/dist/.setup/{voice-runtime-BsDILmAv.mjs → voice-runtime-B7V_LTdX.mjs} +231 -452
- package/dist/.source-module-urls/d6c089460280c5a04184542d6712e04545caeb1ebb290d3504377b4cc5e22fea.json +1 -0
- package/dist/account-inspect-api.js +1 -1
- package/dist/action-runtime-api.js +1 -2
- package/dist/activities-api.js +286 -341
- package/dist/api.js +16 -16
- package/dist/channel-config-api.js +1 -2
- package/dist/channel-plugin-api.js +1 -2
- package/dist/contract-api.js +1 -2
- package/dist/directory-contract-api.js +1 -1
- package/dist/runtime-api.js +22 -22
- package/dist/runtime-setter-api.js +1 -2
- package/dist/secret-contract-api.js +1 -2
- package/dist/security-audit-contract-api.js +1 -2
- package/dist/security-contract-api.js +1 -2
- package/dist/session-key-api.js +1 -2
- package/dist/setup-entry.js +1 -1
- package/dist/setup-plugin-api.js +1 -2
- package/dist/src/voice/audio-worker.runtime.js +56 -68
- package/dist/subagent-hooks-api.js +1 -1
- package/dist/thread-binding-api.js +1 -2
- package/dist/transcripts-source-api.js +1 -1
- package/node_modules/@napi-rs/wasm-runtime/dist/fs.js +3339 -4021
- package/node_modules/@napi-rs/wasm-runtime/package.json +1 -1
- package/node_modules/@types/lodash/README.md +1 -1
- package/node_modules/@types/lodash/common/function.d.ts +2 -2
- package/node_modules/@types/lodash/package.json +2 -2
- package/node_modules/@types/node/README.md +1 -1
- package/node_modules/@types/node/package.json +2 -2
- package/node_modules/@types/node/util.d.ts +6 -3
- package/node_modules/discord-api-types/package.json +4 -4
- package/node_modules/discord-api-types/rest/v10/index.d.ts +8 -0
- package/node_modules/discord-api-types/rest/v10/index.d.ts.map +1 -1
- package/node_modules/discord-api-types/rest/v10/index.js +8 -0
- package/node_modules/discord-api-types/rest/v10/index.js.map +1 -1
- package/node_modules/discord-api-types/rest/v10/oauth2.d.ts +26 -2
- package/node_modules/discord-api-types/rest/v10/oauth2.d.ts.map +1 -1
- package/node_modules/discord-api-types/rest/v9/index.d.ts +8 -0
- package/node_modules/discord-api-types/rest/v9/index.d.ts.map +1 -1
- package/node_modules/discord-api-types/rest/v9/index.js +8 -0
- package/node_modules/discord-api-types/rest/v9/index.js.map +1 -1
- package/node_modules/discord-api-types/rest/v9/oauth2.d.ts +26 -2
- package/node_modules/discord-api-types/rest/v9/oauth2.d.ts.map +1 -1
- package/node_modules/typebox/build/format/duration.d.mts +2 -2
- package/node_modules/typebox/build/format/duration.mjs +2 -2
- package/node_modules/typebox/build/format/idn_email.d.mts +1 -0
- package/node_modules/typebox/build/format/idn_email.mjs +1 -0
- package/node_modules/typebox/build/format/idn_hostname.d.mts +1 -1
- package/node_modules/typebox/build/format/idn_hostname.mjs +1 -1
- package/node_modules/typebox/build/format/ipv4.d.mts +2 -2
- package/node_modules/typebox/build/format/ipv4.mjs +2 -2
- package/node_modules/typebox/build/format/ipv6.d.mts +1 -1
- package/node_modules/typebox/build/format/ipv6.mjs +1 -1
- package/node_modules/typebox/build/format/relative_json_pointer.d.mts +2 -2
- package/node_modules/typebox/build/format/relative_json_pointer.mjs +2 -2
- package/node_modules/typebox/build/schema/build.mjs +1 -0
- package/node_modules/typebox/build/schema/engine/_unique.d.mts +4 -2
- package/node_modules/typebox/build/schema/engine/_unique.mjs +7 -3
- package/node_modules/typebox/build/schema/engine/additionalItems.mjs +3 -3
- package/node_modules/typebox/build/schema/engine/additionalProperties.d.mts +0 -3
- package/node_modules/typebox/build/schema/engine/additionalProperties.mjs +15 -17
- package/node_modules/typebox/build/schema/engine/contains.mjs +3 -3
- package/node_modules/typebox/build/schema/engine/index.d.mts +1 -0
- package/node_modules/typebox/build/schema/engine/index.mjs +1 -0
- package/node_modules/typebox/build/schema/engine/items.mjs +7 -4
- package/node_modules/typebox/build/schema/engine/maxContains.mjs +2 -2
- package/node_modules/typebox/build/schema/engine/minContains.mjs +3 -3
- package/node_modules/typebox/build/schema/engine/oneOf.mjs +2 -2
- package/node_modules/typebox/build/schema/engine/patternProperties.mjs +2 -2
- package/node_modules/typebox/build/schema/engine/propertyNames.mjs +2 -2
- package/node_modules/typebox/build/schema/engine/unevaluatedItems.mjs +2 -2
- package/node_modules/typebox/build/schema/engine/unevaluatedProperties.mjs +2 -2
- package/node_modules/typebox/build/system/hashing/hash.mjs +63 -34
- package/node_modules/typebox/build/system/locale/en_US.mjs +2 -1
- package/node_modules/typebox/build/system/memory/assign.d.mts +2 -8
- package/node_modules/typebox/build/system/memory/assign.mjs +13 -6
- package/node_modules/typebox/build/system/memory/clone.d.mts +4 -5
- package/node_modules/typebox/build/system/memory/clone.mjs +8 -96
- package/node_modules/typebox/build/system/memory/create.d.mts +1 -5
- package/node_modules/typebox/build/system/memory/create.mjs +18 -13
- package/node_modules/typebox/build/system/memory/deep.d.mts +2 -0
- package/node_modules/typebox/build/system/memory/deep.mjs +108 -0
- package/node_modules/typebox/build/system/memory/discard.d.mts +1 -1
- package/node_modules/typebox/build/system/memory/discard.mjs +9 -8
- package/node_modules/typebox/build/system/memory/finalize.d.mts +4 -0
- package/node_modules/typebox/build/system/memory/finalize.mjs +30 -0
- package/node_modules/typebox/build/system/memory/keys.d.mts +2 -0
- package/node_modules/typebox/build/system/memory/keys.mjs +8 -0
- package/node_modules/typebox/build/system/memory/update.d.mts +1 -4
- package/node_modules/typebox/build/system/memory/update.mjs +43 -16
- package/node_modules/typebox/build/type/engine/call/index.d.mts +1 -0
- package/node_modules/typebox/build/type/engine/call/index.mjs +1 -0
- package/node_modules/typebox/build/type/engine/evaluate/composite.d.mts +2 -24
- package/node_modules/typebox/build/type/engine/evaluate/composite.mjs +2 -29
- package/node_modules/typebox/build/type/engine/evaluate/index.d.mts +1 -0
- package/node_modules/typebox/build/type/engine/evaluate/index.mjs +1 -0
- package/node_modules/typebox/build/type/engine/evaluate/narrow.d.mts +5 -1
- package/node_modules/typebox/build/type/engine/evaluate/narrow.mjs +6 -1
- package/node_modules/typebox/build/type/engine/evaluate/property.d.mts +30 -0
- package/node_modules/typebox/build/type/engine/evaluate/property.mjs +29 -0
- package/node_modules/typebox/build/type/engine/immutable/instantiate_add.d.mts +1 -3
- package/node_modules/typebox/build/type/engine/immutable/instantiate_add.mjs +1 -4
- package/node_modules/typebox/build/type/engine/object/from_intersect.d.mts +2 -2
- package/node_modules/typebox/build/type/engine/object/from_intersect.mjs +2 -2
- package/node_modules/typebox/build/type/engine/object/from_union.d.mts +2 -2
- package/node_modules/typebox/build/type/engine/object/from_union.mjs +2 -2
- package/node_modules/typebox/build/type/engine/optional/instantiate_add.d.mts +1 -3
- package/node_modules/typebox/build/type/engine/optional/instantiate_add.mjs +1 -4
- package/node_modules/typebox/build/type/engine/readonly/instantiate_add.d.mts +1 -3
- package/node_modules/typebox/build/type/engine/readonly/instantiate_add.mjs +1 -4
- package/node_modules/typebox/build/type/engine/this/index.d.mts +1 -0
- package/node_modules/typebox/build/type/engine/this/index.mjs +1 -0
- package/node_modules/typebox/build/value/clone/clone.d.mts +4 -3
- package/node_modules/typebox/build/value/clone/clone.mjs +5 -7
- package/node_modules/typebox/build/value/repair/from_cyclic.d.mts +2 -0
- package/node_modules/typebox/build/value/repair/from_cyclic.mjs +6 -0
- package/node_modules/typebox/build/value/shared/union_priority_sort.mjs +25 -14
- package/node_modules/typebox/package.json +1 -1
- package/node_modules/typebox/readme.md +1 -1
- package/node_modules/undici/docs/docs/api/Interceptors.md +15 -2
- package/node_modules/undici/lib/dispatcher/client-h2.js +78 -3
- package/node_modules/undici/lib/dispatcher/pool-base.js +20 -3
- package/node_modules/undici/package.json +3 -3
- package/node_modules/undici/types/api.d.ts +1 -1
- package/node_modules/undici/types/utility.d.ts +4 -4
- package/node_modules/uuid/package.json +17 -17
- package/node_modules/zod/package.json +1 -1
- package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
- package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
- package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
- package/node_modules/zod/src/v4/core/compile.ts +9 -0
- package/node_modules/zod/src/v4/core/schemas.ts +35 -1
- package/node_modules/zod/src/v4/core/util.ts +13 -0
- package/node_modules/zod/src/v4/core/versions.ts +1 -1
- package/node_modules/zod/v4/core/compile.cjs +8 -0
- package/node_modules/zod/v4/core/compile.js +8 -0
- package/node_modules/zod/v4/core/schemas.cjs +30 -0
- package/node_modules/zod/v4/core/schemas.d.cts +3 -1
- package/node_modules/zod/v4/core/schemas.d.ts +3 -1
- package/node_modules/zod/v4/core/schemas.js +30 -0
- package/node_modules/zod/v4/core/util.cjs +15 -0
- package/node_modules/zod/v4/core/util.d.cts +2 -0
- package/node_modules/zod/v4/core/util.d.ts +2 -0
- package/node_modules/zod/v4/core/util.js +14 -0
- package/node_modules/zod/v4/core/versions.cjs +1 -1
- package/node_modules/zod/v4/core/versions.js +1 -1
- package/openclaw.plugin.json +1 -31
- package/package.json +8 -8
- package/dist/.setup/channel-access-DasWY_OV.mjs +0 -48
- package/dist/.setup/channel.setup-DaDQdctj.mjs +0 -249
- package/dist/.setup/outbound-adapter-DfAanoCO.mjs +0 -543
- package/dist/.setup/provider.runtime-DnionCyo.mjs +0 -2
- package/dist/.setup/setup-plugin-api-D1QuM187.mjs +0 -3
- package/dist/.setup/targets-UWWZ6gF7.mjs +0 -3
- package/node_modules/typebox/build/system/memory/freeze.d.mts +0 -4
- package/node_modules/typebox/build/system/memory/freeze.mjs +0 -6
|
@@ -1,691 +1,776 @@
|
|
|
1
1
|
import { n as __reExport, t as __exportAll } from "./rolldown-runtime-B4FMCO8f.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { C as parseDiscordRetryAfterBodySeconds } from "./allow-list-BXrS8-R9.mjs";
|
|
3
|
+
import { n as getDiscordEndpointRuntime } from "./endpoint-runtime-lf4DeLas.mjs";
|
|
4
|
+
import { i as parseCustomId, n as BaseModalComponent, t as BaseMessageInteractiveComponent } from "./components.base-CiS0h_XP.mjs";
|
|
3
5
|
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
|
|
4
|
-
import { asOptionalObjectRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
5
|
-
import { ApplicationCommandOptionType, ApplicationCommandType,
|
|
6
|
-
import { asDateTimestampMs, clampTimerTimeoutMs, parseStrictNonNegativeInteger
|
|
7
|
-
import { captureChannelReadAuthority, captureEffectAuthority } from "openclaw/plugin-sdk/fetch-runtime";
|
|
8
|
-
import { Type } from "typebox";
|
|
9
|
-
import { Check } from "typebox/value";
|
|
10
|
-
import { createHash } from "node:crypto";
|
|
11
|
-
import { raceWithTimeout } from "openclaw/plugin-sdk/time-runtime";
|
|
12
|
-
import { inspect } from "node:util";
|
|
6
|
+
import { asOptionalObjectRecord, asRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
7
|
+
import { ApplicationCommandOptionType, ApplicationCommandType, ComponentType, GatewayDispatchEvents, InteractionContextType, InteractionResponseType, InteractionType, MessageFlags, Routes, TextInputStyle } from "discord-api-types/v10";
|
|
8
|
+
import { asDateTimestampMs, clampTimerTimeoutMs, parseStrictNonNegativeInteger, resolveExpiresAtMsFromDurationMs, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
|
|
13
9
|
import { gunzipSync } from "node:zlib";
|
|
10
|
+
import { captureChannelReadAuthority, captureEffectAuthority } from "openclaw/plugin-sdk/fetch-runtime";
|
|
14
11
|
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
|
|
15
12
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
16
13
|
import { resolveGlobalSingleton } from "openclaw/plugin-sdk/global-singleton";
|
|
17
14
|
import { redactIdentifier, redactSensitiveFieldValue } from "openclaw/plugin-sdk/logging-core";
|
|
18
15
|
import { parseRetryAfterHeaderSeconds } from "openclaw/plugin-sdk/retry-runtime";
|
|
16
|
+
import { Type } from "typebox";
|
|
17
|
+
import { Check } from "typebox/value";
|
|
18
|
+
import { createHash } from "node:crypto";
|
|
19
|
+
import { createPermitPool } from "openclaw/plugin-sdk/concurrency-runtime";
|
|
19
20
|
//#region extensions/discord/src/internal/undefined-fields.ts
|
|
20
21
|
function stripUndefinedFields(value) {
|
|
21
22
|
return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0));
|
|
22
23
|
}
|
|
23
24
|
//#endregion
|
|
24
|
-
//#region extensions/discord/src/internal/
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
return async (rest, guildId, userId) => await rest.get(Routes[route](guildId, userId));
|
|
25
|
+
//#region extensions/discord/src/internal/request-authority.ts
|
|
26
|
+
const requestAuthority = resolveGlobalSingleton(Symbol.for("openclaw.discord.requestAuthority"), () => new AsyncLocalStorage());
|
|
27
|
+
/** Carry the host's existing assertion without changing its lifetime or ownership. */
|
|
28
|
+
function withDiscordRequestAuthority(assertCurrent, run) {
|
|
29
|
+
if (!assertCurrent) return run();
|
|
30
|
+
const inherited = requestAuthority.getStore();
|
|
31
|
+
return requestAuthority.run(inherited && inherited !== assertCurrent ? () => {
|
|
32
|
+
inherited();
|
|
33
|
+
assertCurrent();
|
|
34
|
+
} : assertCurrent, run);
|
|
35
35
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
async function listGuildEmojis(rest, guildId) {
|
|
39
|
-
const emojis = await rest.get(Routes.guildEmojis(guildId));
|
|
40
|
-
if (!Check(discordGuildEmojiListSchema, emojis)) throw new Error("Invalid Discord guild emoji response.");
|
|
41
|
-
return emojis;
|
|
36
|
+
function captureDiscordRequestAuthority() {
|
|
37
|
+
return requestAuthority.getStore();
|
|
42
38
|
}
|
|
43
39
|
//#endregion
|
|
44
|
-
//#region extensions/discord/src/internal/
|
|
45
|
-
function
|
|
46
|
-
|
|
47
|
-
if (!/^[0-9]+$/u.test(normalized)) throw new Error("Invalid Discord message ID. Expected decimal digits.");
|
|
48
|
-
return normalized;
|
|
49
|
-
}
|
|
50
|
-
async function getChannel(rest, channelId) {
|
|
51
|
-
return await rest.get(Routes.channel(channelId));
|
|
52
|
-
}
|
|
53
|
-
async function createChannelMessage(rest, channelId, data) {
|
|
54
|
-
return await rest.post(Routes.channelMessages(channelId), data);
|
|
40
|
+
//#region extensions/discord/src/internal/rest-body.ts
|
|
41
|
+
function fileBlob(file) {
|
|
42
|
+
return file.data instanceof Blob ? file.data : new Blob([file.data], { type: typeof file.contentType === "string" ? file.contentType : void 0 });
|
|
55
43
|
}
|
|
56
|
-
|
|
57
|
-
|
|
44
|
+
function serializeRequestBody(data, headers) {
|
|
45
|
+
if (data?.headers) for (const [key, value] of Object.entries(data.headers)) headers.set(key, value);
|
|
46
|
+
if (data?.body == null) return;
|
|
47
|
+
if (typeof data.body === "object") {
|
|
48
|
+
const bodyObject = data.body;
|
|
49
|
+
const topLevelFiles = Array.isArray(bodyObject.files) ? bodyObject.files : void 0;
|
|
50
|
+
const nestedData = bodyObject.data && typeof bodyObject.data === "object" ? bodyObject.data : void 0;
|
|
51
|
+
const nestedFiles = nestedData && Array.isArray(nestedData.files) ? nestedData.files : void 0;
|
|
52
|
+
const files = topLevelFiles ?? nestedFiles;
|
|
53
|
+
const filesContainer = topLevelFiles ? bodyObject : nestedFiles ? nestedData : void 0;
|
|
54
|
+
if (files?.length && filesContainer) {
|
|
55
|
+
if (data.multipartStyle === "form") {
|
|
56
|
+
const formData = new FormData();
|
|
57
|
+
for (const [key, value] of Object.entries(filesContainer)) {
|
|
58
|
+
if (key === "files" || value === void 0 || value === null) continue;
|
|
59
|
+
formData.append(key, typeof value === "string" ? value : JSON.stringify(value));
|
|
60
|
+
}
|
|
61
|
+
for (const file of files) {
|
|
62
|
+
const item = file;
|
|
63
|
+
const name = typeof item.name === "string" && item.name ? item.name : "file";
|
|
64
|
+
formData.append(typeof item.fieldName === "string" && item.fieldName ? item.fieldName : "file", fileBlob(item), name);
|
|
65
|
+
}
|
|
66
|
+
return formData;
|
|
67
|
+
}
|
|
68
|
+
const payloadFilesContainer = { ...filesContainer };
|
|
69
|
+
const payloadJson = topLevelFiles ? payloadFilesContainer : {
|
|
70
|
+
...bodyObject,
|
|
71
|
+
data: payloadFilesContainer
|
|
72
|
+
};
|
|
73
|
+
const formData = new FormData();
|
|
74
|
+
const existingAttachments = Array.isArray(payloadFilesContainer.attachments) ? payloadFilesContainer.attachments : [];
|
|
75
|
+
const uploaded = files.map((file, index) => {
|
|
76
|
+
const item = file;
|
|
77
|
+
const name = typeof item.name === "string" && item.name ? item.name : `file-${index}`;
|
|
78
|
+
const id = existingAttachments.length + index;
|
|
79
|
+
formData.append(`files[${id}]`, fileBlob(item), name);
|
|
80
|
+
const attachment = {
|
|
81
|
+
id,
|
|
82
|
+
filename: name
|
|
83
|
+
};
|
|
84
|
+
if (typeof item.description === "string") attachment.description = item.description;
|
|
85
|
+
if (typeof item.duration_secs === "number") attachment.duration_secs = item.duration_secs;
|
|
86
|
+
if (typeof item.waveform === "string") attachment.waveform = item.waveform;
|
|
87
|
+
return attachment;
|
|
88
|
+
});
|
|
89
|
+
payloadFilesContainer.attachments = [...existingAttachments, ...uploaded];
|
|
90
|
+
delete payloadFilesContainer.files;
|
|
91
|
+
formData.append("payload_json", JSON.stringify(payloadJson));
|
|
92
|
+
return formData;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
headers.set("Content-Type", "application/json");
|
|
96
|
+
return JSON.stringify(data.body);
|
|
58
97
|
}
|
|
59
|
-
|
|
60
|
-
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region extensions/discord/src/internal/rest-errors.ts
|
|
100
|
+
const DISCORD_UNKNOWN_MESSAGE = 10008;
|
|
101
|
+
const DISCORD_UNKNOWN_VOICE_STATE = 10065;
|
|
102
|
+
const DISCORD_ERROR_BODY_MAX_DEPTH = 64;
|
|
103
|
+
const DISCORD_ERROR_BODY_MAX_NODES = 1e4;
|
|
104
|
+
const DISCORD_ERROR_BODY_MAX_DEPTH_MARKER = "[Discord error body redacted: maximum depth exceeded]";
|
|
105
|
+
const DISCORD_ERROR_BODY_MAX_NODES_MARKER = "[Discord error body redacted: node limit exceeded]";
|
|
106
|
+
const DISCORD_ERROR_BODY_PRIORITY_KEYS = /* @__PURE__ */ new Set([
|
|
107
|
+
"message",
|
|
108
|
+
"code",
|
|
109
|
+
"retry_after",
|
|
110
|
+
"global"
|
|
111
|
+
]);
|
|
112
|
+
const DISCORD_RATE_LIMIT_SCOPES = /* @__PURE__ */ new Set([
|
|
113
|
+
"user",
|
|
114
|
+
"global",
|
|
115
|
+
"shared"
|
|
116
|
+
]);
|
|
117
|
+
function reserveRedactedKey(key, usedKeys, collisionCounts) {
|
|
118
|
+
let count = (collisionCounts.get(key) ?? 0) + 1;
|
|
119
|
+
let candidate = count === 1 ? key : `${key} [${count}]`;
|
|
120
|
+
while (usedKeys.has(candidate)) {
|
|
121
|
+
count += 1;
|
|
122
|
+
candidate = `${key} [${count}]`;
|
|
123
|
+
}
|
|
124
|
+
collisionCounts.set(key, count);
|
|
125
|
+
usedKeys.add(candidate);
|
|
126
|
+
return candidate;
|
|
61
127
|
}
|
|
62
|
-
|
|
63
|
-
|
|
128
|
+
function redactDiscordErrorBody(body, fieldKey = "", sensitiveAncestorKey, state = {
|
|
129
|
+
seen: /* @__PURE__ */ new WeakSet(),
|
|
130
|
+
remainingNodes: DISCORD_ERROR_BODY_MAX_NODES
|
|
131
|
+
}, depth = 0) {
|
|
132
|
+
if (state.remainingNodes <= 0) return DISCORD_ERROR_BODY_MAX_NODES_MARKER;
|
|
133
|
+
state.remainingNodes -= 1;
|
|
134
|
+
if (typeof body === "string") return redactSensitiveFieldValue(sensitiveAncestorKey ?? fieldKey, body);
|
|
135
|
+
if (sensitiveAncestorKey && (typeof body === "number" || typeof body === "boolean" || typeof body === "bigint")) return redactSensitiveFieldValue(sensitiveAncestorKey, String(body));
|
|
136
|
+
if (!body || typeof body !== "object") return body;
|
|
137
|
+
if (depth >= DISCORD_ERROR_BODY_MAX_DEPTH) return DISCORD_ERROR_BODY_MAX_DEPTH_MARKER;
|
|
138
|
+
if (state.seen.has(body)) return "[Circular]";
|
|
139
|
+
state.seen.add(body);
|
|
140
|
+
let redacted;
|
|
141
|
+
if (Array.isArray(body)) {
|
|
142
|
+
const items = [];
|
|
143
|
+
for (const entry of body) {
|
|
144
|
+
if (state.remainingNodes <= 0) {
|
|
145
|
+
items.push(DISCORD_ERROR_BODY_MAX_NODES_MARKER);
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
items.push(redactDiscordErrorBody(entry, fieldKey, sensitiveAncestorKey, state, depth + 1));
|
|
149
|
+
}
|
|
150
|
+
redacted = items;
|
|
151
|
+
} else {
|
|
152
|
+
const usedKeys = /* @__PURE__ */ new Set();
|
|
153
|
+
const collisionCounts = /* @__PURE__ */ new Map();
|
|
154
|
+
const entries = [];
|
|
155
|
+
const appendEntry = (nestedKey) => {
|
|
156
|
+
if (state.remainingNodes <= 0) return false;
|
|
157
|
+
const outputKey = reserveRedactedKey(redactSensitiveFieldValue(sensitiveAncestorKey ?? "", nestedKey), usedKeys, collisionCounts);
|
|
158
|
+
const nestedSensitiveKey = redactSensitiveFieldValue(nestedKey, "") !== "" ? nestedKey : sensitiveAncestorKey;
|
|
159
|
+
entries.push([outputKey, redactDiscordErrorBody(body[nestedKey], nestedKey, nestedSensitiveKey, state, depth + 1)]);
|
|
160
|
+
return true;
|
|
161
|
+
};
|
|
162
|
+
let truncated = false;
|
|
163
|
+
for (const priorityKey of DISCORD_ERROR_BODY_PRIORITY_KEYS) if (Object.hasOwn(body, priorityKey) && !appendEntry(priorityKey)) {
|
|
164
|
+
truncated = true;
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
if (!truncated) for (const nestedKey in body) {
|
|
168
|
+
if (!Object.hasOwn(body, nestedKey) || DISCORD_ERROR_BODY_PRIORITY_KEYS.has(nestedKey)) continue;
|
|
169
|
+
if (!appendEntry(nestedKey)) {
|
|
170
|
+
truncated = true;
|
|
171
|
+
break;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (truncated) {
|
|
175
|
+
const markerKey = reserveRedactedKey(DISCORD_ERROR_BODY_MAX_NODES_MARKER, usedKeys, collisionCounts);
|
|
176
|
+
entries.push([markerKey, DISCORD_ERROR_BODY_MAX_NODES_MARKER]);
|
|
177
|
+
}
|
|
178
|
+
redacted = Object.fromEntries(entries);
|
|
179
|
+
}
|
|
180
|
+
state.seen.delete(body);
|
|
181
|
+
return redacted;
|
|
64
182
|
}
|
|
65
|
-
function
|
|
66
|
-
return
|
|
67
|
-
await rest[method](Routes[route](channelId, normalizeDiscordMessageId(messageId)));
|
|
68
|
-
};
|
|
183
|
+
function readDiscordCode(body) {
|
|
184
|
+
return parseStrictNonNegativeInteger(asOptionalObjectRecord(body)?.code);
|
|
69
185
|
}
|
|
70
|
-
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
async function createThread(rest, channelId, data, messageId) {
|
|
74
|
-
const route = messageId === void 0 ? Routes.threads(channelId) : Routes.threads(channelId, normalizeDiscordMessageId(messageId));
|
|
75
|
-
return await rest.post(route, data);
|
|
186
|
+
function readDiscordMessage(body, fallback) {
|
|
187
|
+
const value = asOptionalObjectRecord(body)?.message;
|
|
188
|
+
return typeof value === "string" && value.trim() ? value : fallback;
|
|
76
189
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
function ownReactionMutation(method) {
|
|
80
|
-
return async (rest, channelId, messageId, encodedEmoji) => {
|
|
81
|
-
await rest[method](Routes.channelMessageOwnReaction(channelId, normalizeDiscordMessageId(messageId), encodedEmoji));
|
|
82
|
-
};
|
|
190
|
+
function readErrorDiscordCode(err) {
|
|
191
|
+
return parseStrictNonNegativeInteger(asOptionalObjectRecord(err)?.discordCode);
|
|
83
192
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
async function listMessageReactionUsers(rest, channelId, messageId, encodedEmoji, query) {
|
|
87
|
-
return await rest.get(Routes.channelMessageReaction(channelId, normalizeDiscordMessageId(messageId), encodedEmoji), query);
|
|
193
|
+
function isUnknownDiscordMessageError(err) {
|
|
194
|
+
return readErrorDiscordCode(err) === DISCORD_UNKNOWN_MESSAGE;
|
|
88
195
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
async function getCurrentUser(rest) {
|
|
92
|
-
return await rest.get(Routes.user("@me"));
|
|
196
|
+
function isUnknownDiscordVoiceStateError(err) {
|
|
197
|
+
return readErrorDiscordCode(err) === DISCORD_UNKNOWN_VOICE_STATE || /unknown voice state/i.test(formatErrorMessage(err));
|
|
93
198
|
}
|
|
94
|
-
|
|
95
|
-
return
|
|
199
|
+
function readRetryAfter(body, response) {
|
|
200
|
+
return parseDiscordRetryAfterBodySeconds(asOptionalObjectRecord(body)?.retry_after) ?? parseRetryAfterHeaderSeconds(response.headers.get("Retry-After")) ?? 1;
|
|
96
201
|
}
|
|
97
|
-
|
|
98
|
-
|
|
202
|
+
function readDiscordRateLimitBucket(response) {
|
|
203
|
+
const value = response.headers.get("X-RateLimit-Bucket")?.trim();
|
|
204
|
+
return value ? redactIdentifier(value, { len: 32 }) : null;
|
|
99
205
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
return await rest.post(Routes.channelWebhooks(channelId), data);
|
|
206
|
+
function readDiscordRateLimitScope(response) {
|
|
207
|
+
const value = response.headers.get("X-RateLimit-Scope");
|
|
208
|
+
return value && DISCORD_RATE_LIMIT_SCOPES.has(value) ? value : null;
|
|
104
209
|
}
|
|
210
|
+
var DiscordError = class extends Error {
|
|
211
|
+
constructor(response, body) {
|
|
212
|
+
const fallbackMessage = `Discord API request failed (${response.status})`;
|
|
213
|
+
const redactedMessage = redactSensitiveFieldValue("message", readDiscordMessage(body, fallbackMessage));
|
|
214
|
+
const redactedBody = redactDiscordErrorBody(body);
|
|
215
|
+
super(redactedMessage);
|
|
216
|
+
this.name = "DiscordError";
|
|
217
|
+
this.status = response.status;
|
|
218
|
+
this.statusCode = response.status;
|
|
219
|
+
this.rawBody = redactedBody;
|
|
220
|
+
this.discordCode = readDiscordCode(body);
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
var RateLimitError = class extends DiscordError {
|
|
224
|
+
constructor(response, body) {
|
|
225
|
+
super(response, body);
|
|
226
|
+
this.name = "RateLimitError";
|
|
227
|
+
this.retryAfter = readRetryAfter(body, response);
|
|
228
|
+
this.scope = body.global ? "global" : readDiscordRateLimitScope(response);
|
|
229
|
+
}
|
|
230
|
+
};
|
|
105
231
|
//#endregion
|
|
106
|
-
//#region extensions/discord/src/internal/
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
"
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
"
|
|
115
|
-
"description_localized",
|
|
116
|
-
"integration_types",
|
|
117
|
-
"name_localized"
|
|
118
|
-
]);
|
|
119
|
-
const nullableLocalizationFields = /* @__PURE__ */ new Set(["description_localizations", "name_localizations"]);
|
|
120
|
-
function comparableCommand(value) {
|
|
121
|
-
if (!value || typeof value !== "object") return value;
|
|
122
|
-
const omit = /* @__PURE__ */ new Set([
|
|
123
|
-
"application_id",
|
|
124
|
-
"description_localized",
|
|
125
|
-
"dm_permission",
|
|
126
|
-
"guild_id",
|
|
127
|
-
"id",
|
|
128
|
-
"name_localized",
|
|
129
|
-
"nsfw",
|
|
130
|
-
"version",
|
|
131
|
-
"default_permission"
|
|
132
|
-
]);
|
|
133
|
-
return stableComparableObject(Object.fromEntries(Object.entries(value).filter(([key, entry]) => !omit.has(key) && entry !== void 0)));
|
|
232
|
+
//#region extensions/discord/src/internal/rest-routes.ts
|
|
233
|
+
const RATE_LIMIT_HEADER_NUMBER_RE = /^\d+(?:\.\d+)?$/;
|
|
234
|
+
const DISCORD_ROUTE_IDENTIFIER_HASH_LENGTH = 32;
|
|
235
|
+
function redactWebhookTokenInPath(path) {
|
|
236
|
+
const hasLeadingSlash = path.startsWith("/");
|
|
237
|
+
const segments = path.replace(/^\/+/, "").split("/");
|
|
238
|
+
if (segments[0] !== "webhooks" || !segments[1] || !segments[2]) return path;
|
|
239
|
+
segments[2] = redactIdentifier(segments[2], { len: DISCORD_ROUTE_IDENTIFIER_HASH_LENGTH });
|
|
240
|
+
return `${hasLeadingSlash ? "/" : ""}${segments.join("/")}`;
|
|
134
241
|
}
|
|
135
|
-
function
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
const key = pathValue.at(-1);
|
|
139
|
-
if (key && unorderedCommandArrayFields.has(key) && normalized.every((entry) => typeof entry === "string" || typeof entry === "number" || typeof entry === "boolean")) return normalized.toSorted((left, right) => String(left).localeCompare(String(right)));
|
|
140
|
-
return normalized;
|
|
141
|
-
}
|
|
142
|
-
if (!value || typeof value !== "object") return value;
|
|
143
|
-
return Object.fromEntries(Object.entries(value).filter(([key, entry]) => {
|
|
144
|
-
if (entry === void 0) return false;
|
|
145
|
-
if (entry === null && nullableLocalizationFields.has(key)) return false;
|
|
146
|
-
if (pathValue.includes("options") && optionComparisonOmittedFields.has(key)) return false;
|
|
147
|
-
if ((key === "required" || key === "autocomplete") && entry === false) return false;
|
|
148
|
-
return true;
|
|
149
|
-
}).toSorted(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, typeof entry === "string" && (key === "description" || pathValue.at(-1) === "description_localizations") ? normalizeDescriptionForComparison(entry) : stableComparableObject(entry, [...pathValue, key])]));
|
|
242
|
+
function createRouteKey(method, path) {
|
|
243
|
+
const pathname = path.split("?")[0] ?? path;
|
|
244
|
+
return `${method.toUpperCase()} ${redactWebhookTokenInPath(pathname)}`;
|
|
150
245
|
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
const cjkBoundaryWhitespace = /([\u3000-\u303F\u4E00-\u9FFF\uFF00-\uFFEF])\s+([\u3000-\u303F\u4E00-\u9FFF\uFF00-\uFFEF])/g;
|
|
158
|
-
return collapsed.replace(cjkBoundaryWhitespace, "$1$2").replace(cjkBoundaryWhitespace, "$1$2").trim();
|
|
246
|
+
function readTopLevelRouteKey(path) {
|
|
247
|
+
const [pathname = path] = path.split("?");
|
|
248
|
+
const [first, id, token] = pathname.replace(/^\/+/, "").split("/");
|
|
249
|
+
if (!first || !id) return pathname;
|
|
250
|
+
if (first === "channels" || first === "guilds" || first === "webhooks") return first === "webhooks" && token ? `${first}/${id}/${redactIdentifier(token, { len: DISCORD_ROUTE_IDENTIFIER_HASH_LENGTH })}` : `${first}/${id}`;
|
|
251
|
+
return first;
|
|
159
252
|
}
|
|
160
|
-
function
|
|
161
|
-
return
|
|
253
|
+
function createBucketKey(bucket, path) {
|
|
254
|
+
return `${bucket}:${readTopLevelRouteKey(path)}`;
|
|
162
255
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
}
|
|
171
|
-
async deploy() {
|
|
172
|
-
const commands = this.params.commands.filter((command) => command.name !== "*").map((command) => command.serialize());
|
|
173
|
-
const hash = stableCommandSetHash(commands);
|
|
174
|
-
await this.loadPersistedHash();
|
|
175
|
-
if (this.hash === hash) return;
|
|
176
|
-
await this.reconcileGlobalCommands(commands);
|
|
177
|
-
this.hash = hash;
|
|
178
|
-
try {
|
|
179
|
-
await this.params.hashStore?.register(this.cacheKey, hash);
|
|
180
|
-
} catch {}
|
|
181
|
-
}
|
|
182
|
-
get cacheKey() {
|
|
183
|
-
return `app:${this.params.clientId}:global:reconcile`;
|
|
184
|
-
}
|
|
185
|
-
async reconcileGlobalCommands(desired) {
|
|
186
|
-
const existing = await this.rest.get(Routes.applicationCommands(this.params.clientId));
|
|
187
|
-
const existingByKey = new Map(existing.map((command) => [stableCommandKey(command), command]));
|
|
188
|
-
const desiredCommands = desired.map((command) => ({
|
|
189
|
-
command,
|
|
190
|
-
key: stableCommandKey(command)
|
|
191
|
-
}));
|
|
192
|
-
const desiredKeys = new Set(desiredCommands.map(({ key }) => key));
|
|
193
|
-
for (const { command, key } of desiredCommands) {
|
|
194
|
-
const current = existingByKey.get(key);
|
|
195
|
-
if (current && !commandsEqual(current, command)) await this.rest.patch(Routes.applicationCommand(this.params.clientId, current.id), { body: command });
|
|
196
|
-
}
|
|
197
|
-
for (const { command, key } of desiredCommands) {
|
|
198
|
-
if (existingByKey.has(key)) continue;
|
|
199
|
-
try {
|
|
200
|
-
await this.rest.post(Routes.applicationCommands(this.params.clientId), { body: command });
|
|
201
|
-
} catch (error) {
|
|
202
|
-
if (!isApplicationCommandLimitError(error)) throw error;
|
|
203
|
-
await this.rest.put(Routes.applicationCommands(this.params.clientId), { body: desired });
|
|
204
|
-
return;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
for (const command of existing) if (!desiredKeys.has(stableCommandKey(command))) await this.rest.delete(Routes.applicationCommand(this.params.clientId, command.id));
|
|
208
|
-
}
|
|
209
|
-
async loadPersistedHash() {
|
|
210
|
-
if (this.hashLoaded) return;
|
|
211
|
-
this.hashLoaded = true;
|
|
212
|
-
try {
|
|
213
|
-
const hash = await this.params.hashStore?.lookup(this.cacheKey);
|
|
214
|
-
if (typeof hash === "string" && hash.trim()) this.hash = hash;
|
|
215
|
-
} catch {}
|
|
216
|
-
}
|
|
217
|
-
get rest() {
|
|
218
|
-
return this.params.rest();
|
|
219
|
-
}
|
|
220
|
-
};
|
|
221
|
-
function stableCommandKey(command) {
|
|
222
|
-
return `${command.type ?? ApplicationCommandType.ChatInput}:${command.name}`;
|
|
256
|
+
function readHeaderNumber(headers, name) {
|
|
257
|
+
const value = headers.get(name);
|
|
258
|
+
if (!value) return;
|
|
259
|
+
const trimmed = value.trim();
|
|
260
|
+
if (!RATE_LIMIT_HEADER_NUMBER_RE.test(trimmed)) return;
|
|
261
|
+
const parsed = Number(trimmed);
|
|
262
|
+
return Number.isFinite(parsed) && Math.abs(parsed) <= Number.MAX_SAFE_INTEGER ? parsed : void 0;
|
|
223
263
|
}
|
|
224
|
-
function
|
|
225
|
-
|
|
264
|
+
function resolveRateLimitResetAt(delayMs) {
|
|
265
|
+
const clampedDelayMs = Math.ceil(Math.max(0, delayMs));
|
|
266
|
+
if (!Number.isSafeInteger(clampedDelayMs)) return;
|
|
267
|
+
if (clampedDelayMs === 0) return asDateTimestampMs(Date.now());
|
|
268
|
+
return resolveExpiresAtMsFromDurationMs(clampedDelayMs);
|
|
226
269
|
}
|
|
227
|
-
function
|
|
228
|
-
const
|
|
229
|
-
|
|
270
|
+
function readResetAt(response) {
|
|
271
|
+
const resetAfter = readHeaderNumber(response.headers, "X-RateLimit-Reset-After");
|
|
272
|
+
if (resetAfter !== void 0) return resolveRateLimitResetAt(resetAfter * 1e3);
|
|
273
|
+
const reset = readHeaderNumber(response.headers, "X-RateLimit-Reset");
|
|
274
|
+
return reset !== void 0 ? asDateTimestampMs(reset * 1e3) : void 0;
|
|
230
275
|
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
const [
|
|
235
|
-
|
|
236
|
-
const key = keyPart.split(":", 1)[0] ?? "";
|
|
237
|
-
const data = {};
|
|
238
|
-
const entries = firstValue === void 0 ? parts : [rawKey.slice(key.length + 1), ...parts];
|
|
239
|
-
for (const entry of entries) {
|
|
240
|
-
const index = entry.indexOf("=");
|
|
241
|
-
if (index < 0) continue;
|
|
242
|
-
const name = entry.slice(0, index).replace(/^[^:]+:/, "");
|
|
243
|
-
const raw = entry.slice(index + 1);
|
|
244
|
-
data[name] = raw === "true" ? true : raw === "false" ? false : raw;
|
|
245
|
-
}
|
|
246
|
-
return {
|
|
247
|
-
key,
|
|
248
|
-
data
|
|
249
|
-
};
|
|
276
|
+
function appendQuery(path, query) {
|
|
277
|
+
if (!query || Object.keys(query).length === 0) return path;
|
|
278
|
+
const search = new URLSearchParams();
|
|
279
|
+
for (const [key, value] of Object.entries(query)) search.set(key, String(value));
|
|
280
|
+
return `${path}?${search.toString()}`;
|
|
250
281
|
}
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
282
|
+
//#endregion
|
|
283
|
+
//#region extensions/discord/src/internal/rest-scheduler.ts
|
|
284
|
+
const MAX_QUEUE_SIZE = 1e3;
|
|
285
|
+
const MAX_CONCURRENT_WORKERS = 4;
|
|
286
|
+
const MAX_RATE_LIMIT_RETRIES = 3;
|
|
287
|
+
const requestPriorities = [
|
|
288
|
+
"critical",
|
|
289
|
+
"standard",
|
|
290
|
+
"background"
|
|
291
|
+
];
|
|
292
|
+
const laneSchedule = [
|
|
293
|
+
"critical",
|
|
294
|
+
"critical",
|
|
295
|
+
"critical",
|
|
296
|
+
"critical",
|
|
297
|
+
"critical",
|
|
298
|
+
"critical",
|
|
299
|
+
"standard",
|
|
300
|
+
"standard",
|
|
301
|
+
"standard",
|
|
302
|
+
"background"
|
|
303
|
+
];
|
|
304
|
+
function countPending(bucket) {
|
|
305
|
+
return requestPriorities.reduce((count, lane) => count + bucket.pending[lane].length, 0);
|
|
254
306
|
}
|
|
255
|
-
var
|
|
256
|
-
constructor() {
|
|
257
|
-
this.
|
|
307
|
+
var RestScheduler = class {
|
|
308
|
+
constructor(executor) {
|
|
309
|
+
this.executor = executor;
|
|
310
|
+
this.activeWorkers = 0;
|
|
311
|
+
this.buckets = /* @__PURE__ */ new Map();
|
|
312
|
+
this.globalRateLimitUntil = 0;
|
|
313
|
+
this.laneCursor = 0;
|
|
314
|
+
this.queuedByLane = {
|
|
315
|
+
critical: 0,
|
|
316
|
+
standard: 0,
|
|
317
|
+
background: 0
|
|
318
|
+
};
|
|
319
|
+
this.queuedRequests = 0;
|
|
320
|
+
this.routeBuckets = /* @__PURE__ */ new Map();
|
|
258
321
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
322
|
+
enqueue(params) {
|
|
323
|
+
if (this.queuedRequests >= MAX_QUEUE_SIZE) throw new Error("Discord request queue is full");
|
|
324
|
+
const routeKey = createRouteKey(params.method, params.path);
|
|
325
|
+
const bucket = this.getBucket(this.routeBuckets.get(routeKey) ?? routeKey);
|
|
326
|
+
return new Promise((resolve, reject) => {
|
|
327
|
+
this.queuedRequests += 1;
|
|
328
|
+
this.queuedByLane[params.priority] += 1;
|
|
329
|
+
bucket.pending[params.priority].push({
|
|
330
|
+
...params,
|
|
331
|
+
routeKey,
|
|
332
|
+
retryCount: 0,
|
|
333
|
+
resolve,
|
|
334
|
+
reject
|
|
335
|
+
});
|
|
336
|
+
this.drainQueues();
|
|
337
|
+
});
|
|
267
338
|
}
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
339
|
+
getBucket(key) {
|
|
340
|
+
const existing = this.buckets.get(key);
|
|
341
|
+
if (existing) return existing;
|
|
342
|
+
const bucket = {
|
|
343
|
+
active: 0,
|
|
344
|
+
pending: {
|
|
345
|
+
critical: [],
|
|
346
|
+
standard: [],
|
|
347
|
+
background: []
|
|
348
|
+
},
|
|
349
|
+
resetAt: 0,
|
|
350
|
+
routeKeys: /* @__PURE__ */ new Set([key])
|
|
351
|
+
};
|
|
352
|
+
this.buckets.set(key, bucket);
|
|
353
|
+
return bucket;
|
|
277
354
|
}
|
|
278
|
-
|
|
279
|
-
const
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
355
|
+
bindRouteToBucket(routeKey, bucketKey) {
|
|
356
|
+
const target = this.getBucket(bucketKey);
|
|
357
|
+
target.routeKeys.add(routeKey);
|
|
358
|
+
this.routeBuckets.set(routeKey, bucketKey);
|
|
359
|
+
const routeBucket = this.buckets.get(routeKey);
|
|
360
|
+
if (routeBucket && routeBucket !== target) {
|
|
361
|
+
for (const lane of requestPriorities) {
|
|
362
|
+
target.pending[lane].push(...routeBucket.pending[lane]);
|
|
363
|
+
routeBucket.pending[lane] = [];
|
|
364
|
+
}
|
|
365
|
+
if (routeBucket.active === 0) this.buckets.delete(routeKey);
|
|
284
366
|
}
|
|
367
|
+
return target;
|
|
285
368
|
}
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
369
|
+
recordResponse(routeKey, path, response, parsed) {
|
|
370
|
+
const bucketHeader = readDiscordRateLimitBucket(response);
|
|
371
|
+
const bucket = bucketHeader ? this.bindRouteToBucket(routeKey, createBucketKey(bucketHeader, path)) : this.getBucket(this.routeBuckets.get(routeKey) ?? routeKey);
|
|
372
|
+
const limit = readHeaderNumber(response.headers, "X-RateLimit-Limit");
|
|
373
|
+
if (limit !== void 0) bucket.limit = limit;
|
|
374
|
+
const remaining = readHeaderNumber(response.headers, "X-RateLimit-Remaining");
|
|
375
|
+
if (remaining !== void 0) bucket.remaining = remaining;
|
|
376
|
+
const resetAt = readResetAt(response);
|
|
377
|
+
if (resetAt !== void 0) bucket.resetAt = resetAt;
|
|
378
|
+
if (response.status !== 429) return;
|
|
379
|
+
const retryAt = resolveRateLimitResetAt(Math.max(0, readRetryAfter(parsed, response) * 1e3));
|
|
380
|
+
if (retryAt === void 0) return;
|
|
381
|
+
if (response.headers.get("X-RateLimit-Global") === "true" || isGlobalRateLimit(parsed)) {
|
|
382
|
+
this.globalRateLimitUntil = Math.max(this.globalRateLimitUntil, retryAt);
|
|
383
|
+
return;
|
|
294
384
|
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
};
|
|
298
|
-
//#endregion
|
|
299
|
-
//#region extensions/discord/src/internal/structures.ts
|
|
300
|
-
var Base = class {
|
|
301
|
-
constructor(client) {
|
|
302
|
-
this.client = client;
|
|
303
|
-
}
|
|
304
|
-
};
|
|
305
|
-
var PartialEntity = class extends Base {
|
|
306
|
-
constructor(client, rawDataOrId) {
|
|
307
|
-
super(client);
|
|
308
|
-
this.rawDataValue = typeof rawDataOrId === "string" ? null : rawDataOrId;
|
|
309
|
-
this.id = typeof rawDataOrId === "string" ? rawDataOrId : rawDataOrId.id;
|
|
310
|
-
}
|
|
311
|
-
};
|
|
312
|
-
var User = class extends PartialEntity {
|
|
313
|
-
get rawData() {
|
|
314
|
-
if (!this.rawDataValue) throw new Error("Partial Discord user has no raw data");
|
|
315
|
-
return this.rawDataValue;
|
|
316
|
-
}
|
|
317
|
-
get partial() {
|
|
318
|
-
return this.rawDataValue === null;
|
|
319
|
-
}
|
|
320
|
-
get username() {
|
|
321
|
-
return this.rawDataValue?.username ?? "";
|
|
322
|
-
}
|
|
323
|
-
get globalName() {
|
|
324
|
-
return this.rawDataValue?.global_name;
|
|
325
|
-
}
|
|
326
|
-
get discriminator() {
|
|
327
|
-
return this.rawDataValue?.discriminator;
|
|
385
|
+
bucket.remaining = 0;
|
|
386
|
+
bucket.resetAt = Math.max(bucket.resetAt, retryAt);
|
|
328
387
|
}
|
|
329
|
-
|
|
330
|
-
return
|
|
388
|
+
getBucketWaitMs(bucket, now) {
|
|
389
|
+
if (bucket.remaining === 0 && bucket.resetAt > now) return bucket.resetAt - now;
|
|
390
|
+
if (bucket.remaining === 0 && bucket.resetAt <= now) bucket.remaining = bucket.limit;
|
|
391
|
+
return 0;
|
|
331
392
|
}
|
|
332
|
-
|
|
333
|
-
|
|
393
|
+
scheduleDrain(delayMs = 0) {
|
|
394
|
+
if (this.drainTimer) return;
|
|
395
|
+
this.drainTimer = setTimeout(() => {
|
|
396
|
+
this.drainTimer = void 0;
|
|
397
|
+
this.drainQueues();
|
|
398
|
+
}, resolveTimerTimeoutMs(delayMs, 0, 0));
|
|
399
|
+
this.drainTimer.unref();
|
|
334
400
|
}
|
|
335
|
-
|
|
336
|
-
|
|
401
|
+
drainQueues() {
|
|
402
|
+
while (this.activeWorkers < MAX_CONCURRENT_WORKERS) {
|
|
403
|
+
const next = this.takeNextQueuedRequest();
|
|
404
|
+
if (!next.queued) {
|
|
405
|
+
if (next.waitMs !== void 0 && Number.isFinite(next.waitMs)) this.scheduleDrain(next.waitMs);
|
|
406
|
+
break;
|
|
407
|
+
}
|
|
408
|
+
const { bucket, queued } = next;
|
|
409
|
+
if (bucket.remaining !== void 0 && bucket.remaining > 0) bucket.remaining -= 1;
|
|
410
|
+
bucket.active += 1;
|
|
411
|
+
this.activeWorkers += 1;
|
|
412
|
+
this.runQueuedRequest(queued, bucket);
|
|
413
|
+
}
|
|
337
414
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
415
|
+
takeNextQueuedRequest() {
|
|
416
|
+
const now = Date.now();
|
|
417
|
+
if (this.globalRateLimitUntil > now) return { waitMs: this.globalRateLimitUntil - now };
|
|
418
|
+
for (const [key, bucket] of this.buckets) {
|
|
419
|
+
if (bucket.active !== 0 || countPending(bucket) > 0) continue;
|
|
420
|
+
if (bucket.remaining === 0 && bucket.resetAt > now) continue;
|
|
421
|
+
for (const routeKey of bucket.routeKeys) if (this.routeBuckets.get(routeKey) === key) this.routeBuckets.delete(routeKey);
|
|
422
|
+
this.buckets.delete(key);
|
|
423
|
+
}
|
|
424
|
+
let nextDelayMs;
|
|
425
|
+
const buckets = Array.from(this.buckets.values()).filter((bucket) => countPending(bucket) > 0);
|
|
426
|
+
if (buckets.length === 0) return {};
|
|
427
|
+
for (let laneOffset = 0; laneOffset < laneSchedule.length; laneOffset += 1) {
|
|
428
|
+
const lane = laneSchedule[(this.laneCursor + laneOffset) % laneSchedule.length];
|
|
429
|
+
if (!lane || this.queuedByLane[lane] <= 0) continue;
|
|
430
|
+
for (const bucket of buckets) {
|
|
431
|
+
const queue = bucket.pending[lane];
|
|
432
|
+
if (queue.length === 0 || bucket.active > 0) continue;
|
|
433
|
+
const waitMs = this.getBucketWaitMs(bucket, now);
|
|
434
|
+
if (waitMs > 0) {
|
|
435
|
+
nextDelayMs = Math.min(nextDelayMs ?? waitMs, waitMs);
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
const queued = queue.shift();
|
|
439
|
+
if (!queued) continue;
|
|
440
|
+
this.queuedByLane[lane] = Math.max(0, this.queuedByLane[lane] - 1);
|
|
441
|
+
this.laneCursor = (this.laneCursor + laneOffset + 1) % laneSchedule.length;
|
|
442
|
+
return {
|
|
443
|
+
bucket,
|
|
444
|
+
queued
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return { waitMs: nextDelayMs };
|
|
342
449
|
}
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
450
|
+
async runQueuedRequest(queued, bucket) {
|
|
451
|
+
let requeued = false;
|
|
452
|
+
try {
|
|
453
|
+
queued.resolve(await this.executor(queued));
|
|
454
|
+
} catch (error) {
|
|
455
|
+
if (error instanceof RateLimitError && this.requeueRateLimitedRequest(queued)) {
|
|
456
|
+
requeued = true;
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
queued.reject(error);
|
|
460
|
+
} finally {
|
|
461
|
+
bucket.active = Math.max(0, bucket.active - 1);
|
|
462
|
+
this.activeWorkers = Math.max(0, this.activeWorkers - 1);
|
|
463
|
+
if (!requeued) this.queuedRequests = Math.max(0, this.queuedRequests - 1);
|
|
464
|
+
this.drainQueues();
|
|
465
|
+
}
|
|
347
466
|
}
|
|
348
|
-
|
|
349
|
-
return
|
|
467
|
+
requeueRateLimitedRequest(queued) {
|
|
468
|
+
if (queued.retryCount >= MAX_RATE_LIMIT_RETRIES) return false;
|
|
469
|
+
const bucketKey = this.routeBuckets.get(queued.routeKey) ?? queued.routeKey;
|
|
470
|
+
this.getBucket(bucketKey).pending[queued.priority].push({
|
|
471
|
+
...queued,
|
|
472
|
+
retryCount: queued.retryCount + 1
|
|
473
|
+
});
|
|
474
|
+
this.queuedByLane[queued.priority] += 1;
|
|
475
|
+
return true;
|
|
350
476
|
}
|
|
351
477
|
};
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
478
|
+
function isGlobalRateLimit(parsed) {
|
|
479
|
+
return parsed && typeof parsed === "object" && "global" in parsed ? Boolean(parsed.global) : false;
|
|
480
|
+
}
|
|
481
|
+
//#endregion
|
|
482
|
+
//#region extensions/discord/src/internal/schemas.ts
|
|
483
|
+
const discordInteractionPayloadSchema = Type.Object({
|
|
484
|
+
id: Type.String({ minLength: 1 }),
|
|
485
|
+
token: Type.String({ minLength: 1 }),
|
|
486
|
+
type: Type.Number()
|
|
487
|
+
}, { additionalProperties: true });
|
|
488
|
+
const discordRateLimitBodySchema = Type.Object({
|
|
489
|
+
message: Type.Optional(Type.String()),
|
|
490
|
+
retry_after: Type.Optional(Type.Union([Type.Number(), Type.String()])),
|
|
491
|
+
global: Type.Optional(Type.Boolean()),
|
|
492
|
+
code: Type.Optional(Type.Union([Type.Number(), Type.String()]))
|
|
493
|
+
}, { additionalProperties: true });
|
|
494
|
+
function assertDiscordInteractionPayload(value) {
|
|
495
|
+
if (!Check(discordInteractionPayloadSchema, value)) throw new Error("Invalid Discord interaction payload");
|
|
496
|
+
}
|
|
497
|
+
function isDiscordRateLimitBody(value) {
|
|
498
|
+
return Check(discordRateLimitBodySchema, value);
|
|
499
|
+
}
|
|
500
|
+
//#endregion
|
|
501
|
+
//#region extensions/discord/src/internal/rest.ts
|
|
502
|
+
const DISCORD_REST_TIMEOUT_MS = 15e3;
|
|
503
|
+
const defaultOptions = {
|
|
504
|
+
baseUrl: "https://discord.com/api",
|
|
505
|
+
timeout: DISCORD_REST_TIMEOUT_MS,
|
|
506
|
+
queueRequests: true
|
|
366
507
|
};
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
508
|
+
const DISCORD_REST_RESPONSE_BODY_MAX_BYTES = 8388608;
|
|
509
|
+
const GZIP_MAGIC = [31, 139];
|
|
510
|
+
function createResponseBodyOverflowError(size) {
|
|
511
|
+
return /* @__PURE__ */ new Error(`Discord REST response body exceeds ${DISCORD_REST_RESPONSE_BODY_MAX_BYTES} bytes (received ${size})`);
|
|
512
|
+
}
|
|
513
|
+
async function readResponseBodyText(response, idleTimeoutMs) {
|
|
514
|
+
const buffer = await readResponseWithLimit(response, DISCORD_REST_RESPONSE_BODY_MAX_BYTES, {
|
|
515
|
+
chunkTimeoutMs: idleTimeoutMs,
|
|
516
|
+
onOverflow: ({ size }) => createResponseBodyOverflowError(size),
|
|
517
|
+
onIdleTimeout: ({ chunkTimeoutMs }) => /* @__PURE__ */ new Error(`Discord REST response stalled: no data received for ${chunkTimeoutMs}ms`)
|
|
518
|
+
});
|
|
519
|
+
if (!buffer.byteLength) return "";
|
|
520
|
+
if (buffer[0] === GZIP_MAGIC[0] && buffer[1] === GZIP_MAGIC[1]) try {
|
|
521
|
+
return gunzipSync(buffer, { maxOutputLength: DISCORD_REST_RESPONSE_BODY_MAX_BYTES }).toString("utf8");
|
|
522
|
+
} catch (err) {
|
|
523
|
+
if (err instanceof RangeError && "code" in err && err.code === "ERR_BUFFER_TOO_LARGE") throw createResponseBodyOverflowError("decompressed output");
|
|
524
|
+
throw err;
|
|
377
525
|
}
|
|
378
|
-
|
|
379
|
-
|
|
526
|
+
return buffer.toString("utf8");
|
|
527
|
+
}
|
|
528
|
+
function coerceResponseBody(raw) {
|
|
529
|
+
if (!raw) return;
|
|
530
|
+
try {
|
|
531
|
+
return JSON.parse(raw);
|
|
532
|
+
} catch {
|
|
533
|
+
return raw;
|
|
380
534
|
}
|
|
381
|
-
|
|
382
|
-
|
|
535
|
+
}
|
|
536
|
+
var RequestClient = class {
|
|
537
|
+
constructor(token, options) {
|
|
538
|
+
const endpoint = getDiscordEndpointRuntime();
|
|
539
|
+
const resolvedOptions = endpoint ? {
|
|
540
|
+
...options,
|
|
541
|
+
apiBaseUrl: endpoint.descriptor.restApiBaseUrl,
|
|
542
|
+
fetch: endpoint.fetch
|
|
543
|
+
} : options;
|
|
544
|
+
this.token = token.replace(/^Bot\s+/i, "");
|
|
545
|
+
this.customFetch = resolvedOptions?.fetch;
|
|
546
|
+
this.guardedEndpoint = endpoint !== void 0;
|
|
547
|
+
this.options = normalizeRequestClientOptions(resolvedOptions);
|
|
548
|
+
this.scheduler = new RestScheduler(async (request) => await this.executeRequest(request.method, request.path, {
|
|
549
|
+
data: request.data?.data,
|
|
550
|
+
query: request.query
|
|
551
|
+
}, request.routeKey, request.data?.assertCurrent, request.data?.effect));
|
|
383
552
|
}
|
|
384
|
-
get
|
|
385
|
-
return this.
|
|
553
|
+
async get(path, query) {
|
|
554
|
+
return await this.request("GET", path, { query });
|
|
386
555
|
}
|
|
387
|
-
|
|
388
|
-
return this.
|
|
556
|
+
async post(path, data, query) {
|
|
557
|
+
return await this.request("POST", path, {
|
|
558
|
+
data,
|
|
559
|
+
query
|
|
560
|
+
});
|
|
389
561
|
}
|
|
390
|
-
|
|
391
|
-
return this.
|
|
562
|
+
async patch(path, data, query) {
|
|
563
|
+
return await this.request("PATCH", path, {
|
|
564
|
+
data,
|
|
565
|
+
query
|
|
566
|
+
});
|
|
392
567
|
}
|
|
393
|
-
|
|
394
|
-
return this.
|
|
568
|
+
async put(path, data, query) {
|
|
569
|
+
return await this.request("PUT", path, {
|
|
570
|
+
data,
|
|
571
|
+
query
|
|
572
|
+
});
|
|
395
573
|
}
|
|
396
|
-
|
|
397
|
-
return this.
|
|
574
|
+
async delete(path, data, query) {
|
|
575
|
+
return await this.request("DELETE", path, {
|
|
576
|
+
data,
|
|
577
|
+
query
|
|
578
|
+
});
|
|
398
579
|
}
|
|
399
|
-
|
|
400
|
-
const
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
return
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
return this.rawDataValue?.sticker_items ?? [];
|
|
420
|
-
}
|
|
421
|
-
get mentionedUsers() {
|
|
422
|
-
return (this.rawDataValue?.mentions ?? []).map((user) => new User(this.client, user));
|
|
423
|
-
}
|
|
424
|
-
get mentionedRoles() {
|
|
425
|
-
return this.rawDataValue?.mention_roles ?? [];
|
|
426
|
-
}
|
|
427
|
-
get mentionedEveryone() {
|
|
428
|
-
return this.rawDataValue?.mention_everyone ?? false;
|
|
429
|
-
}
|
|
430
|
-
get timestamp() {
|
|
431
|
-
return this.rawDataValue?.timestamp;
|
|
432
|
-
}
|
|
433
|
-
get type() {
|
|
434
|
-
return this.rawDataValue?.type;
|
|
435
|
-
}
|
|
436
|
-
get messageReference() {
|
|
437
|
-
return this.rawDataValue?.message_reference;
|
|
438
|
-
}
|
|
439
|
-
get referencedMessage() {
|
|
440
|
-
return this.rawDataValue?.referenced_message ? new Message(this.client, this.rawDataValue.referenced_message) : null;
|
|
441
|
-
}
|
|
442
|
-
get thread() {
|
|
443
|
-
return this.rawDataValue?.thread ? channelFactory(this.client, this.rawDataValue.thread) : null;
|
|
444
|
-
}
|
|
445
|
-
async fetch() {
|
|
446
|
-
const raw = await getChannelMessage(this.client.rest, this.channelId, this.id);
|
|
447
|
-
return new Message(this.client, raw);
|
|
448
|
-
}
|
|
449
|
-
};
|
|
450
|
-
function channelFactory(clientForTest, channelData) {
|
|
451
|
-
return {
|
|
452
|
-
...channelData,
|
|
453
|
-
rawData: channelData,
|
|
454
|
-
guildId: "guild_id" in channelData ? channelData.guild_id : void 0,
|
|
455
|
-
guild: "guild_id" in channelData && typeof channelData.guild_id === "string" ? new Guild(clientForTest, channelData.guild_id) : void 0,
|
|
456
|
-
parentId: "parent_id" in channelData ? channelData.parent_id : void 0,
|
|
457
|
-
ownerId: "owner_id" in channelData ? channelData.owner_id : void 0
|
|
458
|
-
};
|
|
459
|
-
}
|
|
460
|
-
//#endregion
|
|
461
|
-
//#region extensions/discord/src/internal/entity-cache.ts
|
|
462
|
-
const DEFAULT_REST_CACHE_TTL_MS = 3e4;
|
|
463
|
-
const DEFAULT_MAX_ENTRIES = 5e3;
|
|
464
|
-
const DEFAULT_SWEEP_INTERVAL_MS = 3e4;
|
|
465
|
-
const CACHE_KIND_BY_EVENT = /* @__PURE__ */ new Map([
|
|
466
|
-
[GatewayDispatchEvents.ChannelUpdate, "channel"],
|
|
467
|
-
[GatewayDispatchEvents.ChannelDelete, "channel"],
|
|
468
|
-
[GatewayDispatchEvents.ThreadUpdate, "channel"],
|
|
469
|
-
[GatewayDispatchEvents.ThreadDelete, "channel"],
|
|
470
|
-
[GatewayDispatchEvents.GuildUpdate, "guild"],
|
|
471
|
-
[GatewayDispatchEvents.GuildEmojisUpdate, "guild-emojis"],
|
|
472
|
-
[GatewayDispatchEvents.GuildMemberAdd, "member"],
|
|
473
|
-
[GatewayDispatchEvents.GuildMemberRemove, "member"],
|
|
474
|
-
[GatewayDispatchEvents.GuildMemberUpdate, "member"]
|
|
475
|
-
]);
|
|
476
|
-
var DiscordEntityCache = class {
|
|
477
|
-
constructor(params) {
|
|
478
|
-
this.params = params;
|
|
479
|
-
this.entries = /* @__PURE__ */ new Map();
|
|
480
|
-
this.lastSweepAt = 0;
|
|
481
|
-
}
|
|
482
|
-
get size() {
|
|
483
|
-
return this.entries.size;
|
|
484
|
-
}
|
|
485
|
-
async fetchUser(id) {
|
|
486
|
-
return await this.fetchCached(`user:${id}`, async () => {
|
|
487
|
-
const raw = await getUser(this.params.rest(), id);
|
|
488
|
-
return new User(this.params.client, raw);
|
|
489
|
-
});
|
|
490
|
-
}
|
|
491
|
-
async fetchChannel(id) {
|
|
492
|
-
return await this.fetchCached(`channel:${id}`, async () => {
|
|
493
|
-
const raw = await getChannel(this.params.rest(), id);
|
|
494
|
-
return channelFactory(this.params.client, raw);
|
|
495
|
-
});
|
|
496
|
-
}
|
|
497
|
-
async fetchGuild(id) {
|
|
498
|
-
return await this.fetchCached(`guild:${id}`, async () => {
|
|
499
|
-
const raw = await getGuild(this.params.rest(), id);
|
|
500
|
-
return new Guild(this.params.client, raw);
|
|
501
|
-
});
|
|
502
|
-
}
|
|
503
|
-
async fetchMember(guildId, userId) {
|
|
504
|
-
return await this.fetchCached(`member:${guildId}:${userId}`, async () => {
|
|
505
|
-
const raw = await getGuildMember(this.params.rest(), guildId, userId);
|
|
506
|
-
return new GuildMember(this.params.client, raw);
|
|
507
|
-
});
|
|
508
|
-
}
|
|
509
|
-
async fetchGuildEmojis(guildId, fetcher) {
|
|
510
|
-
return await this.fetchCached(`guild-emojis:${guildId}`, fetcher);
|
|
511
|
-
}
|
|
512
|
-
invalidateForGatewayEvent(type, data) {
|
|
513
|
-
const kind = CACHE_KIND_BY_EVENT.get(type);
|
|
514
|
-
if (!kind) return;
|
|
515
|
-
const raw = data && typeof data === "object" ? data : {};
|
|
516
|
-
if (kind === "member") {
|
|
517
|
-
const guildId = raw.guild_id;
|
|
518
|
-
const user = raw.user && typeof raw.user === "object" ? raw.user : {};
|
|
519
|
-
if (typeof guildId === "string" && typeof user.id === "string") {
|
|
520
|
-
this.entries.delete(`member:${guildId}:${user.id}`);
|
|
521
|
-
this.entries.delete(`user:${user.id}`);
|
|
580
|
+
async request(method, path, params) {
|
|
581
|
+
const routeKey = createRouteKey(method, path);
|
|
582
|
+
const assertActionAuthority = captureDiscordRequestAuthority();
|
|
583
|
+
const assertReadAuthority = captureChannelReadAuthority();
|
|
584
|
+
const effect = captureEffectAuthority();
|
|
585
|
+
const assertCurrent = assertActionAuthority ? () => {
|
|
586
|
+
assertActionAuthority();
|
|
587
|
+
assertReadAuthority?.();
|
|
588
|
+
} : assertReadAuthority;
|
|
589
|
+
assertCurrent?.();
|
|
590
|
+
if (!this.options.queueRequests) return await this.executeRequest(method, path, params, routeKey, assertCurrent, effect);
|
|
591
|
+
return await this.scheduler.enqueue({
|
|
592
|
+
method,
|
|
593
|
+
path,
|
|
594
|
+
priority: getRequestPriority(method, path),
|
|
595
|
+
query: params.query,
|
|
596
|
+
data: {
|
|
597
|
+
data: params.data,
|
|
598
|
+
assertCurrent,
|
|
599
|
+
effect
|
|
522
600
|
}
|
|
523
|
-
} else {
|
|
524
|
-
const id = kind === "guild-emojis" ? raw.guild_id : raw.id;
|
|
525
|
-
if (typeof id === "string") this.entries.delete(`${kind}:${id}`);
|
|
526
|
-
}
|
|
527
|
-
}
|
|
528
|
-
async fetchCached(key, fetcher) {
|
|
529
|
-
const now = Date.now();
|
|
530
|
-
const cached = this.entries.get(key);
|
|
531
|
-
if (cached && cached.expiresAt > now) return cached.value;
|
|
532
|
-
if (cached) this.entries.delete(key);
|
|
533
|
-
const value = await fetcher();
|
|
534
|
-
this.maybeSweepExpired(now);
|
|
535
|
-
this.entries.set(key, {
|
|
536
|
-
expiresAt: now + DEFAULT_REST_CACHE_TTL_MS,
|
|
537
|
-
value
|
|
538
|
-
});
|
|
539
|
-
if (this.entries.size > DEFAULT_MAX_ENTRIES) this.entries.delete(this.entries.keys().next().value);
|
|
540
|
-
return value;
|
|
541
|
-
}
|
|
542
|
-
maybeSweepExpired(now) {
|
|
543
|
-
if (now - this.lastSweepAt < DEFAULT_SWEEP_INTERVAL_MS) return;
|
|
544
|
-
this.lastSweepAt = now;
|
|
545
|
-
for (const [key, entry] of this.entries) if (entry.expiresAt <= now) this.entries.delete(key);
|
|
546
|
-
}
|
|
547
|
-
};
|
|
548
|
-
//#endregion
|
|
549
|
-
//#region extensions/discord/src/internal/event-queue.ts
|
|
550
|
-
const DEFAULT_MAX_QUEUE_SIZE = 1e4;
|
|
551
|
-
const DEFAULT_MAX_CONCURRENCY = 50;
|
|
552
|
-
const DEFAULT_LISTENER_TIMEOUT_MS = 12e4;
|
|
553
|
-
const DEFAULT_SLOW_LISTENER_THRESHOLD_MS = 3e4;
|
|
554
|
-
var DiscordEventQueue = class {
|
|
555
|
-
constructor(options = {}) {
|
|
556
|
-
this.queue = [];
|
|
557
|
-
this.queueHead = 0;
|
|
558
|
-
this.processing = 0;
|
|
559
|
-
this.processedCount = 0;
|
|
560
|
-
this.droppedCount = 0;
|
|
561
|
-
this.timeoutCount = 0;
|
|
562
|
-
this.options = {
|
|
563
|
-
maxQueueSize: normalizePositiveInteger(options.maxQueueSize, DEFAULT_MAX_QUEUE_SIZE),
|
|
564
|
-
maxConcurrency: normalizePositiveInteger(options.maxConcurrency, DEFAULT_MAX_CONCURRENCY),
|
|
565
|
-
listenerTimeout: normalizePositiveInteger(options.listenerTimeout, DEFAULT_LISTENER_TIMEOUT_MS),
|
|
566
|
-
slowListenerThreshold: normalizePositiveInteger(options.slowListenerThreshold, DEFAULT_SLOW_LISTENER_THRESHOLD_MS)
|
|
567
|
-
};
|
|
568
|
-
}
|
|
569
|
-
enqueue(params) {
|
|
570
|
-
if (this.pendingQueueSize >= this.options.maxQueueSize) {
|
|
571
|
-
this.droppedCount += 1;
|
|
572
|
-
return Promise.reject(/* @__PURE__ */ new Error(`Discord event queue is full for ${params.eventType}; maxQueueSize=${this.options.maxQueueSize}`));
|
|
573
|
-
}
|
|
574
|
-
return new Promise((resolve, reject) => {
|
|
575
|
-
this.queue.push({
|
|
576
|
-
...params,
|
|
577
|
-
resolve,
|
|
578
|
-
reject
|
|
579
|
-
});
|
|
580
|
-
this.processNext();
|
|
581
601
|
});
|
|
582
602
|
}
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
maxConcurrency: this.options.maxConcurrency
|
|
592
|
-
};
|
|
593
|
-
}
|
|
594
|
-
get pendingQueueSize() {
|
|
595
|
-
return Math.max(0, this.queue.length - this.queueHead);
|
|
596
|
-
}
|
|
597
|
-
takeNextJob() {
|
|
598
|
-
const job = this.queue[this.queueHead];
|
|
599
|
-
this.queueHead += 1;
|
|
600
|
-
if (this.queueHead >= this.queue.length) {
|
|
601
|
-
this.queue.length = 0;
|
|
602
|
-
this.queueHead = 0;
|
|
603
|
-
} else if (this.queueHead > 256 && this.queueHead * 2 > this.queue.length) {
|
|
604
|
-
this.queue.splice(0, this.queueHead);
|
|
605
|
-
this.queueHead = 0;
|
|
606
|
-
}
|
|
607
|
-
return job;
|
|
608
|
-
}
|
|
609
|
-
processNext() {
|
|
610
|
-
while (this.processing < this.options.maxConcurrency && this.pendingQueueSize > 0) {
|
|
611
|
-
const job = this.takeNextJob();
|
|
612
|
-
if (!job) return;
|
|
613
|
-
this.processing += 1;
|
|
614
|
-
const listenerPromise = Promise.resolve().then(() => job.run());
|
|
615
|
-
const runJobPromise = this.runJob(job, listenerPromise);
|
|
616
|
-
runJobPromise.then(job.resolve, job.reject).finally(() => {
|
|
617
|
-
this.processedCount += 1;
|
|
618
|
-
});
|
|
619
|
-
Promise.allSettled([runJobPromise, listenerPromise]).then(([dispatchResult, listenerResult]) => {
|
|
620
|
-
if (dispatchResult.status === "fulfilled" && dispatchResult.value === "timed-out" && listenerResult.status === "rejected") console.error(`[EventQueue] Listener ${job.listenerName} failed after timeout for event ${job.eventType}:`, listenerResult.reason);
|
|
621
|
-
this.processing -= 1;
|
|
622
|
-
this.processNext();
|
|
623
|
-
});
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
async runJob(job, listenerPromise) {
|
|
627
|
-
const startedAt = Date.now();
|
|
603
|
+
async executeRequest(method, path, params, routeKey = createRouteKey(method, path), assertCurrent, effect = captureEffectAuthority()) {
|
|
604
|
+
const url = `${this.options.apiBaseUrl}${appendQuery(path, params.query)}`;
|
|
605
|
+
const headers = new Headers({ "User-Agent": "OpenClaw Discord" });
|
|
606
|
+
if (this.token !== "webhook") headers.set("Authorization", `Bot ${this.token}`);
|
|
607
|
+
const body = serializeRequestBody(params.data, headers);
|
|
608
|
+
const controller = new AbortController();
|
|
609
|
+
const timeout = setTimeout(() => controller.abort(), this.options.timeout).unref();
|
|
610
|
+
const signal = this.options.signal ? AbortSignal.any([this.options.signal, controller.signal]) : controller.signal;
|
|
628
611
|
try {
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
this.
|
|
639
|
-
|
|
640
|
-
|
|
612
|
+
assertCurrent?.();
|
|
613
|
+
const init = {
|
|
614
|
+
method,
|
|
615
|
+
headers,
|
|
616
|
+
body,
|
|
617
|
+
signal
|
|
618
|
+
};
|
|
619
|
+
const request = () => {
|
|
620
|
+
assertCurrent?.();
|
|
621
|
+
return this.customFetch && assertCurrent ? this.customFetch(url, init, assertCurrent) : (this.customFetch ?? fetch)(url, init);
|
|
622
|
+
};
|
|
623
|
+
const response = this.guardedEndpoint ? await effect.run(request) : await effect.initiate(request);
|
|
624
|
+
const parsed = coerceResponseBody(await readResponseBodyText(response, this.options.timeout).catch((error) => {
|
|
625
|
+
if (response.ok) throw error;
|
|
626
|
+
return "";
|
|
627
|
+
}));
|
|
628
|
+
this.scheduler.recordResponse(routeKey, path, response, parsed);
|
|
629
|
+
if (response.status === 204) return;
|
|
630
|
+
if (response.status === 429) {
|
|
631
|
+
const rateLimitBody = isDiscordRateLimitBody(parsed) ? parsed : void 0;
|
|
632
|
+
throw new RateLimitError(response, {
|
|
633
|
+
message: readDiscordMessage(rateLimitBody, "Rate limited"),
|
|
634
|
+
retry_after: readRetryAfter(rateLimitBody, response),
|
|
635
|
+
code: readDiscordCode(rateLimitBody),
|
|
636
|
+
global: Boolean(rateLimitBody?.global)
|
|
637
|
+
});
|
|
641
638
|
}
|
|
642
|
-
|
|
643
|
-
return
|
|
639
|
+
if (!response.ok) throw new DiscordError(response, parsed);
|
|
640
|
+
return parsed;
|
|
641
|
+
} finally {
|
|
642
|
+
clearTimeout(timeout);
|
|
644
643
|
}
|
|
645
644
|
}
|
|
646
|
-
logSlowListener(job, durationMs) {
|
|
647
|
-
if (durationMs < this.options.slowListenerThreshold) return;
|
|
648
|
-
console.warn(`[EventQueue] Slow listener detected: ${job.listenerName} took ${durationMs}ms for event ${job.eventType}`);
|
|
649
|
-
}
|
|
650
645
|
};
|
|
651
|
-
function
|
|
652
|
-
|
|
653
|
-
|
|
646
|
+
function normalizeRequestClientOptions(options) {
|
|
647
|
+
const merged = {
|
|
648
|
+
...defaultOptions,
|
|
649
|
+
...options
|
|
650
|
+
};
|
|
651
|
+
return {
|
|
652
|
+
...merged,
|
|
653
|
+
apiBaseUrl: options?.apiBaseUrl ?? `${options?.baseUrl ?? defaultOptions.baseUrl}/v10`,
|
|
654
|
+
timeout: clampTimerTimeoutMs(merged.timeout, 1) ?? resolveTimerTimeoutMs(defaultOptions.timeout, 1)
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
function getRequestPriority(method, path) {
|
|
658
|
+
const normalizedMethod = method.toUpperCase();
|
|
659
|
+
const normalizedPath = path.toLowerCase();
|
|
660
|
+
if (/^\/interactions\/\d+\/[^/]+\/callback$/.test(normalizedPath)) return "critical";
|
|
661
|
+
return normalizedMethod === "GET" ? "background" : "standard";
|
|
654
662
|
}
|
|
655
663
|
//#endregion
|
|
656
|
-
//#region extensions/discord/src/internal/
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
664
|
+
//#region extensions/discord/src/internal/api.guild.ts
|
|
665
|
+
const discordGuildEmojiListSchema = Type.Array(Type.Object({
|
|
666
|
+
id: Type.Union([Type.String(), Type.Null()]),
|
|
667
|
+
name: Type.Union([Type.String(), Type.Null()]),
|
|
668
|
+
animated: Type.Optional(Type.Boolean())
|
|
669
|
+
}, { additionalProperties: true }));
|
|
670
|
+
async function getGuild(rest, guildId) {
|
|
671
|
+
return await rest.get(Routes.guild(guildId));
|
|
660
672
|
}
|
|
661
|
-
function
|
|
662
|
-
|
|
663
|
-
return Array.isArray(options) ? options : [];
|
|
673
|
+
function guildUserRead(route) {
|
|
674
|
+
return async (rest, guildId, userId) => await rest.get(Routes[route](guildId, userId));
|
|
664
675
|
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
676
|
+
const getGuildMember = guildUserRead("guildMember");
|
|
677
|
+
const getGuildVoiceState = guildUserRead("guildVoiceState");
|
|
678
|
+
async function listGuildEmojis(rest, guildId) {
|
|
679
|
+
const emojis = await rest.get(Routes.guildEmojis(guildId));
|
|
680
|
+
if (!Check(discordGuildEmojiListSchema, emojis)) throw new Error("Invalid Discord guild emoji response.");
|
|
681
|
+
return emojis;
|
|
668
682
|
}
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
const
|
|
673
|
-
if (
|
|
683
|
+
//#endregion
|
|
684
|
+
//#region extensions/discord/src/internal/api.messages.ts
|
|
685
|
+
function normalizeDiscordMessageId(messageId) {
|
|
686
|
+
const normalized = messageId.trim();
|
|
687
|
+
if (!/^[0-9]+$/u.test(normalized)) throw new Error("Invalid Discord message ID. Expected decimal digits.");
|
|
688
|
+
return normalized;
|
|
674
689
|
}
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
690
|
+
async function getChannel(rest, channelId) {
|
|
691
|
+
return await rest.get(Routes.channel(channelId));
|
|
692
|
+
}
|
|
693
|
+
async function createChannelMessage(rest, channelId, data) {
|
|
694
|
+
return await rest.post(Routes.channelMessages(channelId), data);
|
|
695
|
+
}
|
|
696
|
+
async function getThreadMember(rest, threadId, userId) {
|
|
697
|
+
return await rest.get(Routes.threadMembers(threadId, userId));
|
|
698
|
+
}
|
|
699
|
+
async function getChannelMessage(rest, channelId, messageId) {
|
|
700
|
+
return await rest.get(Routes.channelMessage(channelId, normalizeDiscordMessageId(messageId)));
|
|
701
|
+
}
|
|
702
|
+
async function editChannelMessage(rest, channelId, messageId, data) {
|
|
703
|
+
return await rest.patch(Routes.channelMessage(channelId, normalizeDiscordMessageId(messageId)), data);
|
|
704
|
+
}
|
|
705
|
+
function messageMutation(method, route) {
|
|
706
|
+
return async (rest, channelId, messageId) => {
|
|
707
|
+
await rest[method](Routes[route](channelId, normalizeDiscordMessageId(messageId)));
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
const deleteChannelMessage = messageMutation("delete", "channelMessage");
|
|
711
|
+
const pinChannelMessage = messageMutation("put", "channelMessagesPin");
|
|
712
|
+
const unpinChannelMessage = messageMutation("delete", "channelMessagesPin");
|
|
713
|
+
async function createThread(rest, channelId, data, messageId) {
|
|
714
|
+
const route = messageId === void 0 ? Routes.threads(channelId) : Routes.threads(channelId, normalizeDiscordMessageId(messageId));
|
|
715
|
+
return await rest.post(route, data);
|
|
716
|
+
}
|
|
717
|
+
//#endregion
|
|
718
|
+
//#region extensions/discord/src/internal/api.reactions.ts
|
|
719
|
+
function ownReactionMutation(method) {
|
|
720
|
+
return async (rest, channelId, messageId, encodedEmoji) => {
|
|
721
|
+
await rest[method](Routes.channelMessageOwnReaction(channelId, normalizeDiscordMessageId(messageId), encodedEmoji));
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
const createOwnMessageReaction = ownReactionMutation("put");
|
|
725
|
+
const deleteOwnMessageReaction = ownReactionMutation("delete");
|
|
726
|
+
async function listMessageReactionUsers(rest, channelId, messageId, encodedEmoji, query) {
|
|
727
|
+
return await rest.get(Routes.channelMessageReaction(channelId, normalizeDiscordMessageId(messageId), encodedEmoji), query);
|
|
728
|
+
}
|
|
729
|
+
//#endregion
|
|
730
|
+
//#region extensions/discord/src/internal/api.users.ts
|
|
731
|
+
async function getCurrentUser(rest) {
|
|
732
|
+
return await rest.get(Routes.user("@me"));
|
|
733
|
+
}
|
|
734
|
+
async function getUser(rest, userId) {
|
|
735
|
+
return await rest.get(Routes.user(userId));
|
|
736
|
+
}
|
|
737
|
+
async function createUserDmChannel(rest, recipientId) {
|
|
738
|
+
return await rest.post(Routes.userChannels(), { body: { recipient_id: recipientId } });
|
|
739
|
+
}
|
|
740
|
+
//#endregion
|
|
741
|
+
//#region extensions/discord/src/internal/commands.ts
|
|
742
|
+
async function deferCommandInteractionIfNeeded(command, interaction) {
|
|
743
|
+
if (!command.defer) return;
|
|
744
|
+
await interaction.defer({ ephemeral: command.ephemeral });
|
|
745
|
+
}
|
|
746
|
+
function readRawCommandOptions(interaction) {
|
|
747
|
+
const options = interaction.rawData.data?.options;
|
|
748
|
+
return Array.isArray(options) ? options : [];
|
|
749
|
+
}
|
|
750
|
+
function findSelectedSubcommand(subcommands, interaction) {
|
|
751
|
+
const subcommandName = readRawCommandOptions(interaction).find((option) => option.type === ApplicationCommandOptionType.Subcommand)?.name;
|
|
752
|
+
return typeof subcommandName === "string" ? subcommands.find((command) => command.name === subcommandName) : void 0;
|
|
753
|
+
}
|
|
754
|
+
function resolveFocusedCommandOptionAutocompleteHandler(command, interaction) {
|
|
755
|
+
const focusedName = interaction.options.getFocused()?.name;
|
|
756
|
+
const options = command.commandKind === "group" ? findSelectedSubcommand(command.subcommands, interaction)?.options : command.options;
|
|
757
|
+
const option = focusedName ? options?.find((candidate) => candidate.name === focusedName) : void 0;
|
|
758
|
+
if (option?.type === ApplicationCommandOptionType.String || option?.type === ApplicationCommandOptionType.Integer || option?.type === ApplicationCommandOptionType.Number) return typeof option.autocomplete === "function" ? option.autocomplete : void 0;
|
|
759
|
+
}
|
|
760
|
+
var BaseCommand = class {
|
|
761
|
+
constructor() {
|
|
762
|
+
this.defer = false;
|
|
763
|
+
this.ephemeral = false;
|
|
764
|
+
this.type = ApplicationCommandType.ChatInput;
|
|
765
|
+
}
|
|
766
|
+
serialize() {
|
|
767
|
+
return stripUndefinedFields({
|
|
768
|
+
name: this.name,
|
|
769
|
+
description: this.description ?? "",
|
|
770
|
+
description_localizations: this.descriptionLocalizations,
|
|
771
|
+
type: this.type,
|
|
772
|
+
options: this.serializeOptions(),
|
|
773
|
+
integration_types: [0, 1],
|
|
689
774
|
contexts: [
|
|
690
775
|
InteractionContextType.Guild,
|
|
691
776
|
InteractionContextType.BotDM,
|
|
@@ -742,6 +827,161 @@ var CommandWithSubcommands = class extends BaseCommand {
|
|
|
742
827
|
}
|
|
743
828
|
};
|
|
744
829
|
//#endregion
|
|
830
|
+
//#region extensions/discord/src/internal/structures.ts
|
|
831
|
+
var Base = class {
|
|
832
|
+
constructor(client) {
|
|
833
|
+
this.client = client;
|
|
834
|
+
}
|
|
835
|
+
};
|
|
836
|
+
var PartialEntity = class extends Base {
|
|
837
|
+
constructor(client, rawDataOrId) {
|
|
838
|
+
super(client);
|
|
839
|
+
this.rawDataValue = typeof rawDataOrId === "string" ? null : rawDataOrId;
|
|
840
|
+
this.id = typeof rawDataOrId === "string" ? rawDataOrId : rawDataOrId.id;
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
var User = class extends PartialEntity {
|
|
844
|
+
get username() {
|
|
845
|
+
return this.rawDataValue?.username ?? "";
|
|
846
|
+
}
|
|
847
|
+
get globalName() {
|
|
848
|
+
return this.rawDataValue?.global_name;
|
|
849
|
+
}
|
|
850
|
+
get discriminator() {
|
|
851
|
+
return this.rawDataValue?.discriminator;
|
|
852
|
+
}
|
|
853
|
+
get bot() {
|
|
854
|
+
return this.rawDataValue?.bot;
|
|
855
|
+
}
|
|
856
|
+
get avatar() {
|
|
857
|
+
return this.rawDataValue?.avatar;
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
var Role = class extends PartialEntity {
|
|
861
|
+
get name() {
|
|
862
|
+
return this.rawDataValue?.name ?? "";
|
|
863
|
+
}
|
|
864
|
+
};
|
|
865
|
+
var Guild = class extends PartialEntity {
|
|
866
|
+
get name() {
|
|
867
|
+
return this.rawDataValue?.name ?? "";
|
|
868
|
+
}
|
|
869
|
+
get icon() {
|
|
870
|
+
return this.rawDataValue?.icon;
|
|
871
|
+
}
|
|
872
|
+
};
|
|
873
|
+
var GuildMember = class extends Base {
|
|
874
|
+
constructor(client, rawData) {
|
|
875
|
+
super(client);
|
|
876
|
+
this.rawData = rawData;
|
|
877
|
+
}
|
|
878
|
+
get user() {
|
|
879
|
+
return this.rawData.user ? new User(this.client, this.rawData.user) : null;
|
|
880
|
+
}
|
|
881
|
+
get roles() {
|
|
882
|
+
return this.rawData.roles ?? [];
|
|
883
|
+
}
|
|
884
|
+
get nickname() {
|
|
885
|
+
return this.rawData.nick ?? void 0;
|
|
886
|
+
}
|
|
887
|
+
};
|
|
888
|
+
var Message = class Message extends Base {
|
|
889
|
+
constructor(client, rawDataOrIds) {
|
|
890
|
+
super(client);
|
|
891
|
+
this.rawDataValue = typeof rawDataOrIds === "string" || !("author" in rawDataOrIds) ? null : rawDataOrIds;
|
|
892
|
+
this.id = typeof rawDataOrIds === "string" ? rawDataOrIds : rawDataOrIds.id;
|
|
893
|
+
this.channelId = typeof rawDataOrIds === "string" ? "" : "channel_id" in rawDataOrIds ? rawDataOrIds.channel_id : rawDataOrIds.channelId ?? "";
|
|
894
|
+
}
|
|
895
|
+
get rawData() {
|
|
896
|
+
if (!this.rawDataValue) throw new Error("Partial Discord message has no raw data");
|
|
897
|
+
return this.rawDataValue;
|
|
898
|
+
}
|
|
899
|
+
get partial() {
|
|
900
|
+
return this.rawDataValue === null;
|
|
901
|
+
}
|
|
902
|
+
get message() {
|
|
903
|
+
return this;
|
|
904
|
+
}
|
|
905
|
+
get channel_id() {
|
|
906
|
+
return this.channelId;
|
|
907
|
+
}
|
|
908
|
+
get guild_id() {
|
|
909
|
+
return this.rawDataValue?.guild_id;
|
|
910
|
+
}
|
|
911
|
+
get guild() {
|
|
912
|
+
return this.guild_id ? new Guild(this.client, this.guild_id) : null;
|
|
913
|
+
}
|
|
914
|
+
get webhookId() {
|
|
915
|
+
return this.webhook_id;
|
|
916
|
+
}
|
|
917
|
+
get webhook_id() {
|
|
918
|
+
return this.rawDataValue?.webhook_id ?? null;
|
|
919
|
+
}
|
|
920
|
+
get member() {
|
|
921
|
+
const member = this.rawDataValue?.member;
|
|
922
|
+
return member ? new GuildMember(this.client, member) : null;
|
|
923
|
+
}
|
|
924
|
+
get rawMember() {
|
|
925
|
+
return this.rawDataValue?.member;
|
|
926
|
+
}
|
|
927
|
+
get content() {
|
|
928
|
+
return this.rawDataValue?.content ?? "";
|
|
929
|
+
}
|
|
930
|
+
get author() {
|
|
931
|
+
return this.rawDataValue?.author ? new User(this.client, this.rawDataValue.author) : null;
|
|
932
|
+
}
|
|
933
|
+
get embeds() {
|
|
934
|
+
return this.rawDataValue?.embeds ?? [];
|
|
935
|
+
}
|
|
936
|
+
get components() {
|
|
937
|
+
return this.rawDataValue?.components;
|
|
938
|
+
}
|
|
939
|
+
get attachments() {
|
|
940
|
+
return this.rawDataValue?.attachments ?? [];
|
|
941
|
+
}
|
|
942
|
+
get stickers() {
|
|
943
|
+
return this.rawDataValue?.sticker_items ?? [];
|
|
944
|
+
}
|
|
945
|
+
get mentionedUsers() {
|
|
946
|
+
return (this.rawDataValue?.mentions ?? []).map((user) => new User(this.client, user));
|
|
947
|
+
}
|
|
948
|
+
get mentionedRoles() {
|
|
949
|
+
return this.rawDataValue?.mention_roles ?? [];
|
|
950
|
+
}
|
|
951
|
+
get mentionedEveryone() {
|
|
952
|
+
return this.rawDataValue?.mention_everyone ?? false;
|
|
953
|
+
}
|
|
954
|
+
get timestamp() {
|
|
955
|
+
return this.rawDataValue?.timestamp;
|
|
956
|
+
}
|
|
957
|
+
get type() {
|
|
958
|
+
return this.rawDataValue?.type;
|
|
959
|
+
}
|
|
960
|
+
get messageReference() {
|
|
961
|
+
return this.rawDataValue?.message_reference;
|
|
962
|
+
}
|
|
963
|
+
get referencedMessage() {
|
|
964
|
+
return this.rawDataValue?.referenced_message ? new Message(this.client, this.rawDataValue.referenced_message) : null;
|
|
965
|
+
}
|
|
966
|
+
get thread() {
|
|
967
|
+
return this.rawDataValue?.thread ? channelFactory(this.client, this.rawDataValue.thread) : null;
|
|
968
|
+
}
|
|
969
|
+
async fetch() {
|
|
970
|
+
const raw = await getChannelMessage(this.client.rest, this.channelId, this.id);
|
|
971
|
+
return new Message(this.client, raw);
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
function channelFactory(clientForTest, channelData) {
|
|
975
|
+
return {
|
|
976
|
+
...channelData,
|
|
977
|
+
rawData: channelData,
|
|
978
|
+
guildId: "guild_id" in channelData ? channelData.guild_id : void 0,
|
|
979
|
+
guild: "guild_id" in channelData && typeof channelData.guild_id === "string" ? new Guild(clientForTest, channelData.guild_id) : void 0,
|
|
980
|
+
parentId: "parent_id" in channelData ? channelData.parent_id : void 0,
|
|
981
|
+
ownerId: "owner_id" in channelData ? channelData.owner_id : void 0
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
//#endregion
|
|
745
985
|
//#region extensions/discord/src/internal/interaction-options.ts
|
|
746
986
|
function findOption(options, matches) {
|
|
747
987
|
for (const option of options ?? []) {
|
|
@@ -786,11 +1026,6 @@ var OptionsHandler = class {
|
|
|
786
1026
|
}
|
|
787
1027
|
};
|
|
788
1028
|
//#endregion
|
|
789
|
-
//#region extensions/discord/src/internal/interaction-response.ts
|
|
790
|
-
function needsComponentsV2Query(body) {
|
|
791
|
-
return body !== null && typeof body === "object" && "flags" in body && typeof body.flags === "number" && (body.flags & MessageFlags.IsComponentsV2) !== 0;
|
|
792
|
-
}
|
|
793
|
-
//#endregion
|
|
794
1029
|
//#region extensions/discord/src/internal/modal-fields.ts
|
|
795
1030
|
function extractModalFields(components) {
|
|
796
1031
|
const out = {};
|
|
@@ -873,6 +1108,12 @@ var Embed = class {
|
|
|
873
1108
|
};
|
|
874
1109
|
//#endregion
|
|
875
1110
|
//#region extensions/discord/src/internal/payload.ts
|
|
1111
|
+
function asSerializableComponent(component) {
|
|
1112
|
+
return {
|
|
1113
|
+
isV2: component.type !== ComponentType.ActionRow,
|
|
1114
|
+
serialize: () => component
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
876
1117
|
function hasDiscordV2Components(components) {
|
|
877
1118
|
return Boolean(components?.some((component) => "isV2" in component && component.isV2 || "type" in component && component.type !== ComponentType.ActionRow));
|
|
878
1119
|
}
|
|
@@ -898,26 +1139,10 @@ function serializePayload(payload) {
|
|
|
898
1139
|
});
|
|
899
1140
|
}
|
|
900
1141
|
//#endregion
|
|
901
|
-
//#region extensions/discord/src/internal/schemas.ts
|
|
902
|
-
const discordInteractionPayloadSchema = Type.Object({
|
|
903
|
-
id: Type.String({ minLength: 1 }),
|
|
904
|
-
token: Type.String({ minLength: 1 }),
|
|
905
|
-
type: Type.Number()
|
|
906
|
-
}, { additionalProperties: true });
|
|
907
|
-
const discordRateLimitBodySchema = Type.Object({
|
|
908
|
-
message: Type.Optional(Type.String()),
|
|
909
|
-
retry_after: Type.Optional(Type.Union([Type.Number(), Type.String()])),
|
|
910
|
-
global: Type.Optional(Type.Boolean()),
|
|
911
|
-
code: Type.Optional(Type.Union([Type.Number(), Type.String()]))
|
|
912
|
-
}, { additionalProperties: true });
|
|
913
|
-
function assertDiscordInteractionPayload(value) {
|
|
914
|
-
if (!Check(discordInteractionPayloadSchema, value)) throw new Error("Invalid Discord interaction payload");
|
|
915
|
-
}
|
|
916
|
-
function isDiscordRateLimitBody(value) {
|
|
917
|
-
return Check(discordRateLimitBodySchema, value);
|
|
918
|
-
}
|
|
919
|
-
//#endregion
|
|
920
1142
|
//#region extensions/discord/src/internal/interactions.ts
|
|
1143
|
+
function needsComponentsV2Query(body) {
|
|
1144
|
+
return "flags" in body && ((body.flags ?? 0) & MessageFlags.IsComponentsV2) !== 0;
|
|
1145
|
+
}
|
|
921
1146
|
function readInteractionUser(rawData, client) {
|
|
922
1147
|
const directUser = "user" in rawData ? rawData.user : void 0;
|
|
923
1148
|
if (directUser && typeof directUser === "object" && "id" in directUser) return new User(client, directUser);
|
|
@@ -1050,12 +1275,6 @@ var BaseComponentInteraction = class extends BaseInteraction {
|
|
|
1050
1275
|
return await this.callback(InteractionResponseType.LaunchActivity);
|
|
1051
1276
|
}
|
|
1052
1277
|
};
|
|
1053
|
-
var ButtonInteraction = class extends BaseComponentInteraction {};
|
|
1054
|
-
var StringSelectMenuInteraction = class extends BaseComponentInteraction {};
|
|
1055
|
-
var UserSelectMenuInteraction = class extends BaseComponentInteraction {};
|
|
1056
|
-
var RoleSelectMenuInteraction = class extends BaseComponentInteraction {};
|
|
1057
|
-
var MentionableSelectMenuInteraction = class extends BaseComponentInteraction {};
|
|
1058
|
-
var ChannelSelectMenuInteraction = class extends BaseComponentInteraction {};
|
|
1059
1278
|
var ModalInteraction = class extends BaseInteraction {
|
|
1060
1279
|
constructor(client, rawData) {
|
|
1061
1280
|
super(client, rawData);
|
|
@@ -1065,20 +1284,12 @@ var ModalInteraction = class extends BaseInteraction {
|
|
|
1065
1284
|
return await this.callback(InteractionResponseType.DeferredMessageUpdate);
|
|
1066
1285
|
}
|
|
1067
1286
|
};
|
|
1068
|
-
const componentInteractions = /* @__PURE__ */ new Map([
|
|
1069
|
-
[ComponentType.Button, ButtonInteraction],
|
|
1070
|
-
[ComponentType.StringSelect, StringSelectMenuInteraction],
|
|
1071
|
-
[ComponentType.UserSelect, UserSelectMenuInteraction],
|
|
1072
|
-
[ComponentType.RoleSelect, RoleSelectMenuInteraction],
|
|
1073
|
-
[ComponentType.MentionableSelect, MentionableSelectMenuInteraction],
|
|
1074
|
-
[ComponentType.ChannelSelect, ChannelSelectMenuInteraction]
|
|
1075
|
-
]);
|
|
1076
1287
|
function createInteraction(client, rawData) {
|
|
1077
1288
|
assertDiscordInteractionPayload(rawData);
|
|
1078
1289
|
if (rawData.type === InteractionType.ApplicationCommandAutocomplete) return new AutocompleteInteraction(client, rawData);
|
|
1079
1290
|
if (rawData.type === InteractionType.ApplicationCommand) return new CommandInteraction(client, rawData);
|
|
1080
1291
|
if (rawData.type === InteractionType.ModalSubmit) return new ModalInteraction(client, rawData);
|
|
1081
|
-
if (rawData.type === InteractionType.MessageComponent) return new
|
|
1292
|
+
if (rawData.type === InteractionType.MessageComponent) return new BaseComponentInteraction(client, rawData);
|
|
1082
1293
|
return new BaseInteraction(client, rawData);
|
|
1083
1294
|
}
|
|
1084
1295
|
//#endregion
|
|
@@ -1098,39 +1309,36 @@ async function dispatchInteraction(client, rawData) {
|
|
|
1098
1309
|
return;
|
|
1099
1310
|
}
|
|
1100
1311
|
try {
|
|
1101
|
-
|
|
1312
|
+
if (rawData.type === InteractionType.ApplicationCommand) {
|
|
1313
|
+
const command = client.commands.find((entry) => entry.name === rawData.data?.name);
|
|
1314
|
+
if (command) {
|
|
1315
|
+
await deferCommandInteractionIfNeeded(command, interaction);
|
|
1316
|
+
await command.run(interaction);
|
|
1317
|
+
}
|
|
1318
|
+
return;
|
|
1319
|
+
}
|
|
1320
|
+
if (rawData.type === InteractionType.MessageComponent) {
|
|
1321
|
+
const customId = rawData.data?.custom_id;
|
|
1322
|
+
if (!customId) return;
|
|
1323
|
+
const componentInteraction = interaction;
|
|
1324
|
+
const component = client.componentHandler.resolve(customId, { componentType: rawData.data?.component_type });
|
|
1325
|
+
if (component) {
|
|
1326
|
+
await deferComponentInteractionIfNeeded(component, componentInteraction);
|
|
1327
|
+
await component.run(componentInteraction, (component.customIdParser ?? parseCustomId)(customId).data);
|
|
1328
|
+
}
|
|
1329
|
+
return;
|
|
1330
|
+
}
|
|
1331
|
+
if (rawData.type === InteractionType.ModalSubmit) {
|
|
1332
|
+
const customId = rawData.data?.custom_id;
|
|
1333
|
+
if (!customId) return;
|
|
1334
|
+
const modal = client.modalHandler.resolve(customId);
|
|
1335
|
+
if (modal) await modal.run(interaction, modal.customIdParser(customId).data);
|
|
1336
|
+
}
|
|
1102
1337
|
} catch (error) {
|
|
1103
1338
|
await reportInteractionFailure(interaction);
|
|
1104
1339
|
throw error;
|
|
1105
1340
|
}
|
|
1106
1341
|
}
|
|
1107
|
-
async function dispatchAcknowledgeableInteraction(client, rawData, interaction) {
|
|
1108
|
-
if (rawData.type === InteractionType.ApplicationCommand) {
|
|
1109
|
-
const command = client.commands.find((entry) => entry.name === rawData.data?.name);
|
|
1110
|
-
if (command) {
|
|
1111
|
-
await deferCommandInteractionIfNeeded(command, interaction);
|
|
1112
|
-
await command.run(interaction);
|
|
1113
|
-
}
|
|
1114
|
-
return;
|
|
1115
|
-
}
|
|
1116
|
-
if (rawData.type === InteractionType.MessageComponent) {
|
|
1117
|
-
const customId = rawData.data?.custom_id;
|
|
1118
|
-
if (!customId) return;
|
|
1119
|
-
const componentInteraction = interaction;
|
|
1120
|
-
const component = client.componentHandler.resolve(customId, { componentType: rawData.data?.component_type });
|
|
1121
|
-
if (component) {
|
|
1122
|
-
await deferComponentInteractionIfNeeded(component, componentInteraction);
|
|
1123
|
-
await component.run(componentInteraction, component.customIdParser(customId).data);
|
|
1124
|
-
}
|
|
1125
|
-
return;
|
|
1126
|
-
}
|
|
1127
|
-
if (rawData.type === InteractionType.ModalSubmit) {
|
|
1128
|
-
const customId = rawData.data?.custom_id;
|
|
1129
|
-
if (!customId) return;
|
|
1130
|
-
const modal = client.modalHandler.resolve(customId);
|
|
1131
|
-
if (modal) await modal.run(interaction, modal.customIdParser(customId).data);
|
|
1132
|
-
}
|
|
1133
|
-
}
|
|
1134
1342
|
const INTERACTION_FAILURE_NOTICE = "Command failed. Check the Gateway logs for details.";
|
|
1135
1343
|
async function reportInteractionFailure(interaction) {
|
|
1136
1344
|
if (interaction.responseState !== "deferred" || interaction.hasSentFollowUp) return;
|
|
@@ -1142,7 +1350,7 @@ async function reportInteractionFailure(interaction) {
|
|
|
1142
1350
|
} catch {}
|
|
1143
1351
|
}
|
|
1144
1352
|
function resolveConditionalComponentOption(value, interaction) {
|
|
1145
|
-
return typeof value === "function" ? value(interaction) : value;
|
|
1353
|
+
return typeof value === "function" ? value(interaction) : value ?? false;
|
|
1146
1354
|
}
|
|
1147
1355
|
async function deferComponentInteractionIfNeeded(component, interaction) {
|
|
1148
1356
|
if (!resolveConditionalComponentOption(component.defer, interaction)) return;
|
|
@@ -1153,705 +1361,118 @@ async function deferComponentInteractionIfNeeded(component, interaction) {
|
|
|
1153
1361
|
await interaction.acknowledge();
|
|
1154
1362
|
}
|
|
1155
1363
|
//#endregion
|
|
1156
|
-
//#region extensions/discord/src/internal/
|
|
1157
|
-
const
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
function
|
|
1173
|
-
return
|
|
1364
|
+
//#region extensions/discord/src/internal/client.ts
|
|
1365
|
+
const DEFAULT_REST_CACHE_TTL_MS = 3e4;
|
|
1366
|
+
const DEFAULT_MAX_ENTRIES = 5e3;
|
|
1367
|
+
const DEFAULT_SWEEP_INTERVAL_MS = 3e4;
|
|
1368
|
+
const CACHE_KIND_BY_EVENT = /* @__PURE__ */ new Map([
|
|
1369
|
+
[GatewayDispatchEvents.ChannelUpdate, "channel"],
|
|
1370
|
+
[GatewayDispatchEvents.ChannelDelete, "channel"],
|
|
1371
|
+
[GatewayDispatchEvents.ThreadUpdate, "channel"],
|
|
1372
|
+
[GatewayDispatchEvents.ThreadDelete, "channel"],
|
|
1373
|
+
[GatewayDispatchEvents.GuildUpdate, "guild"],
|
|
1374
|
+
[GatewayDispatchEvents.GuildEmojisUpdate, "guild-emojis"],
|
|
1375
|
+
[GatewayDispatchEvents.GuildMemberAdd, "member"],
|
|
1376
|
+
[GatewayDispatchEvents.GuildMemberRemove, "member"],
|
|
1377
|
+
[GatewayDispatchEvents.GuildMemberUpdate, "member"]
|
|
1378
|
+
]);
|
|
1379
|
+
const DISCORD_APPLICATION_COMMAND_LIMIT_REACHED = 30032;
|
|
1380
|
+
function stableCommandKey(command) {
|
|
1381
|
+
return `${command.type ?? ApplicationCommandType.ChatInput}:${command.name}`;
|
|
1174
1382
|
}
|
|
1175
|
-
function
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
if (typeof data.body === "object") {
|
|
1179
|
-
const bodyObject = data.body;
|
|
1180
|
-
const topLevelFiles = Array.isArray(bodyObject.files) ? bodyObject.files : void 0;
|
|
1181
|
-
const nestedData = bodyObject.data && typeof bodyObject.data === "object" ? bodyObject.data : void 0;
|
|
1182
|
-
const nestedFiles = nestedData && Array.isArray(nestedData.files) ? nestedData.files : void 0;
|
|
1183
|
-
const files = topLevelFiles ?? nestedFiles;
|
|
1184
|
-
const filesContainer = topLevelFiles ? bodyObject : nestedFiles ? nestedData : void 0;
|
|
1185
|
-
if (files?.length && filesContainer) {
|
|
1186
|
-
if (data.multipartStyle === "form") {
|
|
1187
|
-
const formData = new FormData();
|
|
1188
|
-
for (const [key, value] of Object.entries(filesContainer)) {
|
|
1189
|
-
if (key === "files" || value === void 0 || value === null) continue;
|
|
1190
|
-
formData.append(key, typeof value === "string" ? value : JSON.stringify(value));
|
|
1191
|
-
}
|
|
1192
|
-
for (const file of files) {
|
|
1193
|
-
const item = file;
|
|
1194
|
-
const name = typeof item.name === "string" && item.name ? item.name : "file";
|
|
1195
|
-
formData.append(typeof item.fieldName === "string" && item.fieldName ? item.fieldName : "file", fileBlob(item), name);
|
|
1196
|
-
}
|
|
1197
|
-
return formData;
|
|
1198
|
-
}
|
|
1199
|
-
const payloadFilesContainer = { ...filesContainer };
|
|
1200
|
-
const payloadJson = topLevelFiles ? payloadFilesContainer : {
|
|
1201
|
-
...bodyObject,
|
|
1202
|
-
data: payloadFilesContainer
|
|
1203
|
-
};
|
|
1204
|
-
const formData = new FormData();
|
|
1205
|
-
const existingAttachments = Array.isArray(payloadFilesContainer.attachments) ? [...payloadFilesContainer.attachments] : [];
|
|
1206
|
-
const uploaded = files.map((file, index) => {
|
|
1207
|
-
const item = file;
|
|
1208
|
-
const name = typeof item.name === "string" && item.name ? item.name : `file-${index}`;
|
|
1209
|
-
const id = existingAttachments.length + index;
|
|
1210
|
-
formData.append(`files[${id}]`, fileBlob(item), name);
|
|
1211
|
-
const attachment = {
|
|
1212
|
-
id,
|
|
1213
|
-
filename: name
|
|
1214
|
-
};
|
|
1215
|
-
if (typeof item.description === "string") attachment.description = item.description;
|
|
1216
|
-
if (typeof item.duration_secs === "number") attachment.duration_secs = item.duration_secs;
|
|
1217
|
-
if (typeof item.waveform === "string") attachment.waveform = item.waveform;
|
|
1218
|
-
return attachment;
|
|
1219
|
-
});
|
|
1220
|
-
payloadFilesContainer.attachments = [...existingAttachments, ...uploaded];
|
|
1221
|
-
delete payloadFilesContainer.files;
|
|
1222
|
-
formData.append("payload_json", JSON.stringify(payloadJson));
|
|
1223
|
-
return formData;
|
|
1224
|
-
}
|
|
1225
|
-
}
|
|
1226
|
-
headers.set("Content-Type", "application/json");
|
|
1227
|
-
return JSON.stringify(data.body);
|
|
1383
|
+
function stableCommandSetHash(commands) {
|
|
1384
|
+
const stable = commands.toSorted((a, b) => stableCommandKey(a).localeCompare(stableCommandKey(b))).map((command) => stableComparableObject(command));
|
|
1385
|
+
return createHash("sha256").update(JSON.stringify(stable)).digest("hex");
|
|
1228
1386
|
}
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
const DISCORD_ERROR_BODY_MAX_DEPTH = 64;
|
|
1234
|
-
const DISCORD_ERROR_BODY_MAX_NODES = 1e4;
|
|
1235
|
-
const DISCORD_ERROR_BODY_MAX_DEPTH_MARKER = "[Discord error body redacted: maximum depth exceeded]";
|
|
1236
|
-
const DISCORD_ERROR_BODY_MAX_NODES_MARKER = "[Discord error body redacted: node limit exceeded]";
|
|
1237
|
-
const DISCORD_ERROR_BODY_PRIORITY_KEYS = /* @__PURE__ */ new Set([
|
|
1238
|
-
"message",
|
|
1239
|
-
"code",
|
|
1240
|
-
"retry_after",
|
|
1241
|
-
"global"
|
|
1387
|
+
const unorderedCommandArrayFields = /* @__PURE__ */ new Set([
|
|
1388
|
+
"channel_types",
|
|
1389
|
+
"contexts",
|
|
1390
|
+
"integration_types"
|
|
1242
1391
|
]);
|
|
1243
|
-
const
|
|
1244
|
-
"
|
|
1245
|
-
"
|
|
1246
|
-
"
|
|
1392
|
+
const optionComparisonOmittedFields = /* @__PURE__ */ new Set([
|
|
1393
|
+
"contexts",
|
|
1394
|
+
"default_member_permissions",
|
|
1395
|
+
"description_localized",
|
|
1396
|
+
"integration_types",
|
|
1397
|
+
"name_localized"
|
|
1247
1398
|
]);
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1399
|
+
const nullableLocalizationFields = /* @__PURE__ */ new Set(["description_localizations", "name_localizations"]);
|
|
1400
|
+
function comparableCommand(value) {
|
|
1401
|
+
if (!value || typeof value !== "object") return value;
|
|
1402
|
+
const omit = /* @__PURE__ */ new Set([
|
|
1403
|
+
"application_id",
|
|
1404
|
+
"description_localized",
|
|
1405
|
+
"dm_permission",
|
|
1406
|
+
"guild_id",
|
|
1407
|
+
"id",
|
|
1408
|
+
"name_localized",
|
|
1409
|
+
"nsfw",
|
|
1410
|
+
"version",
|
|
1411
|
+
"default_permission"
|
|
1412
|
+
]);
|
|
1413
|
+
return stableComparableObject(Object.fromEntries(Object.entries(value).filter(([key, entry]) => !omit.has(key) && entry !== void 0)));
|
|
1258
1414
|
}
|
|
1259
|
-
function
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
if (typeof body === "string") return redactSensitiveFieldValue(sensitiveAncestorKey ?? fieldKey, body);
|
|
1266
|
-
if (sensitiveAncestorKey && (typeof body === "number" || typeof body === "boolean" || typeof body === "bigint")) return redactSensitiveFieldValue(sensitiveAncestorKey, String(body));
|
|
1267
|
-
if (!body || typeof body !== "object") return body;
|
|
1268
|
-
if (depth >= DISCORD_ERROR_BODY_MAX_DEPTH) return DISCORD_ERROR_BODY_MAX_DEPTH_MARKER;
|
|
1269
|
-
if (state.seen.has(body)) return "[Circular]";
|
|
1270
|
-
state.seen.add(body);
|
|
1271
|
-
let redacted;
|
|
1272
|
-
if (Array.isArray(body)) {
|
|
1273
|
-
const items = [];
|
|
1274
|
-
for (const entry of body) {
|
|
1275
|
-
if (state.remainingNodes <= 0) {
|
|
1276
|
-
items.push(DISCORD_ERROR_BODY_MAX_NODES_MARKER);
|
|
1277
|
-
break;
|
|
1278
|
-
}
|
|
1279
|
-
items.push(redactDiscordErrorBody(entry, fieldKey, sensitiveAncestorKey, state, depth + 1));
|
|
1280
|
-
}
|
|
1281
|
-
redacted = items;
|
|
1282
|
-
} else {
|
|
1283
|
-
const usedKeys = /* @__PURE__ */ new Set();
|
|
1284
|
-
const collisionCounts = /* @__PURE__ */ new Map();
|
|
1285
|
-
const entries = [];
|
|
1286
|
-
const appendEntry = (nestedKey) => {
|
|
1287
|
-
if (state.remainingNodes <= 0) return false;
|
|
1288
|
-
const outputKey = reserveRedactedKey(redactSensitiveFieldValue(sensitiveAncestorKey ?? "", nestedKey), usedKeys, collisionCounts);
|
|
1289
|
-
const nestedSensitiveKey = redactSensitiveFieldValue(nestedKey, "") !== "" ? nestedKey : sensitiveAncestorKey;
|
|
1290
|
-
entries.push([outputKey, redactDiscordErrorBody(body[nestedKey], nestedKey, nestedSensitiveKey, state, depth + 1)]);
|
|
1291
|
-
return true;
|
|
1292
|
-
};
|
|
1293
|
-
let truncated = false;
|
|
1294
|
-
for (const priorityKey of DISCORD_ERROR_BODY_PRIORITY_KEYS) if (Object.hasOwn(body, priorityKey) && !appendEntry(priorityKey)) {
|
|
1295
|
-
truncated = true;
|
|
1296
|
-
break;
|
|
1297
|
-
}
|
|
1298
|
-
if (!truncated) for (const nestedKey in body) {
|
|
1299
|
-
if (!Object.hasOwn(body, nestedKey) || DISCORD_ERROR_BODY_PRIORITY_KEYS.has(nestedKey)) continue;
|
|
1300
|
-
if (!appendEntry(nestedKey)) {
|
|
1301
|
-
truncated = true;
|
|
1302
|
-
break;
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
if (truncated) {
|
|
1306
|
-
const markerKey = reserveRedactedKey(DISCORD_ERROR_BODY_MAX_NODES_MARKER, usedKeys, collisionCounts);
|
|
1307
|
-
entries.push([markerKey, DISCORD_ERROR_BODY_MAX_NODES_MARKER]);
|
|
1308
|
-
}
|
|
1309
|
-
redacted = Object.fromEntries(entries);
|
|
1415
|
+
function stableComparableObject(value, pathValue = []) {
|
|
1416
|
+
if (Array.isArray(value)) {
|
|
1417
|
+
const normalized = value.map((entry) => stableComparableObject(entry, pathValue));
|
|
1418
|
+
const key = pathValue.at(-1);
|
|
1419
|
+
if (key && unorderedCommandArrayFields.has(key) && normalized.every((entry) => typeof entry === "string" || typeof entry === "number" || typeof entry === "boolean")) return normalized.toSorted((left, right) => String(left).localeCompare(String(right)));
|
|
1420
|
+
return normalized;
|
|
1310
1421
|
}
|
|
1311
|
-
|
|
1312
|
-
return
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
}
|
|
1321
|
-
function readErrorDiscordCode(err) {
|
|
1322
|
-
return parseStrictNonNegativeInteger$1(asOptionalObjectRecord(err)?.discordCode);
|
|
1323
|
-
}
|
|
1324
|
-
function isUnknownDiscordMessageError(err) {
|
|
1325
|
-
return readErrorDiscordCode(err) === DISCORD_UNKNOWN_MESSAGE;
|
|
1326
|
-
}
|
|
1327
|
-
function isUnknownDiscordVoiceStateError(err) {
|
|
1328
|
-
return readErrorDiscordCode(err) === DISCORD_UNKNOWN_VOICE_STATE || /unknown voice state/i.test(formatErrorMessage(err));
|
|
1329
|
-
}
|
|
1330
|
-
function readRetryAfter(body, response, fallbackSeconds = 0) {
|
|
1331
|
-
return parseDiscordRetryAfterBodySeconds(asOptionalObjectRecord(body)?.retry_after) ?? parseRetryAfterHeaderSeconds(response.headers.get("Retry-After")) ?? fallbackSeconds;
|
|
1332
|
-
}
|
|
1333
|
-
function readDiscordRateLimitBucket(response) {
|
|
1334
|
-
const value = response.headers.get("X-RateLimit-Bucket")?.trim();
|
|
1335
|
-
return value ? redactIdentifier(value, { len: 32 }) : null;
|
|
1336
|
-
}
|
|
1337
|
-
function readDiscordRateLimitScope(response) {
|
|
1338
|
-
const value = response.headers.get("X-RateLimit-Scope");
|
|
1339
|
-
return value && DISCORD_RATE_LIMIT_SCOPES.has(value) ? value : null;
|
|
1422
|
+
const object = asOptionalObjectRecord(value);
|
|
1423
|
+
if (!object) return value;
|
|
1424
|
+
return Object.fromEntries(Object.entries(object).filter(([key, entry]) => {
|
|
1425
|
+
if (entry === void 0) return false;
|
|
1426
|
+
if (entry === null && nullableLocalizationFields.has(key)) return false;
|
|
1427
|
+
if (pathValue.includes("options") && optionComparisonOmittedFields.has(key)) return false;
|
|
1428
|
+
if ((key === "required" || key === "autocomplete") && entry === false) return false;
|
|
1429
|
+
return true;
|
|
1430
|
+
}).toSorted(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, typeof entry === "string" && (key === "description" || pathValue.at(-1) === "description_localizations") ? normalizeDescriptionForComparison(entry) : stableComparableObject(entry, [...pathValue, key])]));
|
|
1340
1431
|
}
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
super(response, body);
|
|
1358
|
-
this.name = "RateLimitError";
|
|
1359
|
-
this.retryAfter = readRetryAfter(body, response, 1);
|
|
1360
|
-
this.scope = body.global ? "global" : readDiscordRateLimitScope(response);
|
|
1361
|
-
this.bucket = readDiscordRateLimitBucket(response);
|
|
1362
|
-
}
|
|
1363
|
-
};
|
|
1364
|
-
//#endregion
|
|
1365
|
-
//#region extensions/discord/src/internal/rest-routes.ts
|
|
1366
|
-
const RATE_LIMIT_HEADER_NUMBER_RE = /^\d+(?:\.\d+)?$/;
|
|
1367
|
-
const DISCORD_ROUTE_IDENTIFIER_HASH_LENGTH = 32;
|
|
1368
|
-
function redactWebhookTokenInPath(path) {
|
|
1369
|
-
const hasLeadingSlash = path.startsWith("/");
|
|
1370
|
-
const segments = path.replace(/^\/+/, "").split("/");
|
|
1371
|
-
if (segments[0] !== "webhooks" || !segments[1] || !segments[2]) return path;
|
|
1372
|
-
segments[2] = redactIdentifier(segments[2], { len: DISCORD_ROUTE_IDENTIFIER_HASH_LENGTH });
|
|
1373
|
-
return `${hasLeadingSlash ? "/" : ""}${segments.join("/")}`;
|
|
1374
|
-
}
|
|
1375
|
-
function createRouteKey(method, path) {
|
|
1376
|
-
const pathname = path.split("?")[0] ?? path;
|
|
1377
|
-
return `${method.toUpperCase()} ${redactWebhookTokenInPath(pathname)}`;
|
|
1378
|
-
}
|
|
1379
|
-
function readTopLevelRouteKey(path) {
|
|
1380
|
-
const [pathname = path] = path.split("?");
|
|
1381
|
-
const [first, id, token] = pathname.replace(/^\/+/, "").split("/");
|
|
1382
|
-
if (!first || !id) return pathname;
|
|
1383
|
-
if (first === "channels" || first === "guilds" || first === "webhooks") return first === "webhooks" && token ? `${first}/${id}/${redactIdentifier(token, { len: DISCORD_ROUTE_IDENTIFIER_HASH_LENGTH })}` : `${first}/${id}`;
|
|
1384
|
-
return first;
|
|
1385
|
-
}
|
|
1386
|
-
function createBucketKey(bucket, path) {
|
|
1387
|
-
return `${bucket}:${readTopLevelRouteKey(path)}`;
|
|
1388
|
-
}
|
|
1389
|
-
function readHeaderNumber(headers, name) {
|
|
1390
|
-
const value = headers.get(name);
|
|
1391
|
-
if (!value) return;
|
|
1392
|
-
const trimmed = value.trim();
|
|
1393
|
-
if (!RATE_LIMIT_HEADER_NUMBER_RE.test(trimmed)) return;
|
|
1394
|
-
const parsed = Number(trimmed);
|
|
1395
|
-
return Number.isFinite(parsed) && Math.abs(parsed) <= Number.MAX_SAFE_INTEGER ? parsed : void 0;
|
|
1396
|
-
}
|
|
1397
|
-
function resolveRateLimitResetAt(delayMs) {
|
|
1398
|
-
const clampedDelayMs = Math.ceil(Math.max(0, delayMs));
|
|
1399
|
-
if (!Number.isSafeInteger(clampedDelayMs)) return;
|
|
1400
|
-
if (clampedDelayMs === 0) return asDateTimestampMs(Date.now());
|
|
1401
|
-
return resolveExpiresAtMsFromDurationMs(clampedDelayMs);
|
|
1402
|
-
}
|
|
1403
|
-
function readResetAt(response) {
|
|
1404
|
-
const resetAfter = readHeaderNumber(response.headers, "X-RateLimit-Reset-After");
|
|
1405
|
-
if (resetAfter !== void 0) return resolveRateLimitResetAt(resetAfter * 1e3);
|
|
1406
|
-
const reset = readHeaderNumber(response.headers, "X-RateLimit-Reset");
|
|
1407
|
-
return reset !== void 0 ? asDateTimestampMs(reset * 1e3) : void 0;
|
|
1408
|
-
}
|
|
1409
|
-
function appendQuery(path, query) {
|
|
1410
|
-
if (!query || Object.keys(query).length === 0) return path;
|
|
1411
|
-
const search = new URLSearchParams();
|
|
1412
|
-
for (const [key, value] of Object.entries(query)) search.set(key, String(value));
|
|
1413
|
-
return `${path}?${search.toString()}`;
|
|
1414
|
-
}
|
|
1415
|
-
//#endregion
|
|
1416
|
-
//#region extensions/discord/src/internal/rest-scheduler.ts
|
|
1417
|
-
const MAX_QUEUE_SIZE = 1e3;
|
|
1418
|
-
const MAX_CONCURRENT_WORKERS = 4;
|
|
1419
|
-
const MAX_RATE_LIMIT_RETRIES = 3;
|
|
1420
|
-
const BACKGROUND_STALE_AFTER_MS = 2e4;
|
|
1421
|
-
const requestPriorities = [
|
|
1422
|
-
"critical",
|
|
1423
|
-
"standard",
|
|
1424
|
-
"background"
|
|
1425
|
-
];
|
|
1426
|
-
const laneSchedule = [
|
|
1427
|
-
"critical",
|
|
1428
|
-
"critical",
|
|
1429
|
-
"critical",
|
|
1430
|
-
"critical",
|
|
1431
|
-
"critical",
|
|
1432
|
-
"critical",
|
|
1433
|
-
"standard",
|
|
1434
|
-
"standard",
|
|
1435
|
-
"standard",
|
|
1436
|
-
"background"
|
|
1437
|
-
];
|
|
1438
|
-
function countPending(bucket) {
|
|
1439
|
-
return requestPriorities.reduce((count, lane) => count + bucket.pending[lane].length, 0);
|
|
1440
|
-
}
|
|
1441
|
-
var RestScheduler = class {
|
|
1442
|
-
constructor(executor) {
|
|
1443
|
-
this.executor = executor;
|
|
1444
|
-
this.activeWorkers = 0;
|
|
1445
|
-
this.buckets = /* @__PURE__ */ new Map();
|
|
1446
|
-
this.globalRateLimitUntil = 0;
|
|
1447
|
-
this.laneCursor = 0;
|
|
1448
|
-
this.queuedByLane = {
|
|
1449
|
-
critical: 0,
|
|
1450
|
-
standard: 0,
|
|
1451
|
-
background: 0
|
|
1452
|
-
};
|
|
1453
|
-
this.queueGeneration = 0;
|
|
1454
|
-
this.queuedRequests = 0;
|
|
1455
|
-
this.routeBuckets = /* @__PURE__ */ new Map();
|
|
1456
|
-
}
|
|
1457
|
-
enqueue(params) {
|
|
1458
|
-
if (this.queuedRequests >= MAX_QUEUE_SIZE) throw new Error("Discord request queue is full");
|
|
1459
|
-
const routeKey = createRouteKey(params.method, params.path);
|
|
1460
|
-
const bucket = this.getBucket(this.routeBuckets.get(routeKey) ?? routeKey);
|
|
1461
|
-
return new Promise((resolve, reject) => {
|
|
1462
|
-
this.queuedRequests += 1;
|
|
1463
|
-
this.queuedByLane[params.priority] += 1;
|
|
1464
|
-
bucket.pending[params.priority].push({
|
|
1465
|
-
...params,
|
|
1466
|
-
enqueuedAt: Date.now(),
|
|
1467
|
-
generation: this.queueGeneration,
|
|
1468
|
-
routeKey,
|
|
1469
|
-
retryCount: 0,
|
|
1470
|
-
resolve,
|
|
1471
|
-
reject
|
|
1472
|
-
});
|
|
1473
|
-
this.drainQueues();
|
|
1474
|
-
});
|
|
1475
|
-
}
|
|
1476
|
-
clearQueue() {
|
|
1477
|
-
this.queueGeneration += 1;
|
|
1478
|
-
if (this.drainTimer) {
|
|
1479
|
-
clearTimeout(this.drainTimer);
|
|
1480
|
-
this.drainTimer = void 0;
|
|
1481
|
-
}
|
|
1482
|
-
this.rejectPending(/* @__PURE__ */ new Error("Discord request queue cleared"));
|
|
1483
|
-
}
|
|
1484
|
-
abortPending() {
|
|
1485
|
-
this.queueGeneration += 1;
|
|
1486
|
-
this.rejectPending(new DOMException("Aborted", "AbortError"));
|
|
1487
|
-
}
|
|
1488
|
-
get queueSize() {
|
|
1489
|
-
return this.queuedRequests;
|
|
1490
|
-
}
|
|
1491
|
-
getBucket(key) {
|
|
1492
|
-
const existing = this.buckets.get(key);
|
|
1493
|
-
if (existing) return existing;
|
|
1494
|
-
const bucket = {
|
|
1495
|
-
active: 0,
|
|
1496
|
-
pending: {
|
|
1497
|
-
critical: [],
|
|
1498
|
-
standard: [],
|
|
1499
|
-
background: []
|
|
1500
|
-
},
|
|
1501
|
-
resetAt: 0,
|
|
1502
|
-
routeKeys: /* @__PURE__ */ new Set([key])
|
|
1503
|
-
};
|
|
1504
|
-
this.buckets.set(key, bucket);
|
|
1505
|
-
return bucket;
|
|
1506
|
-
}
|
|
1507
|
-
hasBucketReference(key) {
|
|
1508
|
-
for (const bucketKey of this.routeBuckets.values()) if (bucketKey === key) return true;
|
|
1509
|
-
return false;
|
|
1510
|
-
}
|
|
1511
|
-
isBucketRateLimited(bucket, now = Date.now()) {
|
|
1512
|
-
return bucket.remaining === 0 && bucket.resetAt > now;
|
|
1513
|
-
}
|
|
1514
|
-
bindRouteToBucket(routeKey, bucketKey) {
|
|
1515
|
-
const target = this.getBucket(bucketKey);
|
|
1516
|
-
target.routeKeys.add(routeKey);
|
|
1517
|
-
this.routeBuckets.set(routeKey, bucketKey);
|
|
1518
|
-
const routeBucket = this.buckets.get(routeKey);
|
|
1519
|
-
if (routeBucket && routeBucket !== target) {
|
|
1520
|
-
for (const lane of requestPriorities) {
|
|
1521
|
-
target.pending[lane].push(...routeBucket.pending[lane]);
|
|
1522
|
-
routeBucket.pending[lane] = [];
|
|
1523
|
-
}
|
|
1524
|
-
if (routeBucket.active === 0) this.buckets.delete(routeKey);
|
|
1525
|
-
}
|
|
1526
|
-
return target;
|
|
1527
|
-
}
|
|
1528
|
-
recordResponse(routeKey, path, response, parsed) {
|
|
1529
|
-
const bucketHeader = readDiscordRateLimitBucket(response);
|
|
1530
|
-
const bucket = bucketHeader ? this.bindRouteToBucket(routeKey, createBucketKey(bucketHeader, path)) : this.getBucket(this.routeBuckets.get(routeKey) ?? routeKey);
|
|
1531
|
-
const limit = readHeaderNumber(response.headers, "X-RateLimit-Limit");
|
|
1532
|
-
if (limit !== void 0) bucket.limit = limit;
|
|
1533
|
-
const remaining = readHeaderNumber(response.headers, "X-RateLimit-Remaining");
|
|
1534
|
-
if (remaining !== void 0) bucket.remaining = remaining;
|
|
1535
|
-
const resetAt = readResetAt(response);
|
|
1536
|
-
if (resetAt !== void 0) bucket.resetAt = resetAt;
|
|
1537
|
-
if (response.status !== 429) return;
|
|
1538
|
-
const retryAt = resolveRateLimitResetAt(Math.max(0, readRetryAfter(parsed, response, 1) * 1e3));
|
|
1539
|
-
if (retryAt === void 0) return;
|
|
1540
|
-
if (response.headers.get("X-RateLimit-Global") === "true" || isGlobalRateLimit(parsed)) {
|
|
1541
|
-
this.globalRateLimitUntil = Math.max(this.globalRateLimitUntil, retryAt);
|
|
1542
|
-
return;
|
|
1543
|
-
}
|
|
1544
|
-
bucket.remaining = 0;
|
|
1545
|
-
bucket.resetAt = Math.max(bucket.resetAt, retryAt);
|
|
1546
|
-
}
|
|
1547
|
-
getBucketWaitMs(bucket, now) {
|
|
1548
|
-
if (bucket.remaining === 0 && bucket.resetAt > now) return bucket.resetAt - now;
|
|
1549
|
-
if (bucket.remaining === 0 && bucket.resetAt <= now) bucket.remaining = bucket.limit;
|
|
1550
|
-
return 0;
|
|
1551
|
-
}
|
|
1552
|
-
scheduleDrain(delayMs = 0) {
|
|
1553
|
-
if (this.drainTimer) return;
|
|
1554
|
-
this.drainTimer = setTimeout(() => {
|
|
1555
|
-
this.drainTimer = void 0;
|
|
1556
|
-
this.drainQueues();
|
|
1557
|
-
}, resolveTimerTimeoutMs(delayMs, 0, 0));
|
|
1558
|
-
this.drainTimer.unref?.();
|
|
1559
|
-
}
|
|
1560
|
-
drainQueues() {
|
|
1561
|
-
while (this.activeWorkers < MAX_CONCURRENT_WORKERS) {
|
|
1562
|
-
const next = this.takeNextQueuedRequest();
|
|
1563
|
-
if (!next.queued) {
|
|
1564
|
-
if (next.waitMs !== void 0 && Number.isFinite(next.waitMs)) this.scheduleDrain(next.waitMs);
|
|
1565
|
-
break;
|
|
1566
|
-
}
|
|
1567
|
-
const { bucket, queued } = next;
|
|
1568
|
-
if (bucket.remaining !== void 0 && bucket.remaining > 0) bucket.remaining -= 1;
|
|
1569
|
-
bucket.active += 1;
|
|
1570
|
-
this.activeWorkers += 1;
|
|
1571
|
-
this.runQueuedRequest(queued, bucket);
|
|
1572
|
-
}
|
|
1573
|
-
}
|
|
1574
|
-
takeNextQueuedRequest() {
|
|
1575
|
-
const now = Date.now();
|
|
1576
|
-
if (this.globalRateLimitUntil > now) return { waitMs: this.globalRateLimitUntil - now };
|
|
1577
|
-
this.pruneIdleBuckets(now);
|
|
1578
|
-
let nextDelayMs;
|
|
1579
|
-
const buckets = Array.from(this.buckets.values()).filter((bucket) => countPending(bucket) > 0);
|
|
1580
|
-
if (buckets.length === 0) return {};
|
|
1581
|
-
for (let laneOffset = 0; laneOffset < laneSchedule.length; laneOffset += 1) {
|
|
1582
|
-
const lane = laneSchedule[(this.laneCursor + laneOffset) % laneSchedule.length];
|
|
1583
|
-
if (!lane || this.queuedByLane[lane] <= 0) continue;
|
|
1584
|
-
for (const bucket of buckets) {
|
|
1585
|
-
const queue = bucket.pending[lane];
|
|
1586
|
-
this.dropStaleHeadRequests(queue, lane, now);
|
|
1587
|
-
if (queue.length === 0 || bucket.active > 0) continue;
|
|
1588
|
-
const waitMs = this.getBucketWaitMs(bucket, now);
|
|
1589
|
-
if (waitMs > 0) {
|
|
1590
|
-
nextDelayMs = Math.min(nextDelayMs ?? waitMs, waitMs);
|
|
1591
|
-
continue;
|
|
1592
|
-
}
|
|
1593
|
-
const queued = queue.shift();
|
|
1594
|
-
if (!queued) continue;
|
|
1595
|
-
this.queuedByLane[lane] = Math.max(0, this.queuedByLane[lane] - 1);
|
|
1596
|
-
this.laneCursor = (this.laneCursor + laneOffset + 1) % laneSchedule.length;
|
|
1597
|
-
return {
|
|
1598
|
-
bucket,
|
|
1599
|
-
queued
|
|
1600
|
-
};
|
|
1601
|
-
}
|
|
1602
|
-
}
|
|
1603
|
-
return { waitMs: nextDelayMs };
|
|
1604
|
-
}
|
|
1605
|
-
dropStaleHeadRequests(queue, lane, now) {
|
|
1606
|
-
if (lane !== "background") return;
|
|
1607
|
-
while (queue.length > 0 && now - (queue[0]?.enqueuedAt ?? now) > BACKGROUND_STALE_AFTER_MS) {
|
|
1608
|
-
const stale = queue.shift();
|
|
1609
|
-
if (!stale) continue;
|
|
1610
|
-
this.queuedRequests = Math.max(0, this.queuedRequests - 1);
|
|
1611
|
-
this.queuedByLane[lane] = Math.max(0, this.queuedByLane[lane] - 1);
|
|
1612
|
-
stale.reject(/* @__PURE__ */ new Error(`Dropped stale ${lane} request after ${now - stale.enqueuedAt}ms`));
|
|
1613
|
-
}
|
|
1614
|
-
}
|
|
1615
|
-
pruneIdleBuckets(now = Date.now()) {
|
|
1616
|
-
for (const [key, bucket] of this.buckets) {
|
|
1617
|
-
if (bucket.active !== 0 || countPending(bucket) > 0) continue;
|
|
1618
|
-
if (this.isBucketRateLimited(bucket, now)) continue;
|
|
1619
|
-
for (const routeKey of bucket.routeKeys) if (this.routeBuckets.get(routeKey) === key) {
|
|
1620
|
-
this.routeBuckets.delete(routeKey);
|
|
1621
|
-
bucket.routeKeys.delete(routeKey);
|
|
1622
|
-
}
|
|
1623
|
-
if (this.routeBuckets.get(key) !== key && !this.hasBucketReference(key)) this.buckets.delete(key);
|
|
1624
|
-
}
|
|
1625
|
-
}
|
|
1626
|
-
async runQueuedRequest(queued, bucket) {
|
|
1627
|
-
let requeued = false;
|
|
1628
|
-
try {
|
|
1629
|
-
queued.resolve(await this.executor(queued));
|
|
1630
|
-
} catch (error) {
|
|
1631
|
-
if (error instanceof RateLimitError && this.requeueRateLimitedRequest(queued)) {
|
|
1632
|
-
requeued = true;
|
|
1633
|
-
return;
|
|
1634
|
-
}
|
|
1635
|
-
queued.reject(error);
|
|
1636
|
-
} finally {
|
|
1637
|
-
bucket.active = Math.max(0, bucket.active - 1);
|
|
1638
|
-
this.activeWorkers = Math.max(0, this.activeWorkers - 1);
|
|
1639
|
-
if (!requeued) this.queuedRequests = Math.max(0, this.queuedRequests - 1);
|
|
1640
|
-
if (bucket.active === 0 && countPending(bucket) === 0) {
|
|
1641
|
-
for (const routeKey of bucket.routeKeys) if (this.routeBuckets.get(routeKey) === routeKey) this.routeBuckets.delete(routeKey);
|
|
1642
|
-
}
|
|
1643
|
-
this.drainQueues();
|
|
1644
|
-
}
|
|
1645
|
-
}
|
|
1646
|
-
requeueRateLimitedRequest(queued) {
|
|
1647
|
-
if (queued.generation !== this.queueGeneration || queued.retryCount >= MAX_RATE_LIMIT_RETRIES) return false;
|
|
1648
|
-
const bucketKey = this.routeBuckets.get(queued.routeKey) ?? queued.routeKey;
|
|
1649
|
-
this.getBucket(bucketKey).pending[queued.priority].push({
|
|
1650
|
-
...queued,
|
|
1651
|
-
enqueuedAt: Date.now(),
|
|
1652
|
-
retryCount: queued.retryCount + 1
|
|
1653
|
-
});
|
|
1654
|
-
this.queuedByLane[queued.priority] += 1;
|
|
1655
|
-
return true;
|
|
1656
|
-
}
|
|
1657
|
-
rejectPending(error) {
|
|
1658
|
-
for (const bucket of this.buckets.values()) for (const lane of requestPriorities) for (const queued of bucket.pending[lane].splice(0)) {
|
|
1659
|
-
queued.reject(error);
|
|
1660
|
-
this.queuedRequests = Math.max(0, this.queuedRequests - 1);
|
|
1661
|
-
this.queuedByLane[lane] = Math.max(0, this.queuedByLane[lane] - 1);
|
|
1662
|
-
}
|
|
1663
|
-
}
|
|
1664
|
-
};
|
|
1665
|
-
function isGlobalRateLimit(parsed) {
|
|
1666
|
-
return parsed && typeof parsed === "object" && "global" in parsed ? Boolean(parsed.global) : false;
|
|
1667
|
-
}
|
|
1668
|
-
//#endregion
|
|
1669
|
-
//#region extensions/discord/src/internal/rest.ts
|
|
1670
|
-
const defaultOptions = {
|
|
1671
|
-
baseUrl: "https://discord.com/api",
|
|
1672
|
-
timeout: 15e3,
|
|
1673
|
-
queueRequests: true
|
|
1674
|
-
};
|
|
1675
|
-
const DISCORD_REST_RESPONSE_BODY_MAX_BYTES = 8388608;
|
|
1676
|
-
const GZIP_MAGIC = [31, 139];
|
|
1677
|
-
function createResponseBodyOverflowError(size) {
|
|
1678
|
-
return /* @__PURE__ */ new Error(`Discord REST response body exceeds ${DISCORD_REST_RESPONSE_BODY_MAX_BYTES} bytes (received ${size})`);
|
|
1679
|
-
}
|
|
1680
|
-
async function readResponseBodyText(response, idleTimeoutMs) {
|
|
1681
|
-
const buffer = await readResponseWithLimit(response, DISCORD_REST_RESPONSE_BODY_MAX_BYTES, {
|
|
1682
|
-
chunkTimeoutMs: idleTimeoutMs,
|
|
1683
|
-
onOverflow: ({ size }) => createResponseBodyOverflowError(size),
|
|
1684
|
-
onIdleTimeout: ({ chunkTimeoutMs }) => /* @__PURE__ */ new Error(`Discord REST response stalled: no data received for ${chunkTimeoutMs}ms`)
|
|
1685
|
-
});
|
|
1686
|
-
if (!buffer.byteLength) return "";
|
|
1687
|
-
if (buffer[0] === GZIP_MAGIC[0] && buffer[1] === GZIP_MAGIC[1]) try {
|
|
1688
|
-
return gunzipSync(buffer, { maxOutputLength: DISCORD_REST_RESPONSE_BODY_MAX_BYTES }).toString("utf8");
|
|
1689
|
-
} catch (err) {
|
|
1690
|
-
if (err instanceof RangeError && "code" in err && err.code === "ERR_BUFFER_TOO_LARGE") throw createResponseBodyOverflowError("decompressed output");
|
|
1691
|
-
throw err;
|
|
1692
|
-
}
|
|
1693
|
-
return buffer.toString("utf8");
|
|
1694
|
-
}
|
|
1695
|
-
function coerceResponseBody(raw) {
|
|
1696
|
-
if (!raw) return;
|
|
1697
|
-
try {
|
|
1698
|
-
return JSON.parse(raw);
|
|
1699
|
-
} catch {
|
|
1700
|
-
return raw;
|
|
1701
|
-
}
|
|
1702
|
-
}
|
|
1703
|
-
var RequestClient = class {
|
|
1704
|
-
constructor(token, options) {
|
|
1705
|
-
this.requestControllers = /* @__PURE__ */ new Set();
|
|
1706
|
-
const endpoint = getDiscordEndpointRuntime();
|
|
1707
|
-
const resolvedOptions = endpoint ? {
|
|
1708
|
-
...options,
|
|
1709
|
-
apiBaseUrl: endpoint.descriptor.restApiBaseUrl,
|
|
1710
|
-
fetch: endpoint.fetch
|
|
1711
|
-
} : options;
|
|
1712
|
-
this.token = token.replace(/^Bot\s+/i, "");
|
|
1713
|
-
this.customFetch = resolvedOptions?.fetch;
|
|
1714
|
-
this.guardedEndpoint = endpoint !== void 0;
|
|
1715
|
-
this.options = normalizeRequestClientOptions(resolvedOptions);
|
|
1716
|
-
this.scheduler = new RestScheduler(async (request) => await this.executeRequest(request.method, request.path, {
|
|
1717
|
-
data: request.data?.data,
|
|
1718
|
-
query: request.query
|
|
1719
|
-
}, request.routeKey, request.data?.assertCurrent, request.data?.effect));
|
|
1720
|
-
}
|
|
1721
|
-
async get(path, query) {
|
|
1722
|
-
return await this.request("GET", path, { query });
|
|
1723
|
-
}
|
|
1724
|
-
async post(path, data, query) {
|
|
1725
|
-
return await this.request("POST", path, {
|
|
1726
|
-
data,
|
|
1727
|
-
query
|
|
1728
|
-
});
|
|
1729
|
-
}
|
|
1730
|
-
async patch(path, data, query) {
|
|
1731
|
-
return await this.request("PATCH", path, {
|
|
1732
|
-
data,
|
|
1733
|
-
query
|
|
1734
|
-
});
|
|
1735
|
-
}
|
|
1736
|
-
async put(path, data, query) {
|
|
1737
|
-
return await this.request("PUT", path, {
|
|
1738
|
-
data,
|
|
1739
|
-
query
|
|
1740
|
-
});
|
|
1741
|
-
}
|
|
1742
|
-
async delete(path, data, query) {
|
|
1743
|
-
return await this.request("DELETE", path, {
|
|
1744
|
-
data,
|
|
1745
|
-
query
|
|
1746
|
-
});
|
|
1747
|
-
}
|
|
1748
|
-
async request(method, path, params) {
|
|
1749
|
-
const routeKey = createRouteKey(method, path);
|
|
1750
|
-
const assertActionAuthority = captureDiscordRequestAuthority();
|
|
1751
|
-
const assertReadAuthority = captureChannelReadAuthority();
|
|
1752
|
-
const effect = captureEffectAuthority();
|
|
1753
|
-
const assertCurrent = assertActionAuthority ? () => {
|
|
1754
|
-
assertActionAuthority();
|
|
1755
|
-
assertReadAuthority?.();
|
|
1756
|
-
} : assertReadAuthority;
|
|
1757
|
-
assertCurrent?.();
|
|
1758
|
-
if (!this.options.queueRequests) return await this.executeRequest(method, path, params, routeKey, assertCurrent, effect);
|
|
1759
|
-
return await this.scheduler.enqueue({
|
|
1760
|
-
method,
|
|
1761
|
-
path,
|
|
1762
|
-
priority: getRequestPriority(method, path),
|
|
1763
|
-
query: params.query,
|
|
1764
|
-
data: {
|
|
1765
|
-
data: params.data,
|
|
1766
|
-
assertCurrent,
|
|
1767
|
-
effect
|
|
1768
|
-
}
|
|
1769
|
-
});
|
|
1770
|
-
}
|
|
1771
|
-
async executeRequest(method, path, params, routeKey = createRouteKey(method, path), assertCurrent, effect = captureEffectAuthority()) {
|
|
1772
|
-
const url = `${this.options.apiBaseUrl}${appendQuery(path, params.query)}`;
|
|
1773
|
-
const headers = new Headers({ "User-Agent": "OpenClaw Discord" });
|
|
1774
|
-
if (this.token !== "webhook") headers.set("Authorization", `Bot ${this.token}`);
|
|
1775
|
-
const body = serializeRequestBody(params.data, headers);
|
|
1776
|
-
const controller = new AbortController();
|
|
1777
|
-
const timeout = setTimeout(() => controller.abort(), this.options.timeout);
|
|
1778
|
-
timeout.unref?.();
|
|
1779
|
-
const signal = this.options.signal ? AbortSignal.any([this.options.signal, controller.signal]) : controller.signal;
|
|
1780
|
-
this.requestControllers.add(controller);
|
|
1781
|
-
try {
|
|
1782
|
-
assertCurrent?.();
|
|
1783
|
-
const init = {
|
|
1784
|
-
method,
|
|
1785
|
-
headers,
|
|
1786
|
-
body,
|
|
1787
|
-
signal
|
|
1788
|
-
};
|
|
1789
|
-
const request = () => {
|
|
1790
|
-
assertCurrent?.();
|
|
1791
|
-
return this.customFetch && assertCurrent ? this.customFetch(url, init, assertCurrent) : (this.customFetch ?? fetch)(url, init);
|
|
1792
|
-
};
|
|
1793
|
-
const response = this.guardedEndpoint ? await effect.run(request) : await effect.initiate(request);
|
|
1794
|
-
const parsed = coerceResponseBody(await readResponseBodyText(response, this.options.timeout).catch((error) => {
|
|
1795
|
-
if (response.ok) throw error;
|
|
1796
|
-
return "";
|
|
1797
|
-
}));
|
|
1798
|
-
this.scheduler.recordResponse(routeKey, path, response, parsed);
|
|
1799
|
-
if (response.status === 204) return;
|
|
1800
|
-
if (response.status === 429) {
|
|
1801
|
-
const rateLimitBody = isDiscordRateLimitBody(parsed) ? parsed : void 0;
|
|
1802
|
-
throw new RateLimitError(response, {
|
|
1803
|
-
message: readDiscordMessage(rateLimitBody, "Rate limited"),
|
|
1804
|
-
retry_after: readRetryAfter(rateLimitBody, response, 1),
|
|
1805
|
-
code: readDiscordCode(rateLimitBody),
|
|
1806
|
-
global: Boolean(rateLimitBody?.global)
|
|
1807
|
-
});
|
|
1808
|
-
}
|
|
1809
|
-
if (!response.ok) throw new DiscordError(response, parsed);
|
|
1810
|
-
return parsed;
|
|
1811
|
-
} catch (error) {
|
|
1812
|
-
if (error instanceof Error) throw error;
|
|
1813
|
-
throw new Error(`Discord request failed: ${inspect(error)}`, { cause: error });
|
|
1814
|
-
} finally {
|
|
1815
|
-
clearTimeout(timeout);
|
|
1816
|
-
this.requestControllers.delete(controller);
|
|
1817
|
-
}
|
|
1818
|
-
}
|
|
1819
|
-
clearQueue() {
|
|
1820
|
-
this.scheduler.clearQueue();
|
|
1432
|
+
/**
|
|
1433
|
+
* Normalize descriptions to match Discord's server-side storage semantics.
|
|
1434
|
+
* Discord collapses whitespace and removes whitespace between CJK characters.
|
|
1435
|
+
*/
|
|
1436
|
+
function normalizeDescriptionForComparison(description) {
|
|
1437
|
+
const collapsed = description.replace(/\s+/g, " ");
|
|
1438
|
+
const cjkBoundaryWhitespace = /([\u3000-\u303F\u4E00-\u9FFF\uFF00-\uFFEF])\s+([\u3000-\u303F\u4E00-\u9FFF\uFF00-\uFFEF])/g;
|
|
1439
|
+
return collapsed.replace(cjkBoundaryWhitespace, "$1$2").replace(cjkBoundaryWhitespace, "$1$2").trim();
|
|
1440
|
+
}
|
|
1441
|
+
function commandsEqual(a, b) {
|
|
1442
|
+
return JSON.stringify(comparableCommand(a)) === JSON.stringify(comparableCommand(b));
|
|
1443
|
+
}
|
|
1444
|
+
var ComponentRegistry = class {
|
|
1445
|
+
constructor() {
|
|
1446
|
+
this.entries = /* @__PURE__ */ new Map();
|
|
1447
|
+
this.wildcardEntries = [];
|
|
1821
1448
|
}
|
|
1822
|
-
|
|
1823
|
-
|
|
1449
|
+
register(entry) {
|
|
1450
|
+
const key = (entry.customIdParser ?? parseCustomId)(entry.customId).key;
|
|
1451
|
+
const entries = key === "*" ? this.wildcardEntries : this.entries.get(key) ?? [];
|
|
1452
|
+
if (!entries.includes(entry)) {
|
|
1453
|
+
entries.push(entry);
|
|
1454
|
+
if (key !== "*") this.entries.set(key, entries);
|
|
1455
|
+
}
|
|
1824
1456
|
}
|
|
1825
|
-
|
|
1826
|
-
this.
|
|
1827
|
-
|
|
1828
|
-
|
|
1457
|
+
resolve(customId, options) {
|
|
1458
|
+
for (const entries of this.entries.values()) {
|
|
1459
|
+
const match = entries.find((entry) => {
|
|
1460
|
+
if (options?.componentType !== void 0 && entry.type !== options.componentType) return false;
|
|
1461
|
+
const parser = entry.customIdParser ?? parseCustomId;
|
|
1462
|
+
return parser(entry.customId).key === parser(customId).key;
|
|
1463
|
+
});
|
|
1464
|
+
if (match) return match;
|
|
1465
|
+
}
|
|
1466
|
+
return this.wildcardEntries.find((entry) => options?.componentType === void 0 || entry.type === options.componentType);
|
|
1829
1467
|
}
|
|
1830
1468
|
};
|
|
1831
|
-
function normalizeRequestClientOptions(options) {
|
|
1832
|
-
const merged = {
|
|
1833
|
-
...defaultOptions,
|
|
1834
|
-
...options
|
|
1835
|
-
};
|
|
1836
|
-
return {
|
|
1837
|
-
...merged,
|
|
1838
|
-
apiBaseUrl: options?.apiBaseUrl ?? `${options?.baseUrl ?? defaultOptions.baseUrl}/v10`,
|
|
1839
|
-
timeout: clampTimerTimeoutMs(merged.timeout, 1) ?? resolveTimerTimeoutMs(defaultOptions.timeout, 1)
|
|
1840
|
-
};
|
|
1841
|
-
}
|
|
1842
|
-
function getRequestPriority(method, path) {
|
|
1843
|
-
const normalizedMethod = method.toUpperCase();
|
|
1844
|
-
const normalizedPath = path.toLowerCase();
|
|
1845
|
-
if (/^\/interactions\/\d+\/[^/]+\/callback$/.test(normalizedPath)) return "critical";
|
|
1846
|
-
return normalizedMethod === "GET" ? "background" : "standard";
|
|
1847
|
-
}
|
|
1848
|
-
//#endregion
|
|
1849
|
-
//#region extensions/discord/src/internal/client.ts
|
|
1850
|
-
var Plugin = class {};
|
|
1851
1469
|
var Client = class {
|
|
1852
1470
|
constructor(options, handlers, plugins = []) {
|
|
1853
1471
|
this.plugins = [];
|
|
1854
1472
|
this.componentHandler = new ComponentRegistry();
|
|
1473
|
+
this.commandDeployHashLoaded = false;
|
|
1474
|
+
this.entityEntries = /* @__PURE__ */ new Map();
|
|
1475
|
+
this.lastEntitySweepAt = 0;
|
|
1855
1476
|
this.modalHandler = new ComponentRegistry();
|
|
1856
1477
|
if (!options.clientId) throw new Error("Missing Discord application ID");
|
|
1857
1478
|
if (!options.token) throw new Error("Missing Discord bot token");
|
|
@@ -1859,17 +1480,11 @@ var Client = class {
|
|
|
1859
1480
|
this.commands = handlers.commands ?? [];
|
|
1860
1481
|
this.listeners = handlers.listeners ?? [];
|
|
1861
1482
|
this.rest = new RequestClient(options.token, options.requestOptions);
|
|
1862
|
-
|
|
1863
|
-
this.
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
}
|
|
1867
|
-
this.commandDeployer = new DiscordCommandDeployer({
|
|
1868
|
-
clientId: this.options.clientId,
|
|
1869
|
-
commands: this.commands,
|
|
1870
|
-
hashStore: this.options.commandDeployHashStore,
|
|
1871
|
-
rest: () => this.rest
|
|
1872
|
-
});
|
|
1483
|
+
const eventQueue = this.options.eventQueue;
|
|
1484
|
+
this.eventQueue = eventQueue ? {
|
|
1485
|
+
permits: createPermitPool(eventQueue.maxConcurrency ?? 50),
|
|
1486
|
+
maxQueueSize: eventQueue.maxQueueSize ?? 1e4
|
|
1487
|
+
} : void 0;
|
|
1873
1488
|
for (const component of handlers.components ?? []) this.componentHandler.register(component);
|
|
1874
1489
|
for (const modal of handlers.modals ?? []) this.modalHandler.register(modal);
|
|
1875
1490
|
for (const plugin of plugins) {
|
|
@@ -1880,274 +1495,159 @@ var Client = class {
|
|
|
1880
1495
|
getPlugin(id) {
|
|
1881
1496
|
return this.plugins.find((plugin) => plugin.id === id);
|
|
1882
1497
|
}
|
|
1883
|
-
getRuntimeMetrics() {
|
|
1884
|
-
return { eventQueue: this.eventQueue?.getMetrics() };
|
|
1885
|
-
}
|
|
1886
1498
|
async fetchUser(id) {
|
|
1887
|
-
return await this.
|
|
1499
|
+
return await this.fetchCachedEntity(`user:${id}`, async () => {
|
|
1500
|
+
const raw = await getUser(this.rest, id);
|
|
1501
|
+
return new User(this, raw);
|
|
1502
|
+
});
|
|
1888
1503
|
}
|
|
1889
1504
|
async fetchChannel(id) {
|
|
1890
|
-
return await this.
|
|
1505
|
+
return await this.fetchCachedEntity(`channel:${id}`, async () => {
|
|
1506
|
+
const raw = await getChannel(this.rest, id);
|
|
1507
|
+
return channelFactory(this, raw);
|
|
1508
|
+
});
|
|
1891
1509
|
}
|
|
1892
1510
|
async fetchGuild(id) {
|
|
1893
|
-
return await this.
|
|
1511
|
+
return await this.fetchCachedEntity(`guild:${id}`, async () => {
|
|
1512
|
+
const raw = await getGuild(this.rest, id);
|
|
1513
|
+
return new Guild(this, raw);
|
|
1514
|
+
});
|
|
1894
1515
|
}
|
|
1895
1516
|
async fetchMember(guildId, userId) {
|
|
1896
|
-
return await this.
|
|
1517
|
+
return await this.fetchCachedEntity(`member:${guildId}:${userId}`, async () => {
|
|
1518
|
+
const raw = await getGuildMember(this.rest, guildId, userId);
|
|
1519
|
+
return new GuildMember(this, raw);
|
|
1520
|
+
});
|
|
1897
1521
|
}
|
|
1898
1522
|
async fetchGuildEmojis(guildId, fetcher) {
|
|
1899
|
-
return await this.
|
|
1523
|
+
return await this.fetchCachedEntity(`guild-emojis:${guildId}`, fetcher);
|
|
1524
|
+
}
|
|
1525
|
+
invalidateEntityCacheForGatewayEvent(type, data) {
|
|
1526
|
+
const kind = CACHE_KIND_BY_EVENT.get(type);
|
|
1527
|
+
if (!kind) return;
|
|
1528
|
+
const raw = asRecord(data);
|
|
1529
|
+
if (kind === "member") {
|
|
1530
|
+
const guildId = raw.guild_id;
|
|
1531
|
+
const user = asRecord(raw.user);
|
|
1532
|
+
if (typeof guildId === "string" && typeof user.id === "string") {
|
|
1533
|
+
this.entityEntries.delete(`member:${guildId}:${user.id}`);
|
|
1534
|
+
this.entityEntries.delete(`user:${user.id}`);
|
|
1535
|
+
}
|
|
1536
|
+
} else {
|
|
1537
|
+
const id = kind === "guild-emojis" ? raw.guild_id : raw.id;
|
|
1538
|
+
if (typeof id === "string") this.entityEntries.delete(`${kind}:${id}`);
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
async fetchCachedEntity(key, fetcher) {
|
|
1542
|
+
const now = Date.now();
|
|
1543
|
+
const cached = this.entityEntries.get(key);
|
|
1544
|
+
if (cached && cached.expiresAt > now) return cached.value;
|
|
1545
|
+
if (cached) this.entityEntries.delete(key);
|
|
1546
|
+
const value = await fetcher();
|
|
1547
|
+
this.sweepExpiredEntities(now);
|
|
1548
|
+
this.entityEntries.set(key, {
|
|
1549
|
+
expiresAt: now + DEFAULT_REST_CACHE_TTL_MS,
|
|
1550
|
+
value
|
|
1551
|
+
});
|
|
1552
|
+
if (this.entityEntries.size > DEFAULT_MAX_ENTRIES) this.entityEntries.delete(this.entityEntries.keys().next().value);
|
|
1553
|
+
return value;
|
|
1554
|
+
}
|
|
1555
|
+
sweepExpiredEntities(now) {
|
|
1556
|
+
if (now - this.lastEntitySweepAt < DEFAULT_SWEEP_INTERVAL_MS) return;
|
|
1557
|
+
this.lastEntitySweepAt = now;
|
|
1558
|
+
for (const [key, entry] of this.entityEntries) if (entry.expiresAt <= now) this.entityEntries.delete(key);
|
|
1900
1559
|
}
|
|
1901
1560
|
async deployCommands() {
|
|
1902
|
-
|
|
1561
|
+
const commands = this.commands.filter((command) => command.name !== "*").map((command) => command.serialize());
|
|
1562
|
+
const hash = stableCommandSetHash(commands);
|
|
1563
|
+
await this.loadPersistedHash();
|
|
1564
|
+
if (this.commandDeployHash === hash) return;
|
|
1565
|
+
await this.reconcileGlobalCommands(commands);
|
|
1566
|
+
this.commandDeployHash = hash;
|
|
1567
|
+
try {
|
|
1568
|
+
await this.options.commandDeployHashStore?.register(this.commandDeployCacheKey, hash);
|
|
1569
|
+
} catch {}
|
|
1570
|
+
}
|
|
1571
|
+
get commandDeployCacheKey() {
|
|
1572
|
+
return `app:${this.options.clientId}:global:reconcile`;
|
|
1573
|
+
}
|
|
1574
|
+
async reconcileGlobalCommands(desired) {
|
|
1575
|
+
const existing = await this.requestCommandDeploy("get", Routes.applicationCommands(this.options.clientId));
|
|
1576
|
+
const existingByKey = new Map(existing.map((command) => [stableCommandKey(command), command]));
|
|
1577
|
+
const desiredCommands = desired.map((command) => ({
|
|
1578
|
+
command,
|
|
1579
|
+
key: stableCommandKey(command)
|
|
1580
|
+
}));
|
|
1581
|
+
const desiredKeys = new Set(desiredCommands.map(({ key }) => key));
|
|
1582
|
+
for (const { command, key } of desiredCommands) {
|
|
1583
|
+
const current = existingByKey.get(key);
|
|
1584
|
+
if (current && !commandsEqual(current, command)) await this.requestCommandDeploy("patch", Routes.applicationCommand(this.options.clientId, current.id), command);
|
|
1585
|
+
}
|
|
1586
|
+
for (const { command, key } of desiredCommands) {
|
|
1587
|
+
if (existingByKey.has(key)) continue;
|
|
1588
|
+
try {
|
|
1589
|
+
await this.requestCommandDeploy("post", Routes.applicationCommands(this.options.clientId), command);
|
|
1590
|
+
} catch (error) {
|
|
1591
|
+
if (!(error !== null && typeof error === "object" && "discordCode" in error && error.discordCode === DISCORD_APPLICATION_COMMAND_LIMIT_REACHED)) throw error;
|
|
1592
|
+
await this.requestCommandDeploy("put", Routes.applicationCommands(this.options.clientId), desired);
|
|
1593
|
+
return;
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
for (const command of existing) if (!desiredKeys.has(stableCommandKey(command))) await this.requestCommandDeploy("delete", Routes.applicationCommand(this.options.clientId, command.id));
|
|
1597
|
+
}
|
|
1598
|
+
async loadPersistedHash() {
|
|
1599
|
+
if (this.commandDeployHashLoaded) return;
|
|
1600
|
+
this.commandDeployHashLoaded = true;
|
|
1601
|
+
try {
|
|
1602
|
+
this.commandDeployHash = await this.options.commandDeployHashStore?.lookup(this.commandDeployCacheKey);
|
|
1603
|
+
} catch {}
|
|
1604
|
+
}
|
|
1605
|
+
async requestCommandDeploy(method, path, body) {
|
|
1606
|
+
const rest = this.rest;
|
|
1607
|
+
const timeoutMs = rest.options.timeout;
|
|
1608
|
+
const startedAt = Date.now();
|
|
1609
|
+
try {
|
|
1610
|
+
return method === "get" || body === void 0 ? await rest[method](path) : await rest[method](path, { body });
|
|
1611
|
+
} catch (error) {
|
|
1612
|
+
if (error && typeof error === "object") {
|
|
1613
|
+
if (body !== void 0 && (!("deployRequestBody" in error) || error.deployRequestBody === void 0)) Object.assign(error, { deployRequestBody: body });
|
|
1614
|
+
Object.assign(error, {
|
|
1615
|
+
deployRestMethod: method,
|
|
1616
|
+
deployRestPath: path,
|
|
1617
|
+
deployRequestMs: Date.now() - startedAt,
|
|
1618
|
+
...Number.isFinite(timeoutMs) ? { deployTimeoutMs: timeoutMs } : {}
|
|
1619
|
+
});
|
|
1620
|
+
}
|
|
1621
|
+
throw error;
|
|
1622
|
+
}
|
|
1903
1623
|
}
|
|
1904
1624
|
async handleInteraction(rawData) {
|
|
1905
1625
|
await dispatchInteraction(this, rawData);
|
|
1906
1626
|
}
|
|
1907
1627
|
async dispatchGatewayEvent(type, data) {
|
|
1908
|
-
this.
|
|
1628
|
+
this.invalidateEntityCacheForGatewayEvent(type, data);
|
|
1909
1629
|
const listeners = this.listeners.filter((entry) => entry.type === type);
|
|
1910
1630
|
if (!this.eventQueue) {
|
|
1911
1631
|
for (const listener of listeners) await listener.handle(data, this);
|
|
1912
1632
|
return;
|
|
1913
1633
|
}
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1634
|
+
const queue = this.eventQueue;
|
|
1635
|
+
await Promise.all(listeners.map(async (listener) => {
|
|
1636
|
+
if (queue.permits.pendingCount >= queue.maxQueueSize) throw new Error(`Discord event queue is full for ${type}; maxQueueSize=${queue.maxQueueSize}`);
|
|
1637
|
+
const listenerName = listener.constructor.name || "AnonymousListener";
|
|
1638
|
+
const release = await queue.permits.acquire();
|
|
1639
|
+
const startedAt = Date.now();
|
|
1640
|
+
try {
|
|
1918
1641
|
await listener.handle(data, this);
|
|
1642
|
+
const durationMs = Date.now() - startedAt;
|
|
1643
|
+
if (durationMs < 3e4) return;
|
|
1644
|
+
console.warn(`[EventQueue] Slow listener detected: ${listenerName} took ${durationMs}ms for event ${type}`);
|
|
1645
|
+
} catch (error) {
|
|
1646
|
+
console.error(`[EventQueue] Listener ${listenerName} failed for event ${type}:`, error);
|
|
1647
|
+
} finally {
|
|
1648
|
+
release?.();
|
|
1919
1649
|
}
|
|
1920
|
-
}))
|
|
1921
|
-
}
|
|
1922
|
-
};
|
|
1923
|
-
//#endregion
|
|
1924
|
-
//#region extensions/discord/src/internal/components.message.ts
|
|
1925
|
-
var BaseButton = class extends BaseMessageInteractiveComponent {
|
|
1926
|
-
constructor(..._args) {
|
|
1927
|
-
super(..._args);
|
|
1928
|
-
this.type = ComponentType.Button;
|
|
1929
|
-
this.style = ButtonStyle.Primary;
|
|
1930
|
-
this.disabled = false;
|
|
1931
|
-
}
|
|
1932
|
-
serialize() {
|
|
1933
|
-
const link = this instanceof LinkButton;
|
|
1934
|
-
return stripUndefinedFields({
|
|
1935
|
-
type: this.type,
|
|
1936
|
-
style: this.style,
|
|
1937
|
-
custom_id: link ? void 0 : this.customId,
|
|
1938
|
-
label: this.label,
|
|
1939
|
-
emoji: this.emoji,
|
|
1940
|
-
disabled: this.disabled || void 0,
|
|
1941
|
-
url: link ? this.url : void 0
|
|
1942
|
-
});
|
|
1943
|
-
}
|
|
1944
|
-
};
|
|
1945
|
-
var Button = class extends BaseButton {};
|
|
1946
|
-
var LinkButton = class extends BaseButton {
|
|
1947
|
-
constructor(..._args2) {
|
|
1948
|
-
super(..._args2);
|
|
1949
|
-
this.customId = "";
|
|
1950
|
-
this.style = ButtonStyle.Link;
|
|
1951
|
-
}
|
|
1952
|
-
async run() {
|
|
1953
|
-
throw new Error("Link buttons do not run handlers");
|
|
1954
|
-
}
|
|
1955
|
-
};
|
|
1956
|
-
var AnySelectMenu = class extends BaseMessageInteractiveComponent {
|
|
1957
|
-
constructor(..._args3) {
|
|
1958
|
-
super(..._args3);
|
|
1959
|
-
this.disabled = false;
|
|
1960
|
-
}
|
|
1961
|
-
serializeOptions() {
|
|
1962
|
-
return {
|
|
1963
|
-
type: this.type,
|
|
1964
|
-
default_values: this.defaultValues
|
|
1965
|
-
};
|
|
1966
|
-
}
|
|
1967
|
-
serialize() {
|
|
1968
|
-
return stripUndefinedFields({
|
|
1969
|
-
...this.serializeOptions(),
|
|
1970
|
-
custom_id: this.customId,
|
|
1971
|
-
placeholder: this.placeholder,
|
|
1972
|
-
min_values: this.minValues,
|
|
1973
|
-
max_values: this.maxValues,
|
|
1974
|
-
disabled: this.disabled || void 0,
|
|
1975
|
-
required: this.required
|
|
1976
|
-
});
|
|
1977
|
-
}
|
|
1978
|
-
};
|
|
1979
|
-
var StringSelectMenu = class extends AnySelectMenu {
|
|
1980
|
-
constructor(..._args4) {
|
|
1981
|
-
super(..._args4);
|
|
1982
|
-
this.type = ComponentType.StringSelect;
|
|
1983
|
-
}
|
|
1984
|
-
serializeOptions() {
|
|
1985
|
-
return {
|
|
1986
|
-
type: this.type,
|
|
1987
|
-
options: this.options
|
|
1988
|
-
};
|
|
1989
|
-
}
|
|
1990
|
-
};
|
|
1991
|
-
var UserSelectMenu = class extends AnySelectMenu {
|
|
1992
|
-
constructor(..._args5) {
|
|
1993
|
-
super(..._args5);
|
|
1994
|
-
this.type = ComponentType.UserSelect;
|
|
1995
|
-
}
|
|
1996
|
-
};
|
|
1997
|
-
var RoleSelectMenu = class extends AnySelectMenu {
|
|
1998
|
-
constructor(..._args6) {
|
|
1999
|
-
super(..._args6);
|
|
2000
|
-
this.type = ComponentType.RoleSelect;
|
|
2001
|
-
}
|
|
2002
|
-
};
|
|
2003
|
-
var MentionableSelectMenu = class extends AnySelectMenu {
|
|
2004
|
-
constructor(..._args7) {
|
|
2005
|
-
super(..._args7);
|
|
2006
|
-
this.type = ComponentType.MentionableSelect;
|
|
2007
|
-
}
|
|
2008
|
-
};
|
|
2009
|
-
var ChannelSelectMenu = class extends AnySelectMenu {
|
|
2010
|
-
constructor(..._args8) {
|
|
2011
|
-
super(..._args8);
|
|
2012
|
-
this.type = ComponentType.ChannelSelect;
|
|
2013
|
-
}
|
|
2014
|
-
serializeOptions() {
|
|
2015
|
-
return {
|
|
2016
|
-
type: this.type,
|
|
2017
|
-
default_values: this.defaultValues,
|
|
2018
|
-
channel_types: this.channelTypes
|
|
2019
|
-
};
|
|
2020
|
-
}
|
|
2021
|
-
};
|
|
2022
|
-
var Row = class extends BaseComponent {
|
|
2023
|
-
constructor(components = []) {
|
|
2024
|
-
super();
|
|
2025
|
-
this.components = components;
|
|
2026
|
-
this.type = ComponentType.ActionRow;
|
|
2027
|
-
this.isV2 = false;
|
|
2028
|
-
}
|
|
2029
|
-
addComponent(component) {
|
|
2030
|
-
this.components.push(component);
|
|
2031
|
-
}
|
|
2032
|
-
serialize() {
|
|
2033
|
-
return {
|
|
2034
|
-
type: this.type,
|
|
2035
|
-
components: this.components.map((entry) => entry.serialize())
|
|
2036
|
-
};
|
|
2037
|
-
}
|
|
2038
|
-
};
|
|
2039
|
-
var V2Component = class extends BaseComponent {
|
|
2040
|
-
constructor(..._args9) {
|
|
2041
|
-
super(..._args9);
|
|
2042
|
-
this.isV2 = true;
|
|
2043
|
-
}
|
|
2044
|
-
};
|
|
2045
|
-
var TextDisplay = class extends V2Component {
|
|
2046
|
-
constructor(content) {
|
|
2047
|
-
super();
|
|
2048
|
-
this.content = content;
|
|
2049
|
-
this.type = ComponentType.TextDisplay;
|
|
2050
|
-
}
|
|
2051
|
-
serialize() {
|
|
2052
|
-
return stripUndefinedFields({
|
|
2053
|
-
type: this.type,
|
|
2054
|
-
content: this.content
|
|
2055
|
-
});
|
|
2056
|
-
}
|
|
2057
|
-
};
|
|
2058
|
-
var Separator = class extends V2Component {
|
|
2059
|
-
constructor(options) {
|
|
2060
|
-
super();
|
|
2061
|
-
this.type = ComponentType.Separator;
|
|
2062
|
-
this.divider = true;
|
|
2063
|
-
this.spacing = "small";
|
|
2064
|
-
this.spacing = options?.spacing ?? this.spacing;
|
|
2065
|
-
this.divider = options?.divider ?? this.divider;
|
|
2066
|
-
}
|
|
2067
|
-
serialize() {
|
|
2068
|
-
return stripUndefinedFields({
|
|
2069
|
-
type: this.type,
|
|
2070
|
-
divider: this.divider,
|
|
2071
|
-
spacing: this.spacing === "large" ? 2 : this.spacing === "small" ? 1 : this.spacing
|
|
2072
|
-
});
|
|
2073
|
-
}
|
|
2074
|
-
};
|
|
2075
|
-
var Thumbnail = class extends V2Component {
|
|
2076
|
-
constructor(url) {
|
|
2077
|
-
super();
|
|
2078
|
-
this.url = url;
|
|
2079
|
-
this.type = ComponentType.Thumbnail;
|
|
2080
|
-
}
|
|
2081
|
-
serialize() {
|
|
2082
|
-
return stripUndefinedFields({
|
|
2083
|
-
type: this.type,
|
|
2084
|
-
media: this.url ? { url: this.url } : void 0
|
|
2085
|
-
});
|
|
2086
|
-
}
|
|
2087
|
-
};
|
|
2088
|
-
var Section = class extends V2Component {
|
|
2089
|
-
constructor(components = [], accessory) {
|
|
2090
|
-
super();
|
|
2091
|
-
this.components = components;
|
|
2092
|
-
this.accessory = accessory;
|
|
2093
|
-
this.type = ComponentType.Section;
|
|
2094
|
-
}
|
|
2095
|
-
serialize() {
|
|
2096
|
-
return stripUndefinedFields({
|
|
2097
|
-
type: this.type,
|
|
2098
|
-
components: this.components.map((entry) => entry.serialize()),
|
|
2099
|
-
accessory: this.accessory?.serialize()
|
|
2100
|
-
});
|
|
2101
|
-
}
|
|
2102
|
-
};
|
|
2103
|
-
var MediaGallery = class extends V2Component {
|
|
2104
|
-
constructor(items = []) {
|
|
2105
|
-
super();
|
|
2106
|
-
this.items = items;
|
|
2107
|
-
this.type = ComponentType.MediaGallery;
|
|
2108
|
-
}
|
|
2109
|
-
serialize() {
|
|
2110
|
-
return {
|
|
2111
|
-
type: this.type,
|
|
2112
|
-
items: this.items.map((entry) => ({
|
|
2113
|
-
media: { url: entry.url },
|
|
2114
|
-
description: entry.description,
|
|
2115
|
-
spoiler: entry.spoiler
|
|
2116
|
-
}))
|
|
2117
|
-
};
|
|
2118
|
-
}
|
|
2119
|
-
};
|
|
2120
|
-
var File = class extends V2Component {
|
|
2121
|
-
constructor(file, spoiler = false) {
|
|
2122
|
-
super();
|
|
2123
|
-
this.file = file;
|
|
2124
|
-
this.spoiler = spoiler;
|
|
2125
|
-
this.type = ComponentType.File;
|
|
2126
|
-
}
|
|
2127
|
-
serialize() {
|
|
2128
|
-
return stripUndefinedFields({
|
|
2129
|
-
type: this.type,
|
|
2130
|
-
file: this.file ? { url: this.file } : void 0,
|
|
2131
|
-
spoiler: this.spoiler || void 0
|
|
2132
|
-
});
|
|
2133
|
-
}
|
|
2134
|
-
};
|
|
2135
|
-
var Container = class extends V2Component {
|
|
2136
|
-
constructor(components = [], options) {
|
|
2137
|
-
super();
|
|
2138
|
-
this.components = components;
|
|
2139
|
-
this.type = ComponentType.Container;
|
|
2140
|
-
this.spoiler = false;
|
|
2141
|
-
this.accentColor = options?.accentColor;
|
|
2142
|
-
this.spoiler = options?.spoiler ?? false;
|
|
2143
|
-
}
|
|
2144
|
-
serialize() {
|
|
2145
|
-
return stripUndefinedFields({
|
|
2146
|
-
type: this.type,
|
|
2147
|
-
components: this.components.map((entry) => entry.serialize()),
|
|
2148
|
-
accent_color: colorToNumber(this.accentColor),
|
|
2149
|
-
spoiler: this.spoiler || void 0
|
|
2150
|
-
});
|
|
1650
|
+
}));
|
|
2151
1651
|
}
|
|
2152
1652
|
};
|
|
2153
1653
|
//#endregion
|
|
@@ -2244,60 +1744,6 @@ var GuildCreateListener = class extends BaseListener {
|
|
|
2244
1744
|
this.type = GatewayDispatchEvents.GuildCreate;
|
|
2245
1745
|
}
|
|
2246
1746
|
};
|
|
2247
|
-
var GuildDeleteListener = class extends BaseListener {
|
|
2248
|
-
constructor(..._args3) {
|
|
2249
|
-
super(..._args3);
|
|
2250
|
-
this.type = GatewayDispatchEvents.GuildDelete;
|
|
2251
|
-
}
|
|
2252
|
-
};
|
|
2253
|
-
var MessageCreateListener = class extends BaseListener {
|
|
2254
|
-
constructor(..._args4) {
|
|
2255
|
-
super(..._args4);
|
|
2256
|
-
this.type = GatewayDispatchEvents.MessageCreate;
|
|
2257
|
-
}
|
|
2258
|
-
};
|
|
2259
|
-
var InteractionCreateListener = class extends BaseListener {
|
|
2260
|
-
constructor(..._args5) {
|
|
2261
|
-
super(..._args5);
|
|
2262
|
-
this.type = GatewayDispatchEvents.InteractionCreate;
|
|
2263
|
-
}
|
|
2264
|
-
};
|
|
2265
|
-
var MessageReactionAddListener = class extends BaseListener {
|
|
2266
|
-
constructor(..._args6) {
|
|
2267
|
-
super(..._args6);
|
|
2268
|
-
this.type = GatewayDispatchEvents.MessageReactionAdd;
|
|
2269
|
-
}
|
|
2270
|
-
};
|
|
2271
|
-
var MessageReactionRemoveListener = class extends BaseListener {
|
|
2272
|
-
constructor(..._args7) {
|
|
2273
|
-
super(..._args7);
|
|
2274
|
-
this.type = GatewayDispatchEvents.MessageReactionRemove;
|
|
2275
|
-
}
|
|
2276
|
-
};
|
|
2277
|
-
var PresenceUpdateListener = class extends BaseListener {
|
|
2278
|
-
constructor(..._args8) {
|
|
2279
|
-
super(..._args8);
|
|
2280
|
-
this.type = GatewayDispatchEvents.PresenceUpdate;
|
|
2281
|
-
}
|
|
2282
|
-
};
|
|
2283
|
-
var VoiceStateUpdateListener = class extends BaseListener {
|
|
2284
|
-
constructor(..._args9) {
|
|
2285
|
-
super(..._args9);
|
|
2286
|
-
this.type = GatewayDispatchEvents.VoiceStateUpdate;
|
|
2287
|
-
}
|
|
2288
|
-
};
|
|
2289
|
-
var ThreadUpdateListener = class extends BaseListener {
|
|
2290
|
-
constructor(..._args10) {
|
|
2291
|
-
super(..._args10);
|
|
2292
|
-
this.type = GatewayDispatchEvents.ThreadUpdate;
|
|
2293
|
-
}
|
|
2294
|
-
};
|
|
2295
|
-
var ThreadDeleteListener = class extends BaseListener {
|
|
2296
|
-
constructor(..._args11) {
|
|
2297
|
-
super(..._args11);
|
|
2298
|
-
this.type = GatewayDispatchEvents.ThreadDelete;
|
|
2299
|
-
}
|
|
2300
|
-
};
|
|
2301
1747
|
//#endregion
|
|
2302
1748
|
//#region extensions/discord/src/internal/discord.ts
|
|
2303
1749
|
var discord_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -2305,57 +1751,27 @@ var discord_exports = /* @__PURE__ */ __exportAll({
|
|
|
2305
1751
|
BaseCommand: () => BaseCommand,
|
|
2306
1752
|
BaseComponentInteraction: () => BaseComponentInteraction,
|
|
2307
1753
|
BaseMessageInteractiveComponent: () => BaseMessageInteractiveComponent,
|
|
2308
|
-
Button: () => Button,
|
|
2309
|
-
ButtonInteraction: () => ButtonInteraction,
|
|
2310
|
-
ChannelSelectMenu: () => ChannelSelectMenu,
|
|
2311
|
-
CheckboxGroup: () => CheckboxGroup,
|
|
2312
1754
|
Client: () => Client,
|
|
2313
1755
|
Command: () => Command,
|
|
2314
1756
|
CommandInteraction: () => CommandInteraction,
|
|
2315
1757
|
CommandWithSubcommands: () => CommandWithSubcommands,
|
|
2316
|
-
|
|
1758
|
+
DISCORD_REST_TIMEOUT_MS: () => DISCORD_REST_TIMEOUT_MS,
|
|
2317
1759
|
DiscordError: () => DiscordError,
|
|
2318
1760
|
Embed: () => Embed,
|
|
2319
|
-
File: () => File,
|
|
2320
1761
|
Guild: () => Guild,
|
|
2321
1762
|
GuildCreateListener: () => GuildCreateListener,
|
|
2322
|
-
GuildDeleteListener: () => GuildDeleteListener,
|
|
2323
1763
|
GuildMember: () => GuildMember,
|
|
2324
|
-
InteractionCreateListener: () => InteractionCreateListener,
|
|
2325
|
-
Label: () => Label,
|
|
2326
|
-
LinkButton: () => LinkButton,
|
|
2327
|
-
MediaGallery: () => MediaGallery,
|
|
2328
|
-
MentionableSelectMenu: () => MentionableSelectMenu,
|
|
2329
1764
|
Message: () => Message,
|
|
2330
|
-
MessageCreateListener: () => MessageCreateListener,
|
|
2331
|
-
MessageReactionAddListener: () => MessageReactionAddListener,
|
|
2332
|
-
MessageReactionRemoveListener: () => MessageReactionRemoveListener,
|
|
2333
1765
|
Modal: () => Modal,
|
|
2334
1766
|
ModalInteraction: () => ModalInteraction,
|
|
2335
|
-
Plugin: () => Plugin,
|
|
2336
|
-
PresenceUpdateListener: () => PresenceUpdateListener,
|
|
2337
|
-
RadioGroup: () => RadioGroup,
|
|
2338
1767
|
RateLimitError: () => RateLimitError,
|
|
2339
1768
|
ReadyListener: () => ReadyListener,
|
|
2340
1769
|
RequestClient: () => RequestClient,
|
|
2341
1770
|
Role: () => Role,
|
|
2342
|
-
RoleSelectMenu: () => RoleSelectMenu,
|
|
2343
|
-
Row: () => Row,
|
|
2344
|
-
Section: () => Section,
|
|
2345
|
-
Separator: () => Separator,
|
|
2346
|
-
StringSelectMenu: () => StringSelectMenu,
|
|
2347
|
-
StringSelectMenuInteraction: () => StringSelectMenuInteraction,
|
|
2348
|
-
TextDisplay: () => TextDisplay,
|
|
2349
|
-
TextInput: () => TextInput,
|
|
2350
|
-
ThreadDeleteListener: () => ThreadDeleteListener,
|
|
2351
|
-
ThreadUpdateListener: () => ThreadUpdateListener,
|
|
2352
|
-
Thumbnail: () => Thumbnail,
|
|
2353
1771
|
User: () => User,
|
|
2354
|
-
|
|
2355
|
-
VoiceStateUpdateListener: () => VoiceStateUpdateListener,
|
|
1772
|
+
asSerializableComponent: () => asSerializableComponent,
|
|
2356
1773
|
channelFactory: () => channelFactory,
|
|
2357
1774
|
createChannelMessage: () => createChannelMessage,
|
|
2358
|
-
createChannelWebhook: () => createChannelWebhook,
|
|
2359
1775
|
createInteraction: () => createInteraction,
|
|
2360
1776
|
createOwnMessageReaction: () => createOwnMessageReaction,
|
|
2361
1777
|
createThread: () => createThread,
|
|
@@ -2373,12 +1789,10 @@ var discord_exports = /* @__PURE__ */ __exportAll({
|
|
|
2373
1789
|
getThreadMember: () => getThreadMember,
|
|
2374
1790
|
getUser: () => getUser,
|
|
2375
1791
|
hasDiscordV2Components: () => hasDiscordV2Components,
|
|
2376
|
-
isUnknownDiscordMessageError: () => isUnknownDiscordMessageError,
|
|
2377
1792
|
isUnknownDiscordVoiceStateError: () => isUnknownDiscordVoiceStateError,
|
|
2378
1793
|
listGuildEmojis: () => listGuildEmojis,
|
|
2379
1794
|
listMessageReactionUsers: () => listMessageReactionUsers,
|
|
2380
1795
|
normalizeDiscordMessageId: () => normalizeDiscordMessageId,
|
|
2381
|
-
parseCustomId: () => parseCustomId,
|
|
2382
1796
|
pinChannelMessage: () => pinChannelMessage,
|
|
2383
1797
|
resolveFocusedCommandOptionAutocompleteHandler: () => resolveFocusedCommandOptionAutocompleteHandler,
|
|
2384
1798
|
serializePayload: () => serializePayload,
|
|
@@ -2387,4 +1801,4 @@ var discord_exports = /* @__PURE__ */ __exportAll({
|
|
|
2387
1801
|
import * as import_discord_api_types_v10 from "discord-api-types/v10";
|
|
2388
1802
|
__reExport(discord_exports, import_discord_api_types_v10);
|
|
2389
1803
|
//#endregion
|
|
2390
|
-
export {
|
|
1804
|
+
export { getThreadMember as A, RateLimitError as B, listMessageReactionUsers as C, editChannelMessage as D, deleteChannelMessage as E, getGuildVoiceState as F, readRetryAfter as G, isUnknownDiscordVoiceStateError as H, listGuildEmojis as I, stripUndefinedFields as J, captureDiscordRequestAuthority as K, DISCORD_REST_TIMEOUT_MS as L, unpinChannelMessage as M, getGuild as N, getChannel as O, getGuildMember as P, RequestClient as R, deleteOwnMessageReaction as S, createThread as T, readDiscordCode as U, isUnknownDiscordMessageError as V, readDiscordMessage as W, Command as _, Label as a, getCurrentUser as b, TextInput as c, hasDiscordV2Components as d, serializePayload as f, User as g, Message as h, CheckboxGroup as i, pinChannelMessage as j, getChannelMessage as k, Client as l, Guild as m, GuildCreateListener as n, Modal as o, Embed as p, withDiscordRequestAuthority as q, ReadyListener as r, RadioGroup as s, discord_exports as t, asSerializableComponent as u, CommandWithSubcommands as v, createChannelMessage as w, createOwnMessageReaction as x, createUserDmChannel as y, DiscordError as z };
|