@openclaw/discord 2026.10.10 → 2026.11.5-beta.1
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-X_Xlr42B.mjs → account-inspect-CSz5Qodj.mjs} +1 -1
- package/dist/.setup/{accounts-C18HNgge.mjs → accounts-DtjvhJUj.mjs} +9 -6
- package/dist/.setup/{active-turn-thread-route-BAc_Xik-.mjs → active-turn-thread-route-DkPnk2x8.mjs} +1 -2
- package/dist/.setup/{allow-list-D1ZGfhXh.mjs → allow-list-DahA0Jxh.mjs} +3 -150
- package/dist/.setup/{api-Bth1wKF9.mjs → api-Bp0HI4q3.mjs} +10 -20
- package/dist/.setup/{approval-handler.runtime-BAoEELJJ.mjs → approval-handler.runtime-Cy53ugTf.mjs} +80 -61
- package/dist/.setup/{approval-message-updates-Cks-MSCJ.mjs → approval-message-updates-DqOXxPss.mjs} +2 -2
- package/dist/.setup/{audit-Dw_rAZIz.mjs → audit-DoPKOfQE.mjs} +4 -4
- package/dist/.setup/{channel-BMpMAeQL.mjs → channel-Ds6iuNdy.mjs} +134 -201
- package/dist/.setup/channel-access-DhJhVrdZ.mjs +23 -0
- package/dist/.setup/channel.setup-BLt9dkIG.mjs +235 -0
- package/dist/.setup/{components-BvOWSPxr.mjs → components-WTfUxead.mjs} +208 -426
- package/dist/.setup/components.base-C5sAPHe4.mjs +31 -0
- package/dist/.setup/{config-schema-Coyq5wOr.mjs → config-schema-GX2yDgIH.mjs} +6 -7
- package/dist/.setup/{conversation-binding-route-DOPUZNYo.mjs → conversation-binding-route-CZdm-X5A.mjs} +2 -2
- package/dist/.setup/{directory-config-CIqVnQtn.mjs → directory-config-BXJuh9-J.mjs} +1 -1
- package/dist/.setup/{directory-live-DUuPEWub.mjs → directory-live-CEopeb8Q.mjs} +55 -62
- package/dist/.setup/{discord-eFlHX1Gn.mjs → discord-r79VFjJp.mjs} +1087 -1664
- package/dist/.setup/{doctor-Dty_Ossy.mjs → doctor-UfLW8nye.mjs} +3 -5
- package/dist/.setup/endpoint-runtime-BM3x-m6O.mjs +138 -0
- package/dist/.setup/guilds-DQucP5Tn.mjs +21 -0
- package/dist/.setup/{handle-action-DXY91jF-.mjs → handle-action-BarHOi-v.mjs} +15 -15
- package/dist/.setup/{handle-action.guild-admin-BvBCfhXF.mjs → handle-action.guild-admin-oRUb8p_O.mjs} +5 -5
- package/dist/.setup/listeners-CHgTENFu.mjs +46 -0
- package/dist/.setup/{live-policy-config-DO1Fk2hp.mjs → live-policy-config-EKp4O6zx.mjs} +2 -3
- package/dist/.setup/{message-handler-fL1j1NiR.mjs → message-handler-DUeT8Asf.mjs} +154 -113
- package/dist/.setup/{message-handler.preflight-DkjwNZAd.mjs → message-handler.preflight-C6TNtKW0.mjs} +30 -104
- package/dist/.setup/{message-handler.preflight-pluralkit-DR4BnvMU.mjs → message-handler.preflight-pluralkit-6E9TFmmN.mjs} +9 -22
- package/dist/.setup/{message-handler.process-ClOwIPDK.mjs → message-handler.process-D8_oQ5Cp.mjs} +256 -367
- package/dist/.setup/outbound-payload-DUsrFICb.mjs +445 -0
- package/dist/.setup/{outbound-session-route-TFBPPkoz.mjs → outbound-session-route-Cb8cv4Oi.mjs} +138 -86
- package/dist/.setup/{preflight-audio-CwtPIsvk.mjs → preflight-audio-r4BbaJxh.mjs} +1 -5
- package/dist/.setup/{presence-cache-CgutE4NN.mjs → presence-cache-B3xj3b0l.mjs} +1 -6
- package/dist/.setup/{probe-DNge7OEP.mjs → probe-BUmJyH35.mjs} +5 -9
- package/dist/.setup/{provider-BBDuE14w.mjs → provider-Dm2ERSxe.mjs} +3600 -4454
- package/dist/.setup/{provider-session.runtime-D8hMXXqJ.mjs → provider-session.runtime-DCIqDsIg.mjs} +3 -3
- package/dist/.setup/provider.runtime-DmxPGoUg.mjs +1 -0
- package/dist/.setup/proxy-fetch-B8cK6FLQ.mjs +29 -0
- package/dist/.setup/{realtime-session.runtime-cetognkp.mjs → realtime-session.runtime-WJL6NdwK.mjs} +43 -81
- package/dist/.setup/{receive-recovery-C77CVdGM.mjs → receive-recovery-DV_v5ROf.mjs} +13 -27
- package/dist/.setup/{resolve-allowlist-common-CI77288n.mjs → resolve-allowlist-common-C37fgnYG.mjs} +3 -12
- package/dist/.setup/{resolve-channels-DYc6-xgV.mjs → resolve-channels-CwpnQ7C2.mjs} +5 -4
- package/dist/.setup/{resolve-users-BQT7XWF2.mjs → resolve-users-D6jSwe8R.mjs} +4 -7
- package/dist/.setup/{runtime-CcijhTJT.mjs → runtime-B-PgPsGR.mjs} +6 -6
- package/dist/.setup/{runtime-CI0UJqeS.mjs → runtime-DhOMlnYS.mjs} +196 -235
- package/dist/.setup/{secret-config-contract-BdbCvqnM.mjs → secret-config-contract-CP6teHec.mjs} +4 -9
- package/dist/.setup/{send-Cbq-IVsS.mjs → send-DnLL6XoO.mjs} +149 -174
- package/dist/.setup/{send.components-BV6ucNpJ.mjs → send.components-xB43CksK.mjs} +61 -71
- package/dist/.setup/{send.outbound-CGhBhzjQ.mjs → send.outbound-B11X6TOE.mjs} +75 -129
- package/dist/.setup/{send.receipt-Dw-_r5Bx.mjs → send.receipt-CMteCIZS.mjs} +29 -31
- package/dist/.setup/{send.shared-D4MioxW_.mjs → send.shared-BcLLZBul.mjs} +38 -112
- package/dist/.setup/{sender-identity-DrN5c4ec.mjs → sender-identity-CGNpdJmb.mjs} +3 -9
- package/dist/.setup/setup-plugin-api-C6AMx3hu.mjs +2 -0
- package/dist/.setup/{shared-Bp0sxD5R.mjs → shared-BEYw16he.mjs} +8 -10
- package/dist/.setup/shared-interactive-DKBw4SNV.mjs +311 -0
- package/dist/.setup/{subagent-hooks-mQbDkvuD.mjs → subagent-hooks-DlYElpXa.mjs} +1 -1
- package/dist/.setup/{system-events-2zc2eGfF.mjs → system-events--Pk6y9aP.mjs} +2 -2
- package/dist/.setup/{target-resolver-CAHeVfmZ.mjs → target-resolver-Bo9EpGp_.mjs} +3 -3
- package/dist/.setup/{thread-bindings-Dg7X_ZXP.mjs → thread-bindings-BF-hr-bg.mjs} +12 -20
- package/dist/.setup/{thread-bindings.manager-DCDYksah.mjs → thread-bindings.manager-CQCkha5r.mjs} +22 -42
- package/dist/.setup/{thread-bindings.session-updates-C76plLS3.mjs → thread-bindings.session-updates-C2gJAj_I.mjs} +11 -18
- package/dist/.setup/{threading-l0UfrE6x.mjs → threading-HA9C2wYR.mjs} +68 -104
- package/dist/.setup/{timeouts-DTrUsJ_W.mjs → timeouts-CT9hnmo4.mjs} +1 -1
- package/dist/.setup/{transcripts-source-CGgOaWcu.mjs → transcripts-source-DzpzETZR.mjs} +102 -172
- package/dist/.setup/{voice-runtime-DY1EwDfi.mjs → voice-runtime-Bo_nsVvX.mjs} +231 -448
- package/dist/.source-module-urls/d6c089460280c5a04184542d6712e04545caeb1ebb290d3504377b4cc5e22fea.json +1 -1
- package/dist/account-inspect-api.js +1 -1
- package/dist/action-runtime-api.js +1 -1
- package/dist/activities-api.js +285 -337
- package/dist/api.js +16 -16
- package/dist/assets/embedded-app-sdk.mjs +1 -1
- package/dist/channel-config-api.js +1 -1
- package/dist/channel-plugin-api.js +1 -1
- package/dist/directory-contract-api.js +1 -1
- package/dist/runtime-api.js +22 -22
- package/dist/secret-contract-api.js +1 -1
- package/dist/setup-entry.js +1 -1
- package/dist/setup-plugin-api.js +1 -1
- package/dist/src/voice/audio-worker.runtime.js +56 -68
- package/dist/subagent-hooks-api.js +1 -1
- package/dist/transcripts-source-api.js +1 -1
- package/node_modules/@discord/embedded-app-sdk/output/lib/zod/lib/index.cjs +2 -3
- package/node_modules/@discord/embedded-app-sdk/output/lib/zod/lib/index.mjs +2 -3
- 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-BPrWoEXM.mjs +0 -47
- package/dist/.setup/channel.setup-DVe7Y3Jf.mjs +0 -245
- package/dist/.setup/outbound-adapter-DWyAWBFh.mjs +0 -537
- package/dist/.setup/provider.runtime-BQ1z4Aq1.mjs +0 -1
- package/dist/.setup/setup-plugin-api-B4J6wmL1.mjs +0 -2
- package/dist/.setup/targets-BaklhOqq.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,342 +1,860 @@
|
|
|
1
1
|
import { n as __reExport, t as __exportAll } from "./rolldown-runtime-nwUcYXjP.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { C as parseDiscordRetryAfterBodySeconds } from "./allow-list-DahA0Jxh.mjs";
|
|
3
|
+
import { n as getDiscordEndpointRuntime } from "./endpoint-runtime-BM3x-m6O.mjs";
|
|
4
|
+
import { i as parseCustomId, n as BaseModalComponent, t as BaseMessageInteractiveComponent } from "./components.base-C5sAPHe4.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
|
// 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
|
-
// extensions/discord/src/internal/
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
24
|
+
// extensions/discord/src/internal/request-authority.ts
|
|
25
|
+
const requestAuthority = resolveGlobalSingleton(Symbol.for("openclaw.discord.requestAuthority"), () => new AsyncLocalStorage());
|
|
26
|
+
/** Carry the host's existing assertion without changing its lifetime or ownership. */
|
|
27
|
+
function withDiscordRequestAuthority(assertCurrent, run) {
|
|
28
|
+
if (!assertCurrent) return run();
|
|
29
|
+
const inherited = requestAuthority.getStore();
|
|
30
|
+
return requestAuthority.run(inherited && inherited !== assertCurrent ? () => {
|
|
31
|
+
inherited();
|
|
32
|
+
assertCurrent();
|
|
33
|
+
} : assertCurrent, run);
|
|
31
34
|
}
|
|
32
|
-
function
|
|
33
|
-
return
|
|
35
|
+
function captureDiscordRequestAuthority() {
|
|
36
|
+
return requestAuthority.getStore();
|
|
34
37
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const emojis = await rest.get(Routes.guildEmojis(guildId));
|
|
39
|
-
if (!Check(discordGuildEmojiListSchema, emojis)) throw new Error("Invalid Discord guild emoji response.");
|
|
40
|
-
return emojis;
|
|
38
|
+
// extensions/discord/src/internal/rest-body.ts
|
|
39
|
+
function fileBlob(file) {
|
|
40
|
+
return file.data instanceof Blob ? file.data : new Blob([file.data], { type: typeof file.contentType === "string" ? file.contentType : void 0 });
|
|
41
41
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
if (
|
|
46
|
-
|
|
42
|
+
function serializeRequestBody(data, headers) {
|
|
43
|
+
if (data?.headers) for (const [key, value] of Object.entries(data.headers)) headers.set(key, value);
|
|
44
|
+
if (data?.body == null) return;
|
|
45
|
+
if (typeof data.body === "object") {
|
|
46
|
+
const bodyObject = data.body;
|
|
47
|
+
const topLevelFiles = Array.isArray(bodyObject.files) ? bodyObject.files : void 0;
|
|
48
|
+
const nestedData = bodyObject.data && typeof bodyObject.data === "object" ? bodyObject.data : void 0;
|
|
49
|
+
const nestedFiles = nestedData && Array.isArray(nestedData.files) ? nestedData.files : void 0;
|
|
50
|
+
const files = topLevelFiles ?? nestedFiles;
|
|
51
|
+
const filesContainer = topLevelFiles ? bodyObject : nestedFiles ? nestedData : void 0;
|
|
52
|
+
if (files?.length && filesContainer) {
|
|
53
|
+
if (data.multipartStyle === "form") {
|
|
54
|
+
const formData = new FormData();
|
|
55
|
+
for (const [key, value] of Object.entries(filesContainer)) {
|
|
56
|
+
if (key === "files" || value === void 0 || value === null) continue;
|
|
57
|
+
formData.append(key, typeof value === "string" ? value : JSON.stringify(value));
|
|
58
|
+
}
|
|
59
|
+
for (const file of files) {
|
|
60
|
+
const item = file;
|
|
61
|
+
const name = typeof item.name === "string" && item.name ? item.name : "file";
|
|
62
|
+
formData.append(typeof item.fieldName === "string" && item.fieldName ? item.fieldName : "file", fileBlob(item), name);
|
|
63
|
+
}
|
|
64
|
+
return formData;
|
|
65
|
+
}
|
|
66
|
+
const payloadFilesContainer = { ...filesContainer };
|
|
67
|
+
const payloadJson = topLevelFiles ? payloadFilesContainer : {
|
|
68
|
+
...bodyObject,
|
|
69
|
+
data: payloadFilesContainer
|
|
70
|
+
};
|
|
71
|
+
const formData = new FormData();
|
|
72
|
+
const existingAttachments = Array.isArray(payloadFilesContainer.attachments) ? payloadFilesContainer.attachments : [];
|
|
73
|
+
const uploaded = files.map((file, index) => {
|
|
74
|
+
const item = file;
|
|
75
|
+
const name = typeof item.name === "string" && item.name ? item.name : `file-${index}`;
|
|
76
|
+
const id = existingAttachments.length + index;
|
|
77
|
+
formData.append(`files[${id}]`, fileBlob(item), name);
|
|
78
|
+
const attachment = {
|
|
79
|
+
id,
|
|
80
|
+
filename: name
|
|
81
|
+
};
|
|
82
|
+
if (typeof item.description === "string") attachment.description = item.description;
|
|
83
|
+
if (typeof item.duration_secs === "number") attachment.duration_secs = item.duration_secs;
|
|
84
|
+
if (typeof item.waveform === "string") attachment.waveform = item.waveform;
|
|
85
|
+
return attachment;
|
|
86
|
+
});
|
|
87
|
+
payloadFilesContainer.attachments = [...existingAttachments, ...uploaded];
|
|
88
|
+
delete payloadFilesContainer.files;
|
|
89
|
+
formData.append("payload_json", JSON.stringify(payloadJson));
|
|
90
|
+
return formData;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
headers.set("Content-Type", "application/json");
|
|
94
|
+
return JSON.stringify(data.body);
|
|
47
95
|
}
|
|
48
|
-
|
|
49
|
-
|
|
96
|
+
// extensions/discord/src/internal/rest-errors.ts
|
|
97
|
+
const DISCORD_UNKNOWN_MESSAGE = 10008;
|
|
98
|
+
const DISCORD_UNKNOWN_VOICE_STATE = 10065;
|
|
99
|
+
const DISCORD_ERROR_BODY_MAX_DEPTH = 64;
|
|
100
|
+
const DISCORD_ERROR_BODY_MAX_NODES = 1e4;
|
|
101
|
+
const DISCORD_ERROR_BODY_MAX_DEPTH_MARKER = "[Discord error body redacted: maximum depth exceeded]";
|
|
102
|
+
const DISCORD_ERROR_BODY_MAX_NODES_MARKER = "[Discord error body redacted: node limit exceeded]";
|
|
103
|
+
const DISCORD_ERROR_BODY_PRIORITY_KEYS = /* @__PURE__ */ new Set([
|
|
104
|
+
"message",
|
|
105
|
+
"code",
|
|
106
|
+
"retry_after",
|
|
107
|
+
"global"
|
|
108
|
+
]);
|
|
109
|
+
const DISCORD_RATE_LIMIT_SCOPES = /* @__PURE__ */ new Set([
|
|
110
|
+
"user",
|
|
111
|
+
"global",
|
|
112
|
+
"shared"
|
|
113
|
+
]);
|
|
114
|
+
function reserveRedactedKey(key, usedKeys, collisionCounts) {
|
|
115
|
+
let count = (collisionCounts.get(key) ?? 0) + 1;
|
|
116
|
+
let candidate = count === 1 ? key : `${key} [${count}]`;
|
|
117
|
+
while (usedKeys.has(candidate)) {
|
|
118
|
+
count += 1;
|
|
119
|
+
candidate = `${key} [${count}]`;
|
|
120
|
+
}
|
|
121
|
+
collisionCounts.set(key, count);
|
|
122
|
+
usedKeys.add(candidate);
|
|
123
|
+
return candidate;
|
|
50
124
|
}
|
|
51
|
-
|
|
52
|
-
|
|
125
|
+
function redactDiscordErrorBody(body, fieldKey = "", sensitiveAncestorKey, state = {
|
|
126
|
+
seen: /* @__PURE__ */ new WeakSet(),
|
|
127
|
+
remainingNodes: DISCORD_ERROR_BODY_MAX_NODES
|
|
128
|
+
}, depth = 0) {
|
|
129
|
+
if (state.remainingNodes <= 0) return DISCORD_ERROR_BODY_MAX_NODES_MARKER;
|
|
130
|
+
state.remainingNodes -= 1;
|
|
131
|
+
if (typeof body === "string") return redactSensitiveFieldValue(sensitiveAncestorKey ?? fieldKey, body);
|
|
132
|
+
if (sensitiveAncestorKey && (typeof body === "number" || typeof body === "boolean" || typeof body === "bigint")) return redactSensitiveFieldValue(sensitiveAncestorKey, String(body));
|
|
133
|
+
if (!body || typeof body !== "object") return body;
|
|
134
|
+
if (depth >= DISCORD_ERROR_BODY_MAX_DEPTH) return DISCORD_ERROR_BODY_MAX_DEPTH_MARKER;
|
|
135
|
+
if (state.seen.has(body)) return "[Circular]";
|
|
136
|
+
state.seen.add(body);
|
|
137
|
+
let redacted;
|
|
138
|
+
if (Array.isArray(body)) {
|
|
139
|
+
const items = [];
|
|
140
|
+
for (const entry of body) {
|
|
141
|
+
if (state.remainingNodes <= 0) {
|
|
142
|
+
items.push(DISCORD_ERROR_BODY_MAX_NODES_MARKER);
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
items.push(redactDiscordErrorBody(entry, fieldKey, sensitiveAncestorKey, state, depth + 1));
|
|
146
|
+
}
|
|
147
|
+
redacted = items;
|
|
148
|
+
} else {
|
|
149
|
+
const usedKeys = /* @__PURE__ */ new Set();
|
|
150
|
+
const collisionCounts = /* @__PURE__ */ new Map();
|
|
151
|
+
const entries = [];
|
|
152
|
+
const appendEntry = (nestedKey) => {
|
|
153
|
+
if (state.remainingNodes <= 0) return false;
|
|
154
|
+
const outputKey = reserveRedactedKey(redactSensitiveFieldValue(sensitiveAncestorKey ?? "", nestedKey), usedKeys, collisionCounts);
|
|
155
|
+
const nestedSensitiveKey = redactSensitiveFieldValue(nestedKey, "") !== "" ? nestedKey : sensitiveAncestorKey;
|
|
156
|
+
entries.push([outputKey, redactDiscordErrorBody(body[nestedKey], nestedKey, nestedSensitiveKey, state, depth + 1)]);
|
|
157
|
+
return true;
|
|
158
|
+
};
|
|
159
|
+
let truncated = false;
|
|
160
|
+
for (const priorityKey of DISCORD_ERROR_BODY_PRIORITY_KEYS) if (Object.hasOwn(body, priorityKey) && !appendEntry(priorityKey)) {
|
|
161
|
+
truncated = true;
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
if (!truncated) for (const nestedKey in body) {
|
|
165
|
+
if (!Object.hasOwn(body, nestedKey) || DISCORD_ERROR_BODY_PRIORITY_KEYS.has(nestedKey)) continue;
|
|
166
|
+
if (!appendEntry(nestedKey)) {
|
|
167
|
+
truncated = true;
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (truncated) {
|
|
172
|
+
const markerKey = reserveRedactedKey(DISCORD_ERROR_BODY_MAX_NODES_MARKER, usedKeys, collisionCounts);
|
|
173
|
+
entries.push([markerKey, DISCORD_ERROR_BODY_MAX_NODES_MARKER]);
|
|
174
|
+
}
|
|
175
|
+
redacted = Object.fromEntries(entries);
|
|
176
|
+
}
|
|
177
|
+
state.seen.delete(body);
|
|
178
|
+
return redacted;
|
|
53
179
|
}
|
|
54
|
-
|
|
55
|
-
return
|
|
180
|
+
function readDiscordCode(body) {
|
|
181
|
+
return parseStrictNonNegativeInteger(asOptionalObjectRecord(body)?.code);
|
|
56
182
|
}
|
|
57
|
-
|
|
58
|
-
|
|
183
|
+
function readDiscordMessage(body, fallback) {
|
|
184
|
+
const value = asOptionalObjectRecord(body)?.message;
|
|
185
|
+
return typeof value === "string" && value.trim() ? value : fallback;
|
|
59
186
|
}
|
|
60
|
-
|
|
61
|
-
return
|
|
187
|
+
function readErrorDiscordCode(err) {
|
|
188
|
+
return parseStrictNonNegativeInteger(asOptionalObjectRecord(err)?.discordCode);
|
|
62
189
|
}
|
|
63
|
-
function
|
|
64
|
-
return
|
|
65
|
-
await rest[method](Routes[route](channelId, normalizeDiscordMessageId(messageId)));
|
|
66
|
-
};
|
|
190
|
+
function isUnknownDiscordMessageError(err) {
|
|
191
|
+
return readErrorDiscordCode(err) === DISCORD_UNKNOWN_MESSAGE;
|
|
67
192
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
const unpinChannelMessage = messageMutation("delete", "channelPin");
|
|
71
|
-
async function createThread(rest, channelId, data, messageId) {
|
|
72
|
-
const route = messageId === void 0 ? Routes.threads(channelId) : Routes.threads(channelId, normalizeDiscordMessageId(messageId));
|
|
73
|
-
return await rest.post(route, data);
|
|
193
|
+
function isUnknownDiscordVoiceStateError(err) {
|
|
194
|
+
return readErrorDiscordCode(err) === DISCORD_UNKNOWN_VOICE_STATE || /unknown voice state/i.test(formatErrorMessage(err));
|
|
74
195
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
return async (rest, channelId, messageId, encodedEmoji) => {
|
|
78
|
-
await rest[method](Routes.channelMessageOwnReaction(channelId, normalizeDiscordMessageId(messageId), encodedEmoji));
|
|
79
|
-
};
|
|
196
|
+
function readRetryAfter(body, response) {
|
|
197
|
+
return parseDiscordRetryAfterBodySeconds(asOptionalObjectRecord(body)?.retry_after) ?? parseRetryAfterHeaderSeconds(response.headers.get("Retry-After")) ?? 1;
|
|
80
198
|
}
|
|
81
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
return await rest.get(Routes.channelMessageReaction(channelId, normalizeDiscordMessageId(messageId), encodedEmoji), query);
|
|
199
|
+
function readDiscordRateLimitBucket(response) {
|
|
200
|
+
const value = response.headers.get("X-RateLimit-Bucket")?.trim();
|
|
201
|
+
return value ? redactIdentifier(value, { len: 32 }) : null;
|
|
85
202
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
return
|
|
203
|
+
function readDiscordRateLimitScope(response) {
|
|
204
|
+
const value = response.headers.get("X-RateLimit-Scope");
|
|
205
|
+
return value && DISCORD_RATE_LIMIT_SCOPES.has(value) ? value : null;
|
|
89
206
|
}
|
|
90
|
-
|
|
91
|
-
|
|
207
|
+
var DiscordError = class extends Error {
|
|
208
|
+
constructor(response, body) {
|
|
209
|
+
const fallbackMessage = `Discord API request failed (${response.status})`;
|
|
210
|
+
const redactedMessage = redactSensitiveFieldValue("message", readDiscordMessage(body, fallbackMessage));
|
|
211
|
+
const redactedBody = redactDiscordErrorBody(body);
|
|
212
|
+
super(redactedMessage);
|
|
213
|
+
this.name = "DiscordError";
|
|
214
|
+
this.status = response.status;
|
|
215
|
+
this.statusCode = response.status;
|
|
216
|
+
this.rawBody = redactedBody;
|
|
217
|
+
this.discordCode = readDiscordCode(body);
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
var RateLimitError = class extends DiscordError {
|
|
221
|
+
constructor(response, body) {
|
|
222
|
+
super(response, body);
|
|
223
|
+
this.name = "RateLimitError";
|
|
224
|
+
this.retryAfter = readRetryAfter(body, response);
|
|
225
|
+
this.scope = body.global ? "global" : readDiscordRateLimitScope(response);
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
// extensions/discord/src/internal/rest-routes.ts
|
|
229
|
+
const RATE_LIMIT_HEADER_NUMBER_RE = /^\d+(?:\.\d+)?$/;
|
|
230
|
+
const DISCORD_ROUTE_IDENTIFIER_HASH_LENGTH = 32;
|
|
231
|
+
function redactWebhookTokenInPath(path) {
|
|
232
|
+
const hasLeadingSlash = path.startsWith("/");
|
|
233
|
+
const segments = path.replace(/^\/+/, "").split("/");
|
|
234
|
+
if (segments[0] !== "webhooks" || !segments[1] || !segments[2]) return path;
|
|
235
|
+
segments[2] = redactIdentifier(segments[2], { len: DISCORD_ROUTE_IDENTIFIER_HASH_LENGTH });
|
|
236
|
+
return `${hasLeadingSlash ? "/" : ""}${segments.join("/")}`;
|
|
92
237
|
}
|
|
93
|
-
|
|
94
|
-
|
|
238
|
+
function createRouteKey(method, path) {
|
|
239
|
+
const pathname = path.split("?")[0] ?? path;
|
|
240
|
+
return `${method.toUpperCase()} ${redactWebhookTokenInPath(pathname)}`;
|
|
95
241
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
242
|
+
function readTopLevelRouteKey(path) {
|
|
243
|
+
const [pathname = path] = path.split("?");
|
|
244
|
+
const [first, id, token] = pathname.replace(/^\/+/, "").split("/");
|
|
245
|
+
if (!first || !id) return pathname;
|
|
246
|
+
if (first === "channels" || first === "guilds" || first === "webhooks") return first === "webhooks" && token ? `${first}/${id}/${redactIdentifier(token, { len: DISCORD_ROUTE_IDENTIFIER_HASH_LENGTH })}` : `${first}/${id}`;
|
|
247
|
+
return first;
|
|
99
248
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
"channel_types",
|
|
103
|
-
"contexts",
|
|
104
|
-
"integration_types"
|
|
105
|
-
]);
|
|
106
|
-
const optionComparisonOmittedFields = /* @__PURE__ */ new Set([
|
|
107
|
-
"contexts",
|
|
108
|
-
"default_member_permissions",
|
|
109
|
-
"description_localized",
|
|
110
|
-
"integration_types",
|
|
111
|
-
"name_localized"
|
|
112
|
-
]);
|
|
113
|
-
const nullableLocalizationFields = /* @__PURE__ */ new Set(["description_localizations", "name_localizations"]);
|
|
114
|
-
function comparableCommand(value) {
|
|
115
|
-
if (!value || typeof value !== "object") return value;
|
|
116
|
-
const omit = /* @__PURE__ */ new Set([
|
|
117
|
-
"application_id",
|
|
118
|
-
"description_localized",
|
|
119
|
-
"dm_permission",
|
|
120
|
-
"guild_id",
|
|
121
|
-
"id",
|
|
122
|
-
"name_localized",
|
|
123
|
-
"nsfw",
|
|
124
|
-
"version",
|
|
125
|
-
"default_permission"
|
|
126
|
-
]);
|
|
127
|
-
return stableComparableObject(Object.fromEntries(Object.entries(value).filter(([key, entry]) => !omit.has(key) && entry !== void 0)));
|
|
249
|
+
function createBucketKey(bucket, path) {
|
|
250
|
+
return `${bucket}:${readTopLevelRouteKey(path)}`;
|
|
128
251
|
}
|
|
129
|
-
function
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
if (!value || typeof value !== "object") return value;
|
|
137
|
-
return Object.fromEntries(Object.entries(value).filter(([key, entry]) => {
|
|
138
|
-
if (entry === void 0) return false;
|
|
139
|
-
if (entry === null && nullableLocalizationFields.has(key)) return false;
|
|
140
|
-
if (pathValue.includes("options") && optionComparisonOmittedFields.has(key)) return false;
|
|
141
|
-
if ((key === "required" || key === "autocomplete") && entry === false) return false;
|
|
142
|
-
return true;
|
|
143
|
-
}).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])]));
|
|
252
|
+
function readHeaderNumber(headers, name) {
|
|
253
|
+
const value = headers.get(name);
|
|
254
|
+
if (!value) return;
|
|
255
|
+
const trimmed = value.trim();
|
|
256
|
+
if (!RATE_LIMIT_HEADER_NUMBER_RE.test(trimmed)) return;
|
|
257
|
+
const parsed = Number(trimmed);
|
|
258
|
+
return Number.isFinite(parsed) && Math.abs(parsed) <= Number.MAX_SAFE_INTEGER ? parsed : void 0;
|
|
144
259
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
const collapsed = description.replace(/\s+/g, " ");
|
|
151
|
-
const cjkBoundaryWhitespace = /([\u3000-\u303F\u4E00-\u9FFF\uFF00-\uFFEF])\s+([\u3000-\u303F\u4E00-\u9FFF\uFF00-\uFFEF])/g;
|
|
152
|
-
return collapsed.replace(cjkBoundaryWhitespace, "$1$2").replace(cjkBoundaryWhitespace, "$1$2").trim();
|
|
260
|
+
function resolveRateLimitResetAt(delayMs) {
|
|
261
|
+
const clampedDelayMs = Math.ceil(Math.max(0, delayMs));
|
|
262
|
+
if (!Number.isSafeInteger(clampedDelayMs)) return;
|
|
263
|
+
if (clampedDelayMs === 0) return asDateTimestampMs(Date.now());
|
|
264
|
+
return resolveExpiresAtMsFromDurationMs(clampedDelayMs);
|
|
153
265
|
}
|
|
154
|
-
function
|
|
155
|
-
|
|
266
|
+
function readResetAt(response) {
|
|
267
|
+
const resetAfter = readHeaderNumber(response.headers, "X-RateLimit-Reset-After");
|
|
268
|
+
if (resetAfter !== void 0) return resolveRateLimitResetAt(resetAfter * 1e3);
|
|
269
|
+
const reset = readHeaderNumber(response.headers, "X-RateLimit-Reset");
|
|
270
|
+
return reset !== void 0 ? asDateTimestampMs(reset * 1e3) : void 0;
|
|
156
271
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
272
|
+
function appendQuery(path, query) {
|
|
273
|
+
if (!query || Object.keys(query).length === 0) return path;
|
|
274
|
+
const search = new URLSearchParams();
|
|
275
|
+
for (const [key, value] of Object.entries(query)) search.set(key, String(value));
|
|
276
|
+
return `${path}?${search.toString()}`;
|
|
277
|
+
}
|
|
278
|
+
// extensions/discord/src/internal/rest-scheduler.ts
|
|
279
|
+
const MAX_QUEUE_SIZE = 1e3;
|
|
280
|
+
const MAX_CONCURRENT_WORKERS = 4;
|
|
281
|
+
const MAX_RATE_LIMIT_RETRIES = 3;
|
|
282
|
+
const requestPriorities = [
|
|
283
|
+
"critical",
|
|
284
|
+
"standard",
|
|
285
|
+
"background"
|
|
286
|
+
];
|
|
287
|
+
const laneSchedule = [
|
|
288
|
+
"critical",
|
|
289
|
+
"critical",
|
|
290
|
+
"critical",
|
|
291
|
+
"critical",
|
|
292
|
+
"critical",
|
|
293
|
+
"critical",
|
|
294
|
+
"standard",
|
|
295
|
+
"standard",
|
|
296
|
+
"standard",
|
|
297
|
+
"background"
|
|
298
|
+
];
|
|
299
|
+
function countPending(bucket) {
|
|
300
|
+
return requestPriorities.reduce((count, lane) => count + bucket.pending[lane].length, 0);
|
|
301
|
+
}
|
|
302
|
+
var RestScheduler = class {
|
|
303
|
+
constructor(executor) {
|
|
304
|
+
this.executor = executor;
|
|
305
|
+
this.activeWorkers = 0;
|
|
306
|
+
this.buckets = /* @__PURE__ */ new Map();
|
|
307
|
+
this.globalRateLimitUntil = 0;
|
|
308
|
+
this.laneCursor = 0;
|
|
309
|
+
this.queuedByLane = {
|
|
310
|
+
critical: 0,
|
|
311
|
+
standard: 0,
|
|
312
|
+
background: 0
|
|
313
|
+
};
|
|
314
|
+
this.queuedRequests = 0;
|
|
315
|
+
this.routeBuckets = /* @__PURE__ */ new Map();
|
|
163
316
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
317
|
+
enqueue(params) {
|
|
318
|
+
if (this.queuedRequests >= MAX_QUEUE_SIZE) throw new Error("Discord request queue is full");
|
|
319
|
+
const routeKey = createRouteKey(params.method, params.path);
|
|
320
|
+
const bucket = this.getBucket(this.routeBuckets.get(routeKey) ?? routeKey);
|
|
321
|
+
return new Promise((resolve, reject) => {
|
|
322
|
+
this.queuedRequests += 1;
|
|
323
|
+
this.queuedByLane[params.priority] += 1;
|
|
324
|
+
bucket.pending[params.priority].push({
|
|
325
|
+
...params,
|
|
326
|
+
routeKey,
|
|
327
|
+
retryCount: 0,
|
|
328
|
+
resolve,
|
|
329
|
+
reject
|
|
330
|
+
});
|
|
331
|
+
this.drainQueues();
|
|
332
|
+
});
|
|
174
333
|
}
|
|
175
|
-
|
|
176
|
-
|
|
334
|
+
getBucket(key) {
|
|
335
|
+
const existing = this.buckets.get(key);
|
|
336
|
+
if (existing) return existing;
|
|
337
|
+
const bucket = {
|
|
338
|
+
active: 0,
|
|
339
|
+
pending: {
|
|
340
|
+
critical: [],
|
|
341
|
+
standard: [],
|
|
342
|
+
background: []
|
|
343
|
+
},
|
|
344
|
+
resetAt: 0,
|
|
345
|
+
routeKeys: /* @__PURE__ */ new Set([key])
|
|
346
|
+
};
|
|
347
|
+
this.buckets.set(key, bucket);
|
|
348
|
+
return bucket;
|
|
177
349
|
}
|
|
178
|
-
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
const current = existingByKey.get(key);
|
|
188
|
-
if (current && !commandsEqual(current, command)) await this.rest.patch(Routes.applicationCommand(this.params.clientId, current.id), { body: command });
|
|
189
|
-
}
|
|
190
|
-
for (const { command, key } of desiredCommands) {
|
|
191
|
-
if (existingByKey.has(key)) continue;
|
|
192
|
-
try {
|
|
193
|
-
await this.rest.post(Routes.applicationCommands(this.params.clientId), { body: command });
|
|
194
|
-
} catch (error) {
|
|
195
|
-
if (!isApplicationCommandLimitError(error)) throw error;
|
|
196
|
-
await this.rest.put(Routes.applicationCommands(this.params.clientId), { body: desired });
|
|
197
|
-
return;
|
|
350
|
+
bindRouteToBucket(routeKey, bucketKey) {
|
|
351
|
+
const target = this.getBucket(bucketKey);
|
|
352
|
+
target.routeKeys.add(routeKey);
|
|
353
|
+
this.routeBuckets.set(routeKey, bucketKey);
|
|
354
|
+
const routeBucket = this.buckets.get(routeKey);
|
|
355
|
+
if (routeBucket && routeBucket !== target) {
|
|
356
|
+
for (const lane of requestPriorities) {
|
|
357
|
+
target.pending[lane].push(...routeBucket.pending[lane]);
|
|
358
|
+
routeBucket.pending[lane] = [];
|
|
198
359
|
}
|
|
360
|
+
if (routeBucket.active === 0) this.buckets.delete(routeKey);
|
|
199
361
|
}
|
|
200
|
-
|
|
201
|
-
}
|
|
202
|
-
async loadPersistedHash() {
|
|
203
|
-
if (this.hashLoaded) return;
|
|
204
|
-
this.hashLoaded = true;
|
|
205
|
-
try {
|
|
206
|
-
const hash = await this.params.hashStore?.lookup(this.cacheKey);
|
|
207
|
-
if (typeof hash === "string" && hash.trim()) this.hash = hash;
|
|
208
|
-
} catch {}
|
|
209
|
-
}
|
|
210
|
-
get rest() {
|
|
211
|
-
return this.params.rest();
|
|
362
|
+
return target;
|
|
212
363
|
}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
for (const entry of entries) {
|
|
232
|
-
const index = entry.indexOf("=");
|
|
233
|
-
if (index < 0) continue;
|
|
234
|
-
const name = entry.slice(0, index).replace(/^[^:]+:/, "");
|
|
235
|
-
const raw = entry.slice(index + 1);
|
|
236
|
-
data[name] = raw === "true" ? true : raw === "false" ? false : raw;
|
|
364
|
+
recordResponse(routeKey, path, response, parsed) {
|
|
365
|
+
const bucketHeader = readDiscordRateLimitBucket(response);
|
|
366
|
+
const bucket = bucketHeader ? this.bindRouteToBucket(routeKey, createBucketKey(bucketHeader, path)) : this.getBucket(this.routeBuckets.get(routeKey) ?? routeKey);
|
|
367
|
+
const limit = readHeaderNumber(response.headers, "X-RateLimit-Limit");
|
|
368
|
+
if (limit !== void 0) bucket.limit = limit;
|
|
369
|
+
const remaining = readHeaderNumber(response.headers, "X-RateLimit-Remaining");
|
|
370
|
+
if (remaining !== void 0) bucket.remaining = remaining;
|
|
371
|
+
const resetAt = readResetAt(response);
|
|
372
|
+
if (resetAt !== void 0) bucket.resetAt = resetAt;
|
|
373
|
+
if (response.status !== 429) return;
|
|
374
|
+
const retryAt = resolveRateLimitResetAt(Math.max(0, readRetryAfter(parsed, response) * 1e3));
|
|
375
|
+
if (retryAt === void 0) return;
|
|
376
|
+
if (response.headers.get("X-RateLimit-Global") === "true" || isGlobalRateLimit(parsed)) {
|
|
377
|
+
this.globalRateLimitUntil = Math.max(this.globalRateLimitUntil, retryAt);
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
bucket.remaining = 0;
|
|
381
|
+
bucket.resetAt = Math.max(bucket.resetAt, retryAt);
|
|
237
382
|
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
}
|
|
243
|
-
function colorToNumber(value) {
|
|
244
|
-
if (typeof value === "number") return Number.isInteger(value) && value >= 0 && value <= 16777215 ? value : void 0;
|
|
245
|
-
if (typeof value === "string" && /^#?[0-9a-f]{6}$/i.test(value)) return Number.parseInt(value.replace(/^#/, ""), 16);
|
|
246
|
-
}
|
|
247
|
-
var BaseComponent = class {
|
|
248
|
-
constructor() {
|
|
249
|
-
this.isV2 = false;
|
|
383
|
+
getBucketWaitMs(bucket, now) {
|
|
384
|
+
if (bucket.remaining === 0 && bucket.resetAt > now) return bucket.resetAt - now;
|
|
385
|
+
if (bucket.remaining === 0 && bucket.resetAt <= now) bucket.remaining = bucket.limit;
|
|
386
|
+
return 0;
|
|
250
387
|
}
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
this.
|
|
258
|
-
this.customIdParser = parseCustomId;
|
|
388
|
+
scheduleDrain(delayMs = 0) {
|
|
389
|
+
if (this.drainTimer) return;
|
|
390
|
+
this.drainTimer = setTimeout(() => {
|
|
391
|
+
this.drainTimer = void 0;
|
|
392
|
+
this.drainQueues();
|
|
393
|
+
}, resolveTimerTimeoutMs(delayMs, 0, 0));
|
|
394
|
+
this.drainTimer.unref();
|
|
259
395
|
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
396
|
+
drainQueues() {
|
|
397
|
+
while (this.activeWorkers < MAX_CONCURRENT_WORKERS) {
|
|
398
|
+
const next = this.takeNextQueuedRequest();
|
|
399
|
+
if (!next.queued) {
|
|
400
|
+
if (next.waitMs !== void 0 && Number.isFinite(next.waitMs)) this.scheduleDrain(next.waitMs);
|
|
401
|
+
break;
|
|
402
|
+
}
|
|
403
|
+
const { bucket, queued } = next;
|
|
404
|
+
if (bucket.remaining !== void 0 && bucket.remaining > 0) bucket.remaining -= 1;
|
|
405
|
+
bucket.active += 1;
|
|
406
|
+
this.activeWorkers += 1;
|
|
407
|
+
this.runQueuedRequest(queued, bucket);
|
|
408
|
+
}
|
|
268
409
|
}
|
|
269
|
-
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
if (
|
|
410
|
+
takeNextQueuedRequest() {
|
|
411
|
+
const now = Date.now();
|
|
412
|
+
if (this.globalRateLimitUntil > now) return { waitMs: this.globalRateLimitUntil - now };
|
|
413
|
+
for (const [key, bucket] of this.buckets) {
|
|
414
|
+
if (bucket.active !== 0 || countPending(bucket) > 0) continue;
|
|
415
|
+
if (bucket.remaining === 0 && bucket.resetAt > now) continue;
|
|
416
|
+
for (const routeKey of bucket.routeKeys) if (this.routeBuckets.get(routeKey) === key) this.routeBuckets.delete(routeKey);
|
|
417
|
+
this.buckets.delete(key);
|
|
418
|
+
}
|
|
419
|
+
let nextDelayMs;
|
|
420
|
+
const buckets = Array.from(this.buckets.values()).filter((bucket) => countPending(bucket) > 0);
|
|
421
|
+
if (buckets.length === 0) return {};
|
|
422
|
+
for (let laneOffset = 0; laneOffset < laneSchedule.length; laneOffset += 1) {
|
|
423
|
+
const lane = laneSchedule[(this.laneCursor + laneOffset) % laneSchedule.length];
|
|
424
|
+
if (!lane || this.queuedByLane[lane] <= 0) continue;
|
|
425
|
+
for (const bucket of buckets) {
|
|
426
|
+
const queue = bucket.pending[lane];
|
|
427
|
+
if (queue.length === 0 || bucket.active > 0) continue;
|
|
428
|
+
const waitMs = this.getBucketWaitMs(bucket, now);
|
|
429
|
+
if (waitMs > 0) {
|
|
430
|
+
nextDelayMs = Math.min(nextDelayMs ?? waitMs, waitMs);
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
const queued = queue.shift();
|
|
434
|
+
if (!queued) continue;
|
|
435
|
+
this.queuedByLane[lane] = Math.max(0, this.queuedByLane[lane] - 1);
|
|
436
|
+
this.laneCursor = (this.laneCursor + laneOffset + 1) % laneSchedule.length;
|
|
437
|
+
return {
|
|
438
|
+
bucket,
|
|
439
|
+
queued
|
|
440
|
+
};
|
|
441
|
+
}
|
|
275
442
|
}
|
|
443
|
+
return { waitMs: nextDelayMs };
|
|
276
444
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
445
|
+
async runQueuedRequest(queued, bucket) {
|
|
446
|
+
let requeued = false;
|
|
447
|
+
try {
|
|
448
|
+
queued.resolve(await this.executor(queued));
|
|
449
|
+
} catch (error) {
|
|
450
|
+
if (error instanceof RateLimitError && this.requeueRateLimitedRequest(queued)) {
|
|
451
|
+
requeued = true;
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
queued.reject(error);
|
|
455
|
+
} finally {
|
|
456
|
+
bucket.active = Math.max(0, bucket.active - 1);
|
|
457
|
+
this.activeWorkers = Math.max(0, this.activeWorkers - 1);
|
|
458
|
+
if (!requeued) this.queuedRequests = Math.max(0, this.queuedRequests - 1);
|
|
459
|
+
this.drainQueues();
|
|
285
460
|
}
|
|
286
|
-
return this.wildcardEntries.find((entry) => options?.componentType === void 0 || entry.type === options.componentType);
|
|
287
461
|
}
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
462
|
+
requeueRateLimitedRequest(queued) {
|
|
463
|
+
if (queued.retryCount >= MAX_RATE_LIMIT_RETRIES) return false;
|
|
464
|
+
const bucketKey = this.routeBuckets.get(queued.routeKey) ?? queued.routeKey;
|
|
465
|
+
this.getBucket(bucketKey).pending[queued.priority].push({
|
|
466
|
+
...queued,
|
|
467
|
+
retryCount: queued.retryCount + 1
|
|
468
|
+
});
|
|
469
|
+
this.queuedByLane[queued.priority] += 1;
|
|
470
|
+
return true;
|
|
293
471
|
}
|
|
294
472
|
};
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
}
|
|
473
|
+
function isGlobalRateLimit(parsed) {
|
|
474
|
+
return parsed && typeof parsed === "object" && "global" in parsed ? Boolean(parsed.global) : false;
|
|
475
|
+
}
|
|
476
|
+
// extensions/discord/src/internal/schemas.ts
|
|
477
|
+
const discordInteractionPayloadSchema = Type.Object({
|
|
478
|
+
id: Type.String({ minLength: 1 }),
|
|
479
|
+
token: Type.String({ minLength: 1 }),
|
|
480
|
+
type: Type.Number()
|
|
481
|
+
}, { additionalProperties: true });
|
|
482
|
+
const discordRateLimitBodySchema = Type.Object({
|
|
483
|
+
message: Type.Optional(Type.String()),
|
|
484
|
+
retry_after: Type.Optional(Type.Union([Type.Number(), Type.String()])),
|
|
485
|
+
global: Type.Optional(Type.Boolean()),
|
|
486
|
+
code: Type.Optional(Type.Union([Type.Number(), Type.String()]))
|
|
487
|
+
}, { additionalProperties: true });
|
|
488
|
+
function assertDiscordInteractionPayload(value) {
|
|
489
|
+
if (!Check(discordInteractionPayloadSchema, value)) throw new Error("Invalid Discord interaction payload");
|
|
490
|
+
}
|
|
491
|
+
function isDiscordRateLimitBody(value) {
|
|
492
|
+
return Check(discordRateLimitBodySchema, value);
|
|
493
|
+
}
|
|
494
|
+
// extensions/discord/src/internal/rest.ts
|
|
495
|
+
const DISCORD_REST_TIMEOUT_MS = 15e3;
|
|
496
|
+
const defaultOptions = {
|
|
497
|
+
baseUrl: "https://discord.com/api",
|
|
498
|
+
timeout: DISCORD_REST_TIMEOUT_MS,
|
|
499
|
+
queueRequests: true
|
|
301
500
|
};
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
501
|
+
const DISCORD_REST_RESPONSE_BODY_MAX_BYTES = 8388608;
|
|
502
|
+
const GZIP_MAGIC = [31, 139];
|
|
503
|
+
function createResponseBodyOverflowError(size) {
|
|
504
|
+
return /* @__PURE__ */ new Error(`Discord REST response body exceeds ${DISCORD_REST_RESPONSE_BODY_MAX_BYTES} bytes (received ${size})`);
|
|
505
|
+
}
|
|
506
|
+
async function readResponseBodyText(response, idleTimeoutMs) {
|
|
507
|
+
const buffer = await readResponseWithLimit(response, DISCORD_REST_RESPONSE_BODY_MAX_BYTES, {
|
|
508
|
+
chunkTimeoutMs: idleTimeoutMs,
|
|
509
|
+
onOverflow: ({ size }) => createResponseBodyOverflowError(size),
|
|
510
|
+
onIdleTimeout: ({ chunkTimeoutMs }) => /* @__PURE__ */ new Error(`Discord REST response stalled: no data received for ${chunkTimeoutMs}ms`)
|
|
511
|
+
});
|
|
512
|
+
if (!buffer.byteLength) return "";
|
|
513
|
+
if (buffer[0] === GZIP_MAGIC[0] && buffer[1] === GZIP_MAGIC[1]) try {
|
|
514
|
+
return gunzipSync(buffer, { maxOutputLength: DISCORD_REST_RESPONSE_BODY_MAX_BYTES }).toString("utf8");
|
|
515
|
+
} catch (err) {
|
|
516
|
+
if (err instanceof RangeError && "code" in err && err.code === "ERR_BUFFER_TOO_LARGE") throw createResponseBodyOverflowError("decompressed output");
|
|
517
|
+
throw err;
|
|
309
518
|
}
|
|
310
|
-
|
|
311
|
-
|
|
519
|
+
return buffer.toString("utf8");
|
|
520
|
+
}
|
|
521
|
+
function coerceResponseBody(raw) {
|
|
522
|
+
if (!raw) return;
|
|
523
|
+
try {
|
|
524
|
+
return JSON.parse(raw);
|
|
525
|
+
} catch {
|
|
526
|
+
return raw;
|
|
312
527
|
}
|
|
313
|
-
|
|
314
|
-
|
|
528
|
+
}
|
|
529
|
+
var RequestClient = class {
|
|
530
|
+
constructor(token, options) {
|
|
531
|
+
const endpoint = getDiscordEndpointRuntime();
|
|
532
|
+
const resolvedOptions = endpoint ? {
|
|
533
|
+
...options,
|
|
534
|
+
apiBaseUrl: endpoint.descriptor.restApiBaseUrl,
|
|
535
|
+
fetch: endpoint.fetch
|
|
536
|
+
} : options;
|
|
537
|
+
this.token = token.replace(/^Bot\s+/i, "");
|
|
538
|
+
this.customFetch = resolvedOptions?.fetch;
|
|
539
|
+
this.guardedEndpoint = endpoint !== void 0;
|
|
540
|
+
this.options = normalizeRequestClientOptions(resolvedOptions);
|
|
541
|
+
this.scheduler = new RestScheduler(async (request) => await this.executeRequest(request.method, request.path, {
|
|
542
|
+
data: request.data?.data,
|
|
543
|
+
query: request.query
|
|
544
|
+
}, request.routeKey, request.data?.assertCurrent, request.data?.effect));
|
|
315
545
|
}
|
|
316
|
-
get
|
|
317
|
-
return this.
|
|
546
|
+
async get(path, query) {
|
|
547
|
+
return await this.request("GET", path, { query });
|
|
318
548
|
}
|
|
319
|
-
|
|
320
|
-
return this.
|
|
549
|
+
async post(path, data, query) {
|
|
550
|
+
return await this.request("POST", path, {
|
|
551
|
+
data,
|
|
552
|
+
query
|
|
553
|
+
});
|
|
321
554
|
}
|
|
322
|
-
|
|
323
|
-
return this.
|
|
555
|
+
async patch(path, data, query) {
|
|
556
|
+
return await this.request("PATCH", path, {
|
|
557
|
+
data,
|
|
558
|
+
query
|
|
559
|
+
});
|
|
324
560
|
}
|
|
325
|
-
async
|
|
326
|
-
return this.
|
|
561
|
+
async put(path, data, query) {
|
|
562
|
+
return await this.request("PUT", path, {
|
|
563
|
+
data,
|
|
564
|
+
query
|
|
565
|
+
});
|
|
327
566
|
}
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
567
|
+
async delete(path, data, query) {
|
|
568
|
+
return await this.request("DELETE", path, {
|
|
569
|
+
data,
|
|
570
|
+
query
|
|
571
|
+
});
|
|
332
572
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
573
|
+
async request(method, path, params) {
|
|
574
|
+
const routeKey = createRouteKey(method, path);
|
|
575
|
+
const assertActionAuthority = captureDiscordRequestAuthority();
|
|
576
|
+
const assertReadAuthority = captureChannelReadAuthority();
|
|
577
|
+
const effect = captureEffectAuthority();
|
|
578
|
+
const assertCurrent = assertActionAuthority ? () => {
|
|
579
|
+
assertActionAuthority();
|
|
580
|
+
assertReadAuthority?.();
|
|
581
|
+
} : assertReadAuthority;
|
|
582
|
+
assertCurrent?.();
|
|
583
|
+
if (!this.options.queueRequests) return await this.executeRequest(method, path, params, routeKey, assertCurrent, effect);
|
|
584
|
+
return await this.scheduler.enqueue({
|
|
585
|
+
method,
|
|
586
|
+
path,
|
|
587
|
+
priority: getRequestPriority(method, path),
|
|
588
|
+
query: params.query,
|
|
589
|
+
data: {
|
|
590
|
+
data: params.data,
|
|
591
|
+
assertCurrent,
|
|
592
|
+
effect
|
|
593
|
+
}
|
|
594
|
+
});
|
|
337
595
|
}
|
|
338
|
-
|
|
339
|
-
|
|
596
|
+
async executeRequest(method, path, params, routeKey = createRouteKey(method, path), assertCurrent, effect = captureEffectAuthority()) {
|
|
597
|
+
const url = `${this.options.apiBaseUrl}${appendQuery(path, params.query)}`;
|
|
598
|
+
const headers = new Headers({ "User-Agent": "OpenClaw Discord" });
|
|
599
|
+
if (this.token !== "webhook") headers.set("Authorization", `Bot ${this.token}`);
|
|
600
|
+
const body = serializeRequestBody(params.data, headers);
|
|
601
|
+
const controller = new AbortController();
|
|
602
|
+
const timeout = setTimeout(() => controller.abort(), this.options.timeout).unref();
|
|
603
|
+
const signal = this.options.signal ? AbortSignal.any([this.options.signal, controller.signal]) : controller.signal;
|
|
604
|
+
try {
|
|
605
|
+
assertCurrent?.();
|
|
606
|
+
const init = {
|
|
607
|
+
method,
|
|
608
|
+
headers,
|
|
609
|
+
body,
|
|
610
|
+
signal
|
|
611
|
+
};
|
|
612
|
+
const request = () => {
|
|
613
|
+
assertCurrent?.();
|
|
614
|
+
return this.customFetch && assertCurrent ? this.customFetch(url, init, assertCurrent) : (this.customFetch ?? fetch)(url, init);
|
|
615
|
+
};
|
|
616
|
+
const response = this.guardedEndpoint ? await effect.run(request) : await effect.initiate(request);
|
|
617
|
+
const parsed = coerceResponseBody(await readResponseBodyText(response, this.options.timeout).catch((error) => {
|
|
618
|
+
if (response.ok) throw error;
|
|
619
|
+
return "";
|
|
620
|
+
}));
|
|
621
|
+
this.scheduler.recordResponse(routeKey, path, response, parsed);
|
|
622
|
+
if (response.status === 204) return;
|
|
623
|
+
if (response.status === 429) {
|
|
624
|
+
const rateLimitBody = isDiscordRateLimitBody(parsed) ? parsed : void 0;
|
|
625
|
+
throw new RateLimitError(response, {
|
|
626
|
+
message: readDiscordMessage(rateLimitBody, "Rate limited"),
|
|
627
|
+
retry_after: readRetryAfter(rateLimitBody, response),
|
|
628
|
+
code: readDiscordCode(rateLimitBody),
|
|
629
|
+
global: Boolean(rateLimitBody?.global)
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
if (!response.ok) throw new DiscordError(response, parsed);
|
|
633
|
+
return parsed;
|
|
634
|
+
} finally {
|
|
635
|
+
clearTimeout(timeout);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
function normalizeRequestClientOptions(options) {
|
|
640
|
+
const merged = {
|
|
641
|
+
...defaultOptions,
|
|
642
|
+
...options
|
|
643
|
+
};
|
|
644
|
+
return {
|
|
645
|
+
...merged,
|
|
646
|
+
apiBaseUrl: options?.apiBaseUrl ?? `${options?.baseUrl ?? defaultOptions.baseUrl}/v10`,
|
|
647
|
+
timeout: clampTimerTimeoutMs(merged.timeout, 1) ?? resolveTimerTimeoutMs(defaultOptions.timeout, 1)
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
function getRequestPriority(method, path) {
|
|
651
|
+
const normalizedMethod = method.toUpperCase();
|
|
652
|
+
const normalizedPath = path.toLowerCase();
|
|
653
|
+
if (/^\/interactions\/\d+\/[^/]+\/callback$/.test(normalizedPath)) return "critical";
|
|
654
|
+
return normalizedMethod === "GET" ? "background" : "standard";
|
|
655
|
+
}
|
|
656
|
+
// extensions/discord/src/internal/api.guild.ts
|
|
657
|
+
const discordGuildEmojiListSchema = Type.Array(Type.Object({
|
|
658
|
+
id: Type.Union([Type.String(), Type.Null()]),
|
|
659
|
+
name: Type.Union([Type.String(), Type.Null()]),
|
|
660
|
+
animated: Type.Optional(Type.Boolean())
|
|
661
|
+
}, { additionalProperties: true }));
|
|
662
|
+
async function getGuild(rest, guildId) {
|
|
663
|
+
return await rest.get(Routes.guild(guildId));
|
|
664
|
+
}
|
|
665
|
+
function guildUserRead(route) {
|
|
666
|
+
return async (rest, guildId, userId) => await rest.get(Routes[route](guildId, userId));
|
|
667
|
+
}
|
|
668
|
+
const getGuildMember = guildUserRead("guildMember");
|
|
669
|
+
const getGuildVoiceState = guildUserRead("guildVoiceState");
|
|
670
|
+
async function listGuildEmojis(rest, guildId) {
|
|
671
|
+
const emojis = await rest.get(Routes.guildEmojis(guildId));
|
|
672
|
+
if (!Check(discordGuildEmojiListSchema, emojis)) throw new Error("Invalid Discord guild emoji response.");
|
|
673
|
+
return emojis;
|
|
674
|
+
}
|
|
675
|
+
// extensions/discord/src/internal/api.messages.ts
|
|
676
|
+
function normalizeDiscordMessageId(messageId) {
|
|
677
|
+
const normalized = messageId.trim();
|
|
678
|
+
if (!/^[0-9]+$/u.test(normalized)) throw new Error("Invalid Discord message ID. Expected decimal digits.");
|
|
679
|
+
return normalized;
|
|
680
|
+
}
|
|
681
|
+
async function getChannel(rest, channelId) {
|
|
682
|
+
return await rest.get(Routes.channel(channelId));
|
|
683
|
+
}
|
|
684
|
+
async function createChannelMessage(rest, channelId, data) {
|
|
685
|
+
return await rest.post(Routes.channelMessages(channelId), data);
|
|
686
|
+
}
|
|
687
|
+
async function getThreadMember(rest, threadId, userId) {
|
|
688
|
+
return await rest.get(Routes.threadMembers(threadId, userId));
|
|
689
|
+
}
|
|
690
|
+
async function getChannelMessage(rest, channelId, messageId) {
|
|
691
|
+
return await rest.get(Routes.channelMessage(channelId, normalizeDiscordMessageId(messageId)));
|
|
692
|
+
}
|
|
693
|
+
async function editChannelMessage(rest, channelId, messageId, data) {
|
|
694
|
+
return await rest.patch(Routes.channelMessage(channelId, normalizeDiscordMessageId(messageId)), data);
|
|
695
|
+
}
|
|
696
|
+
function messageMutation(method, route) {
|
|
697
|
+
return async (rest, channelId, messageId) => {
|
|
698
|
+
await rest[method](Routes[route](channelId, normalizeDiscordMessageId(messageId)));
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
const deleteChannelMessage = messageMutation("delete", "channelMessage");
|
|
702
|
+
const pinChannelMessage = messageMutation("put", "channelMessagesPin");
|
|
703
|
+
const unpinChannelMessage = messageMutation("delete", "channelMessagesPin");
|
|
704
|
+
async function createThread(rest, channelId, data, messageId) {
|
|
705
|
+
const route = messageId === void 0 ? Routes.threads(channelId) : Routes.threads(channelId, normalizeDiscordMessageId(messageId));
|
|
706
|
+
return await rest.post(route, data);
|
|
707
|
+
}
|
|
708
|
+
// extensions/discord/src/internal/api.reactions.ts
|
|
709
|
+
function ownReactionMutation(method) {
|
|
710
|
+
return async (rest, channelId, messageId, encodedEmoji) => {
|
|
711
|
+
await rest[method](Routes.channelMessageOwnReaction(channelId, normalizeDiscordMessageId(messageId), encodedEmoji));
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
const createOwnMessageReaction = ownReactionMutation("put");
|
|
715
|
+
const deleteOwnMessageReaction = ownReactionMutation("delete");
|
|
716
|
+
async function listMessageReactionUsers(rest, channelId, messageId, encodedEmoji, query) {
|
|
717
|
+
return await rest.get(Routes.channelMessageReaction(channelId, normalizeDiscordMessageId(messageId), encodedEmoji), query);
|
|
718
|
+
}
|
|
719
|
+
// extensions/discord/src/internal/api.users.ts
|
|
720
|
+
async function getCurrentUser(rest) {
|
|
721
|
+
return await rest.get(Routes.user("@me"));
|
|
722
|
+
}
|
|
723
|
+
async function getUser(rest, userId) {
|
|
724
|
+
return await rest.get(Routes.user(userId));
|
|
725
|
+
}
|
|
726
|
+
async function createUserDmChannel(rest, recipientId) {
|
|
727
|
+
return await rest.post(Routes.userChannels(), { body: { recipient_id: recipientId } });
|
|
728
|
+
}
|
|
729
|
+
// extensions/discord/src/internal/commands.ts
|
|
730
|
+
async function deferCommandInteractionIfNeeded(command, interaction) {
|
|
731
|
+
if (!command.defer) return;
|
|
732
|
+
await interaction.defer({ ephemeral: command.ephemeral });
|
|
733
|
+
}
|
|
734
|
+
function readRawCommandOptions(interaction) {
|
|
735
|
+
const options = interaction.rawData.data?.options;
|
|
736
|
+
return Array.isArray(options) ? options : [];
|
|
737
|
+
}
|
|
738
|
+
function findSelectedSubcommand(subcommands, interaction) {
|
|
739
|
+
const subcommandName = readRawCommandOptions(interaction).find((option) => option.type === ApplicationCommandOptionType.Subcommand)?.name;
|
|
740
|
+
return typeof subcommandName === "string" ? subcommands.find((command) => command.name === subcommandName) : void 0;
|
|
741
|
+
}
|
|
742
|
+
function resolveFocusedCommandOptionAutocompleteHandler(command, interaction) {
|
|
743
|
+
const focusedName = interaction.options.getFocused()?.name;
|
|
744
|
+
const options = command.commandKind === "group" ? findSelectedSubcommand(command.subcommands, interaction)?.options : command.options;
|
|
745
|
+
const option = focusedName ? options?.find((candidate) => candidate.name === focusedName) : void 0;
|
|
746
|
+
if (option?.type === ApplicationCommandOptionType.String || option?.type === ApplicationCommandOptionType.Integer || option?.type === ApplicationCommandOptionType.Number) return typeof option.autocomplete === "function" ? option.autocomplete : void 0;
|
|
747
|
+
}
|
|
748
|
+
var BaseCommand = class {
|
|
749
|
+
constructor() {
|
|
750
|
+
this.defer = false;
|
|
751
|
+
this.ephemeral = false;
|
|
752
|
+
this.type = ApplicationCommandType.ChatInput;
|
|
753
|
+
}
|
|
754
|
+
serialize() {
|
|
755
|
+
return stripUndefinedFields({
|
|
756
|
+
name: this.name,
|
|
757
|
+
description: this.description ?? "",
|
|
758
|
+
description_localizations: this.descriptionLocalizations,
|
|
759
|
+
type: this.type,
|
|
760
|
+
options: this.serializeOptions(),
|
|
761
|
+
integration_types: [0, 1],
|
|
762
|
+
contexts: [
|
|
763
|
+
InteractionContextType.Guild,
|
|
764
|
+
InteractionContextType.BotDM,
|
|
765
|
+
InteractionContextType.PrivateChannel
|
|
766
|
+
],
|
|
767
|
+
default_member_permissions: null
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
var Command = class extends BaseCommand {
|
|
772
|
+
constructor(..._args) {
|
|
773
|
+
super(..._args);
|
|
774
|
+
this.commandKind = "leaf";
|
|
775
|
+
}
|
|
776
|
+
async autocomplete(interaction) {
|
|
777
|
+
throw new Error(`The ${interaction.rawData?.data?.name ?? this.name} command does not support autocomplete`);
|
|
778
|
+
}
|
|
779
|
+
serializeOptions() {
|
|
780
|
+
return this.options?.map((option) => {
|
|
781
|
+
const type = option.type;
|
|
782
|
+
if ((type === ApplicationCommandOptionType.String || type === ApplicationCommandOptionType.Integer || type === ApplicationCommandOptionType.Number) && typeof option.autocomplete === "function") {
|
|
783
|
+
const { autocomplete: _autocomplete, ...rest } = option;
|
|
784
|
+
return {
|
|
785
|
+
...rest,
|
|
786
|
+
autocomplete: true
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
return option;
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
var CommandWithSubcommands = class extends BaseCommand {
|
|
794
|
+
constructor(..._args2) {
|
|
795
|
+
super(..._args2);
|
|
796
|
+
this.commandKind = "group";
|
|
797
|
+
}
|
|
798
|
+
async run(interaction) {
|
|
799
|
+
const subcommand = findSelectedSubcommand(this.subcommands, interaction);
|
|
800
|
+
if (!subcommand) {
|
|
801
|
+
const subcommandName = readRawCommandOptions(interaction).find((option) => option.type === ApplicationCommandOptionType.Subcommand)?.name;
|
|
802
|
+
throw new Error(`Unknown Discord subcommand: ${typeof subcommandName === "string" ? subcommandName : "<missing>"}`);
|
|
803
|
+
}
|
|
804
|
+
await deferCommandInteractionIfNeeded(subcommand, interaction);
|
|
805
|
+
return await subcommand.run(interaction);
|
|
806
|
+
}
|
|
807
|
+
serializeOptions() {
|
|
808
|
+
return this.subcommands.map((command) => stripUndefinedFields({
|
|
809
|
+
name: command.name,
|
|
810
|
+
description: command.description ?? "",
|
|
811
|
+
description_localizations: command.descriptionLocalizations,
|
|
812
|
+
type: ApplicationCommandOptionType.Subcommand,
|
|
813
|
+
options: command.serializeOptions()
|
|
814
|
+
}));
|
|
815
|
+
}
|
|
816
|
+
};
|
|
817
|
+
// extensions/discord/src/internal/structures.ts
|
|
818
|
+
var Base = class {
|
|
819
|
+
constructor(client) {
|
|
820
|
+
this.client = client;
|
|
821
|
+
}
|
|
822
|
+
};
|
|
823
|
+
var PartialEntity = class extends Base {
|
|
824
|
+
constructor(client, rawDataOrId) {
|
|
825
|
+
super(client);
|
|
826
|
+
this.rawDataValue = typeof rawDataOrId === "string" ? null : rawDataOrId;
|
|
827
|
+
this.id = typeof rawDataOrId === "string" ? rawDataOrId : rawDataOrId.id;
|
|
828
|
+
}
|
|
829
|
+
};
|
|
830
|
+
var User = class extends PartialEntity {
|
|
831
|
+
get username() {
|
|
832
|
+
return this.rawDataValue?.username ?? "";
|
|
833
|
+
}
|
|
834
|
+
get globalName() {
|
|
835
|
+
return this.rawDataValue?.global_name;
|
|
836
|
+
}
|
|
837
|
+
get discriminator() {
|
|
838
|
+
return this.rawDataValue?.discriminator;
|
|
839
|
+
}
|
|
840
|
+
get bot() {
|
|
841
|
+
return this.rawDataValue?.bot;
|
|
842
|
+
}
|
|
843
|
+
get avatar() {
|
|
844
|
+
return this.rawDataValue?.avatar;
|
|
845
|
+
}
|
|
846
|
+
};
|
|
847
|
+
var Role = class extends PartialEntity {
|
|
848
|
+
get name() {
|
|
849
|
+
return this.rawDataValue?.name ?? "";
|
|
850
|
+
}
|
|
851
|
+
};
|
|
852
|
+
var Guild = class extends PartialEntity {
|
|
853
|
+
get name() {
|
|
854
|
+
return this.rawDataValue?.name ?? "";
|
|
855
|
+
}
|
|
856
|
+
get icon() {
|
|
857
|
+
return this.rawDataValue?.icon;
|
|
340
858
|
}
|
|
341
859
|
};
|
|
342
860
|
var GuildMember = class extends Base {
|
|
@@ -402,6 +920,9 @@ var Message = class Message extends Base {
|
|
|
402
920
|
get embeds() {
|
|
403
921
|
return this.rawDataValue?.embeds ?? [];
|
|
404
922
|
}
|
|
923
|
+
get components() {
|
|
924
|
+
return this.rawDataValue?.components;
|
|
925
|
+
}
|
|
405
926
|
get attachments() {
|
|
406
927
|
return this.rawDataValue?.attachments ?? [];
|
|
407
928
|
}
|
|
@@ -447,304 +968,23 @@ function channelFactory(clientForTest, channelData) {
|
|
|
447
968
|
ownerId: "owner_id" in channelData ? channelData.owner_id : void 0
|
|
448
969
|
};
|
|
449
970
|
}
|
|
450
|
-
// extensions/discord/src/internal/
|
|
451
|
-
|
|
452
|
-
const
|
|
453
|
-
|
|
454
|
-
const
|
|
455
|
-
|
|
456
|
-
[GatewayDispatchEvents.ChannelDelete, "channel"],
|
|
457
|
-
[GatewayDispatchEvents.ThreadUpdate, "channel"],
|
|
458
|
-
[GatewayDispatchEvents.ThreadDelete, "channel"],
|
|
459
|
-
[GatewayDispatchEvents.GuildUpdate, "guild"],
|
|
460
|
-
[GatewayDispatchEvents.GuildEmojisUpdate, "guild-emojis"],
|
|
461
|
-
[GatewayDispatchEvents.GuildMemberAdd, "member"],
|
|
462
|
-
[GatewayDispatchEvents.GuildMemberRemove, "member"],
|
|
463
|
-
[GatewayDispatchEvents.GuildMemberUpdate, "member"]
|
|
464
|
-
]);
|
|
465
|
-
var DiscordEntityCache = class {
|
|
466
|
-
constructor(params) {
|
|
467
|
-
this.params = params;
|
|
468
|
-
this.entries = /* @__PURE__ */ new Map();
|
|
469
|
-
this.lastSweepAt = 0;
|
|
470
|
-
}
|
|
471
|
-
get size() {
|
|
472
|
-
return this.entries.size;
|
|
971
|
+
// extensions/discord/src/internal/interaction-options.ts
|
|
972
|
+
function findOption(options, matches) {
|
|
973
|
+
for (const option of options ?? []) {
|
|
974
|
+
if (matches(option)) return option;
|
|
975
|
+
const child = "options" in option && Array.isArray(option.options) ? findOption(option.options, matches) : void 0;
|
|
976
|
+
if (child) return child;
|
|
473
977
|
}
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
978
|
+
}
|
|
979
|
+
var OptionsHandler = class {
|
|
980
|
+
constructor(rawOptions, client, resolvedChannels) {
|
|
981
|
+
this.rawOptions = rawOptions;
|
|
982
|
+
this.client = client;
|
|
983
|
+
this.resolvedChannels = resolvedChannels;
|
|
479
984
|
}
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
return channelFactory(this.params.client, raw);
|
|
484
|
-
});
|
|
485
|
-
}
|
|
486
|
-
async fetchGuild(id) {
|
|
487
|
-
return await this.fetchCached(`guild:${id}`, async () => {
|
|
488
|
-
const raw = await getGuild(this.params.rest(), id);
|
|
489
|
-
return new Guild(this.params.client, raw);
|
|
490
|
-
});
|
|
491
|
-
}
|
|
492
|
-
async fetchMember(guildId, userId) {
|
|
493
|
-
return await this.fetchCached(`member:${guildId}:${userId}`, async () => {
|
|
494
|
-
const raw = await getGuildMember(this.params.rest(), guildId, userId);
|
|
495
|
-
return new GuildMember(this.params.client, raw);
|
|
496
|
-
});
|
|
497
|
-
}
|
|
498
|
-
async fetchGuildEmojis(guildId, fetcher) {
|
|
499
|
-
return await this.fetchCached(`guild-emojis:${guildId}`, fetcher);
|
|
500
|
-
}
|
|
501
|
-
invalidateForGatewayEvent(type, data) {
|
|
502
|
-
const kind = CACHE_KIND_BY_EVENT.get(type);
|
|
503
|
-
if (!kind) return;
|
|
504
|
-
const raw = data && typeof data === "object" ? data : {};
|
|
505
|
-
if (kind === "member") {
|
|
506
|
-
const guildId = raw.guild_id;
|
|
507
|
-
const user = raw.user && typeof raw.user === "object" ? raw.user : {};
|
|
508
|
-
if (typeof guildId === "string" && typeof user.id === "string") {
|
|
509
|
-
this.entries.delete(`member:${guildId}:${user.id}`);
|
|
510
|
-
this.entries.delete(`user:${user.id}`);
|
|
511
|
-
}
|
|
512
|
-
} else {
|
|
513
|
-
const id = kind === "guild-emojis" ? raw.guild_id : raw.id;
|
|
514
|
-
if (typeof id === "string") this.entries.delete(`${kind}:${id}`);
|
|
515
|
-
}
|
|
516
|
-
}
|
|
517
|
-
async fetchCached(key, fetcher) {
|
|
518
|
-
const now = Date.now();
|
|
519
|
-
const cached = this.entries.get(key);
|
|
520
|
-
if (cached && cached.expiresAt > now) return cached.value;
|
|
521
|
-
if (cached) this.entries.delete(key);
|
|
522
|
-
const value = await fetcher();
|
|
523
|
-
this.maybeSweepExpired(now);
|
|
524
|
-
this.entries.set(key, {
|
|
525
|
-
expiresAt: now + DEFAULT_REST_CACHE_TTL_MS,
|
|
526
|
-
value
|
|
527
|
-
});
|
|
528
|
-
if (this.entries.size > DEFAULT_MAX_ENTRIES) this.entries.delete(this.entries.keys().next().value);
|
|
529
|
-
return value;
|
|
530
|
-
}
|
|
531
|
-
maybeSweepExpired(now) {
|
|
532
|
-
if (now - this.lastSweepAt < DEFAULT_SWEEP_INTERVAL_MS) return;
|
|
533
|
-
this.lastSweepAt = now;
|
|
534
|
-
for (const [key, entry] of this.entries) if (entry.expiresAt <= now) this.entries.delete(key);
|
|
535
|
-
}
|
|
536
|
-
};
|
|
537
|
-
// extensions/discord/src/internal/event-queue.ts
|
|
538
|
-
const DEFAULT_MAX_QUEUE_SIZE = 1e4;
|
|
539
|
-
const DEFAULT_MAX_CONCURRENCY = 50;
|
|
540
|
-
const DEFAULT_LISTENER_TIMEOUT_MS = 12e4;
|
|
541
|
-
const DEFAULT_SLOW_LISTENER_THRESHOLD_MS = 3e4;
|
|
542
|
-
var DiscordEventQueue = class {
|
|
543
|
-
constructor(options = {}) {
|
|
544
|
-
this.queue = [];
|
|
545
|
-
this.queueHead = 0;
|
|
546
|
-
this.processing = 0;
|
|
547
|
-
this.processedCount = 0;
|
|
548
|
-
this.droppedCount = 0;
|
|
549
|
-
this.timeoutCount = 0;
|
|
550
|
-
this.options = {
|
|
551
|
-
maxQueueSize: normalizePositiveInteger(options.maxQueueSize, DEFAULT_MAX_QUEUE_SIZE),
|
|
552
|
-
maxConcurrency: normalizePositiveInteger(options.maxConcurrency, DEFAULT_MAX_CONCURRENCY),
|
|
553
|
-
listenerTimeout: normalizePositiveInteger(options.listenerTimeout, DEFAULT_LISTENER_TIMEOUT_MS),
|
|
554
|
-
slowListenerThreshold: normalizePositiveInteger(options.slowListenerThreshold, DEFAULT_SLOW_LISTENER_THRESHOLD_MS)
|
|
555
|
-
};
|
|
556
|
-
}
|
|
557
|
-
enqueue(params) {
|
|
558
|
-
if (this.pendingQueueSize >= this.options.maxQueueSize) {
|
|
559
|
-
this.droppedCount += 1;
|
|
560
|
-
return Promise.reject(/* @__PURE__ */ new Error(`Discord event queue is full for ${params.eventType}; maxQueueSize=${this.options.maxQueueSize}`));
|
|
561
|
-
}
|
|
562
|
-
return new Promise((resolve, reject) => {
|
|
563
|
-
this.queue.push({
|
|
564
|
-
...params,
|
|
565
|
-
resolve,
|
|
566
|
-
reject
|
|
567
|
-
});
|
|
568
|
-
this.processNext();
|
|
569
|
-
});
|
|
570
|
-
}
|
|
571
|
-
getMetrics() {
|
|
572
|
-
return {
|
|
573
|
-
queueSize: this.pendingQueueSize,
|
|
574
|
-
processing: this.processing,
|
|
575
|
-
processed: this.processedCount,
|
|
576
|
-
dropped: this.droppedCount,
|
|
577
|
-
timeouts: this.timeoutCount,
|
|
578
|
-
maxQueueSize: this.options.maxQueueSize,
|
|
579
|
-
maxConcurrency: this.options.maxConcurrency
|
|
580
|
-
};
|
|
581
|
-
}
|
|
582
|
-
get pendingQueueSize() {
|
|
583
|
-
return Math.max(0, this.queue.length - this.queueHead);
|
|
584
|
-
}
|
|
585
|
-
takeNextJob() {
|
|
586
|
-
const job = this.queue[this.queueHead];
|
|
587
|
-
this.queueHead += 1;
|
|
588
|
-
if (this.queueHead >= this.queue.length) {
|
|
589
|
-
this.queue.length = 0;
|
|
590
|
-
this.queueHead = 0;
|
|
591
|
-
} else if (this.queueHead > 256 && this.queueHead * 2 > this.queue.length) {
|
|
592
|
-
this.queue.splice(0, this.queueHead);
|
|
593
|
-
this.queueHead = 0;
|
|
594
|
-
}
|
|
595
|
-
return job;
|
|
596
|
-
}
|
|
597
|
-
processNext() {
|
|
598
|
-
while (this.processing < this.options.maxConcurrency && this.pendingQueueSize > 0) {
|
|
599
|
-
const job = this.takeNextJob();
|
|
600
|
-
if (!job) return;
|
|
601
|
-
this.processing += 1;
|
|
602
|
-
const listenerPromise = Promise.resolve().then(() => job.run());
|
|
603
|
-
const runJobPromise = this.runJob(job, listenerPromise);
|
|
604
|
-
runJobPromise.then(job.resolve, job.reject).finally(() => {
|
|
605
|
-
this.processedCount += 1;
|
|
606
|
-
});
|
|
607
|
-
Promise.allSettled([runJobPromise, listenerPromise]).then(([dispatchResult, listenerResult]) => {
|
|
608
|
-
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);
|
|
609
|
-
this.processing -= 1;
|
|
610
|
-
this.processNext();
|
|
611
|
-
});
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
async runJob(job, listenerPromise) {
|
|
615
|
-
const startedAt = Date.now();
|
|
616
|
-
try {
|
|
617
|
-
await raceWithTimeout(listenerPromise, this.options.listenerTimeout, () => {
|
|
618
|
-
const error = /* @__PURE__ */ new Error(`Listener timeout after ${this.options.listenerTimeout}ms`);
|
|
619
|
-
error.name = "DiscordEventQueueListenerTimeoutError";
|
|
620
|
-
throw error;
|
|
621
|
-
}, { ref: false });
|
|
622
|
-
this.logSlowListener(job, Date.now() - startedAt);
|
|
623
|
-
return "completed";
|
|
624
|
-
} catch (error) {
|
|
625
|
-
if (error instanceof Error && error.name === "DiscordEventQueueListenerTimeoutError") {
|
|
626
|
-
this.timeoutCount += 1;
|
|
627
|
-
console.error(`[EventQueue] Listener ${job.listenerName} timed out after ${this.options.listenerTimeout}ms for event ${job.eventType}`);
|
|
628
|
-
return "timed-out";
|
|
629
|
-
}
|
|
630
|
-
console.error(`[EventQueue] Listener ${job.listenerName} failed for event ${job.eventType}:`, error);
|
|
631
|
-
return "failed";
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
logSlowListener(job, durationMs) {
|
|
635
|
-
if (durationMs < this.options.slowListenerThreshold) return;
|
|
636
|
-
console.warn(`[EventQueue] Slow listener detected: ${job.listenerName} took ${durationMs}ms for event ${job.eventType}`);
|
|
637
|
-
}
|
|
638
|
-
};
|
|
639
|
-
function normalizePositiveInteger(value, fallback) {
|
|
640
|
-
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return fallback;
|
|
641
|
-
return Math.max(1, Math.floor(value));
|
|
642
|
-
}
|
|
643
|
-
// extensions/discord/src/internal/commands.ts
|
|
644
|
-
async function deferCommandInteractionIfNeeded(command, interaction) {
|
|
645
|
-
if (!command.defer) return;
|
|
646
|
-
await interaction.defer({ ephemeral: command.ephemeral });
|
|
647
|
-
}
|
|
648
|
-
function readRawCommandOptions(interaction) {
|
|
649
|
-
const options = interaction.rawData.data?.options;
|
|
650
|
-
return Array.isArray(options) ? options : [];
|
|
651
|
-
}
|
|
652
|
-
function findSelectedSubcommand(subcommands, interaction) {
|
|
653
|
-
const subcommandName = readRawCommandOptions(interaction).find((option) => option.type === ApplicationCommandOptionType.Subcommand)?.name;
|
|
654
|
-
return typeof subcommandName === "string" ? subcommands.find((command) => command.name === subcommandName) : void 0;
|
|
655
|
-
}
|
|
656
|
-
function resolveFocusedCommandOptionAutocompleteHandler(command, interaction) {
|
|
657
|
-
const focusedName = interaction.options.getFocused()?.name;
|
|
658
|
-
const options = command.commandKind === "group" ? findSelectedSubcommand(command.subcommands, interaction)?.options : command.options;
|
|
659
|
-
const option = focusedName ? options?.find((candidate) => candidate.name === focusedName) : void 0;
|
|
660
|
-
if (option?.type === ApplicationCommandOptionType.String || option?.type === ApplicationCommandOptionType.Integer || option?.type === ApplicationCommandOptionType.Number) return typeof option.autocomplete === "function" ? option.autocomplete : void 0;
|
|
661
|
-
}
|
|
662
|
-
var BaseCommand = class {
|
|
663
|
-
constructor() {
|
|
664
|
-
this.defer = false;
|
|
665
|
-
this.ephemeral = false;
|
|
666
|
-
this.type = ApplicationCommandType.ChatInput;
|
|
667
|
-
}
|
|
668
|
-
serialize() {
|
|
669
|
-
return stripUndefinedFields({
|
|
670
|
-
name: this.name,
|
|
671
|
-
description: this.description ?? "",
|
|
672
|
-
description_localizations: this.descriptionLocalizations,
|
|
673
|
-
type: this.type,
|
|
674
|
-
options: this.serializeOptions(),
|
|
675
|
-
integration_types: [0, 1],
|
|
676
|
-
contexts: [
|
|
677
|
-
InteractionContextType.Guild,
|
|
678
|
-
InteractionContextType.BotDM,
|
|
679
|
-
InteractionContextType.PrivateChannel
|
|
680
|
-
],
|
|
681
|
-
default_member_permissions: null
|
|
682
|
-
});
|
|
683
|
-
}
|
|
684
|
-
};
|
|
685
|
-
var Command = class extends BaseCommand {
|
|
686
|
-
constructor(..._args) {
|
|
687
|
-
super(..._args);
|
|
688
|
-
this.commandKind = "leaf";
|
|
689
|
-
}
|
|
690
|
-
async autocomplete(interaction) {
|
|
691
|
-
throw new Error(`The ${interaction.rawData?.data?.name ?? this.name} command does not support autocomplete`);
|
|
692
|
-
}
|
|
693
|
-
serializeOptions() {
|
|
694
|
-
return this.options?.map((option) => {
|
|
695
|
-
const type = option.type;
|
|
696
|
-
if ((type === ApplicationCommandOptionType.String || type === ApplicationCommandOptionType.Integer || type === ApplicationCommandOptionType.Number) && typeof option.autocomplete === "function") {
|
|
697
|
-
const { autocomplete: _autocomplete, ...rest } = option;
|
|
698
|
-
return {
|
|
699
|
-
...rest,
|
|
700
|
-
autocomplete: true
|
|
701
|
-
};
|
|
702
|
-
}
|
|
703
|
-
return option;
|
|
704
|
-
});
|
|
705
|
-
}
|
|
706
|
-
};
|
|
707
|
-
var CommandWithSubcommands = class extends BaseCommand {
|
|
708
|
-
constructor(..._args2) {
|
|
709
|
-
super(..._args2);
|
|
710
|
-
this.commandKind = "group";
|
|
711
|
-
}
|
|
712
|
-
async run(interaction) {
|
|
713
|
-
const subcommand = findSelectedSubcommand(this.subcommands, interaction);
|
|
714
|
-
if (!subcommand) {
|
|
715
|
-
const subcommandName = readRawCommandOptions(interaction).find((option) => option.type === ApplicationCommandOptionType.Subcommand)?.name;
|
|
716
|
-
throw new Error(`Unknown Discord subcommand: ${typeof subcommandName === "string" ? subcommandName : "<missing>"}`);
|
|
717
|
-
}
|
|
718
|
-
await deferCommandInteractionIfNeeded(subcommand, interaction);
|
|
719
|
-
return await subcommand.run(interaction);
|
|
720
|
-
}
|
|
721
|
-
serializeOptions() {
|
|
722
|
-
return this.subcommands.map((command) => stripUndefinedFields({
|
|
723
|
-
name: command.name,
|
|
724
|
-
description: command.description ?? "",
|
|
725
|
-
description_localizations: command.descriptionLocalizations,
|
|
726
|
-
type: ApplicationCommandOptionType.Subcommand,
|
|
727
|
-
options: command.serializeOptions()
|
|
728
|
-
}));
|
|
729
|
-
}
|
|
730
|
-
};
|
|
731
|
-
// extensions/discord/src/internal/interaction-options.ts
|
|
732
|
-
function findOption(options, matches) {
|
|
733
|
-
for (const option of options ?? []) {
|
|
734
|
-
if (matches(option)) return option;
|
|
735
|
-
const child = "options" in option && Array.isArray(option.options) ? findOption(option.options, matches) : void 0;
|
|
736
|
-
if (child) return child;
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
var OptionsHandler = class {
|
|
740
|
-
constructor(rawOptions, client, resolvedChannels) {
|
|
741
|
-
this.rawOptions = rawOptions;
|
|
742
|
-
this.client = client;
|
|
743
|
-
this.resolvedChannels = resolvedChannels;
|
|
744
|
-
}
|
|
745
|
-
value(name) {
|
|
746
|
-
const option = findOption(this.rawOptions, (entry) => entry.name === name);
|
|
747
|
-
return option && "value" in option ? option.value : void 0;
|
|
985
|
+
value(name) {
|
|
986
|
+
const option = findOption(this.rawOptions, (entry) => entry.name === name);
|
|
987
|
+
return option && "value" in option ? option.value : void 0;
|
|
748
988
|
}
|
|
749
989
|
getString(name) {
|
|
750
990
|
const value = this.value(name);
|
|
@@ -771,10 +1011,6 @@ var OptionsHandler = class {
|
|
|
771
1011
|
return findOption(this.rawOptions, (option) => "focused" in option && Boolean(option.focused));
|
|
772
1012
|
}
|
|
773
1013
|
};
|
|
774
|
-
// extensions/discord/src/internal/interaction-response.ts
|
|
775
|
-
function needsComponentsV2Query(body) {
|
|
776
|
-
return body !== null && typeof body === "object" && "flags" in body && typeof body.flags === "number" && (body.flags & MessageFlags.IsComponentsV2) !== 0;
|
|
777
|
-
}
|
|
778
1014
|
// extensions/discord/src/internal/modal-fields.ts
|
|
779
1015
|
function extractModalFields(components) {
|
|
780
1016
|
const out = {};
|
|
@@ -855,6 +1091,12 @@ var Embed = class {
|
|
|
855
1091
|
}
|
|
856
1092
|
};
|
|
857
1093
|
// extensions/discord/src/internal/payload.ts
|
|
1094
|
+
function asSerializableComponent(component) {
|
|
1095
|
+
return {
|
|
1096
|
+
isV2: component.type !== ComponentType.ActionRow,
|
|
1097
|
+
serialize: () => component
|
|
1098
|
+
};
|
|
1099
|
+
}
|
|
858
1100
|
function hasDiscordV2Components(components) {
|
|
859
1101
|
return Boolean(components?.some((component) => "isV2" in component && component.isV2 || "type" in component && component.type !== ComponentType.ActionRow));
|
|
860
1102
|
}
|
|
@@ -879,25 +1121,10 @@ function serializePayload(payload) {
|
|
|
879
1121
|
sticker_ids: payload.stickers
|
|
880
1122
|
});
|
|
881
1123
|
}
|
|
882
|
-
// extensions/discord/src/internal/schemas.ts
|
|
883
|
-
const discordInteractionPayloadSchema = Type.Object({
|
|
884
|
-
id: Type.String({ minLength: 1 }),
|
|
885
|
-
token: Type.String({ minLength: 1 }),
|
|
886
|
-
type: Type.Number()
|
|
887
|
-
}, { additionalProperties: true });
|
|
888
|
-
const discordRateLimitBodySchema = Type.Object({
|
|
889
|
-
message: Type.Optional(Type.String()),
|
|
890
|
-
retry_after: Type.Optional(Type.Union([Type.Number(), Type.String()])),
|
|
891
|
-
global: Type.Optional(Type.Boolean()),
|
|
892
|
-
code: Type.Optional(Type.Union([Type.Number(), Type.String()]))
|
|
893
|
-
}, { additionalProperties: true });
|
|
894
|
-
function assertDiscordInteractionPayload(value) {
|
|
895
|
-
if (!Check(discordInteractionPayloadSchema, value)) throw new Error("Invalid Discord interaction payload");
|
|
896
|
-
}
|
|
897
|
-
function isDiscordRateLimitBody(value) {
|
|
898
|
-
return Check(discordRateLimitBodySchema, value);
|
|
899
|
-
}
|
|
900
1124
|
// extensions/discord/src/internal/interactions.ts
|
|
1125
|
+
function needsComponentsV2Query(body) {
|
|
1126
|
+
return "flags" in body && ((body.flags ?? 0) & MessageFlags.IsComponentsV2) !== 0;
|
|
1127
|
+
}
|
|
901
1128
|
function readInteractionUser(rawData, client) {
|
|
902
1129
|
const directUser = "user" in rawData ? rawData.user : void 0;
|
|
903
1130
|
if (directUser && typeof directUser === "object" && "id" in directUser) return new User(client, directUser);
|
|
@@ -1030,12 +1257,6 @@ var BaseComponentInteraction = class extends BaseInteraction {
|
|
|
1030
1257
|
return await this.callback(InteractionResponseType.LaunchActivity);
|
|
1031
1258
|
}
|
|
1032
1259
|
};
|
|
1033
|
-
var ButtonInteraction = class extends BaseComponentInteraction {};
|
|
1034
|
-
var StringSelectMenuInteraction = class extends BaseComponentInteraction {};
|
|
1035
|
-
var UserSelectMenuInteraction = class extends BaseComponentInteraction {};
|
|
1036
|
-
var RoleSelectMenuInteraction = class extends BaseComponentInteraction {};
|
|
1037
|
-
var MentionableSelectMenuInteraction = class extends BaseComponentInteraction {};
|
|
1038
|
-
var ChannelSelectMenuInteraction = class extends BaseComponentInteraction {};
|
|
1039
1260
|
var ModalInteraction = class extends BaseInteraction {
|
|
1040
1261
|
constructor(client, rawData) {
|
|
1041
1262
|
super(client, rawData);
|
|
@@ -1045,20 +1266,12 @@ var ModalInteraction = class extends BaseInteraction {
|
|
|
1045
1266
|
return await this.callback(InteractionResponseType.DeferredMessageUpdate);
|
|
1046
1267
|
}
|
|
1047
1268
|
};
|
|
1048
|
-
const componentInteractions = /* @__PURE__ */ new Map([
|
|
1049
|
-
[ComponentType.Button, ButtonInteraction],
|
|
1050
|
-
[ComponentType.StringSelect, StringSelectMenuInteraction],
|
|
1051
|
-
[ComponentType.UserSelect, UserSelectMenuInteraction],
|
|
1052
|
-
[ComponentType.RoleSelect, RoleSelectMenuInteraction],
|
|
1053
|
-
[ComponentType.MentionableSelect, MentionableSelectMenuInteraction],
|
|
1054
|
-
[ComponentType.ChannelSelect, ChannelSelectMenuInteraction]
|
|
1055
|
-
]);
|
|
1056
1269
|
function createInteraction(client, rawData) {
|
|
1057
1270
|
assertDiscordInteractionPayload(rawData);
|
|
1058
1271
|
if (rawData.type === InteractionType.ApplicationCommandAutocomplete) return new AutocompleteInteraction(client, rawData);
|
|
1059
1272
|
if (rawData.type === InteractionType.ApplicationCommand) return new CommandInteraction(client, rawData);
|
|
1060
1273
|
if (rawData.type === InteractionType.ModalSubmit) return new ModalInteraction(client, rawData);
|
|
1061
|
-
if (rawData.type === InteractionType.MessageComponent) return new
|
|
1274
|
+
if (rawData.type === InteractionType.MessageComponent) return new BaseComponentInteraction(client, rawData);
|
|
1062
1275
|
return new BaseInteraction(client, rawData);
|
|
1063
1276
|
}
|
|
1064
1277
|
// extensions/discord/src/internal/interaction-dispatch.ts
|
|
@@ -1077,39 +1290,36 @@ async function dispatchInteraction(client, rawData) {
|
|
|
1077
1290
|
return;
|
|
1078
1291
|
}
|
|
1079
1292
|
try {
|
|
1080
|
-
|
|
1293
|
+
if (rawData.type === InteractionType.ApplicationCommand) {
|
|
1294
|
+
const command = client.commands.find((entry) => entry.name === rawData.data?.name);
|
|
1295
|
+
if (command) {
|
|
1296
|
+
await deferCommandInteractionIfNeeded(command, interaction);
|
|
1297
|
+
await command.run(interaction);
|
|
1298
|
+
}
|
|
1299
|
+
return;
|
|
1300
|
+
}
|
|
1301
|
+
if (rawData.type === InteractionType.MessageComponent) {
|
|
1302
|
+
const customId = rawData.data?.custom_id;
|
|
1303
|
+
if (!customId) return;
|
|
1304
|
+
const componentInteraction = interaction;
|
|
1305
|
+
const component = client.componentHandler.resolve(customId, { componentType: rawData.data?.component_type });
|
|
1306
|
+
if (component) {
|
|
1307
|
+
await deferComponentInteractionIfNeeded(component, componentInteraction);
|
|
1308
|
+
await component.run(componentInteraction, (component.customIdParser ?? parseCustomId)(customId).data);
|
|
1309
|
+
}
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
if (rawData.type === InteractionType.ModalSubmit) {
|
|
1313
|
+
const customId = rawData.data?.custom_id;
|
|
1314
|
+
if (!customId) return;
|
|
1315
|
+
const modal = client.modalHandler.resolve(customId);
|
|
1316
|
+
if (modal) await modal.run(interaction, modal.customIdParser(customId).data);
|
|
1317
|
+
}
|
|
1081
1318
|
} catch (error) {
|
|
1082
1319
|
await reportInteractionFailure(interaction);
|
|
1083
1320
|
throw error;
|
|
1084
1321
|
}
|
|
1085
1322
|
}
|
|
1086
|
-
async function dispatchAcknowledgeableInteraction(client, rawData, interaction) {
|
|
1087
|
-
if (rawData.type === InteractionType.ApplicationCommand) {
|
|
1088
|
-
const command = client.commands.find((entry) => entry.name === rawData.data?.name);
|
|
1089
|
-
if (command) {
|
|
1090
|
-
await deferCommandInteractionIfNeeded(command, interaction);
|
|
1091
|
-
await command.run(interaction);
|
|
1092
|
-
}
|
|
1093
|
-
return;
|
|
1094
|
-
}
|
|
1095
|
-
if (rawData.type === InteractionType.MessageComponent) {
|
|
1096
|
-
const customId = rawData.data?.custom_id;
|
|
1097
|
-
if (!customId) return;
|
|
1098
|
-
const componentInteraction = interaction;
|
|
1099
|
-
const component = client.componentHandler.resolve(customId, { componentType: rawData.data?.component_type });
|
|
1100
|
-
if (component) {
|
|
1101
|
-
await deferComponentInteractionIfNeeded(component, componentInteraction);
|
|
1102
|
-
await component.run(componentInteraction, component.customIdParser(customId).data);
|
|
1103
|
-
}
|
|
1104
|
-
return;
|
|
1105
|
-
}
|
|
1106
|
-
if (rawData.type === InteractionType.ModalSubmit) {
|
|
1107
|
-
const customId = rawData.data?.custom_id;
|
|
1108
|
-
if (!customId) return;
|
|
1109
|
-
const modal = client.modalHandler.resolve(customId);
|
|
1110
|
-
if (modal) await modal.run(interaction, modal.customIdParser(customId).data);
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
1323
|
const INTERACTION_FAILURE_NOTICE = "Command failed. Check the Gateway logs for details.";
|
|
1114
1324
|
async function reportInteractionFailure(interaction) {
|
|
1115
1325
|
if (interaction.responseState !== "deferred" || interaction.hasSentFollowUp) return;
|
|
@@ -1121,7 +1331,7 @@ async function reportInteractionFailure(interaction) {
|
|
|
1121
1331
|
} catch {}
|
|
1122
1332
|
}
|
|
1123
1333
|
function resolveConditionalComponentOption(value, interaction) {
|
|
1124
|
-
return typeof value === "function" ? value(interaction) : value;
|
|
1334
|
+
return typeof value === "function" ? value(interaction) : value ?? false;
|
|
1125
1335
|
}
|
|
1126
1336
|
async function deferComponentInteractionIfNeeded(component, interaction) {
|
|
1127
1337
|
if (!resolveConditionalComponentOption(component.defer, interaction)) return;
|
|
@@ -1131,699 +1341,118 @@ async function deferComponentInteractionIfNeeded(component, interaction) {
|
|
|
1131
1341
|
}
|
|
1132
1342
|
await interaction.acknowledge();
|
|
1133
1343
|
}
|
|
1134
|
-
// extensions/discord/src/internal/
|
|
1135
|
-
const
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1344
|
+
// extensions/discord/src/internal/client.ts
|
|
1345
|
+
const DEFAULT_REST_CACHE_TTL_MS = 3e4;
|
|
1346
|
+
const DEFAULT_MAX_ENTRIES = 5e3;
|
|
1347
|
+
const DEFAULT_SWEEP_INTERVAL_MS = 3e4;
|
|
1348
|
+
const CACHE_KIND_BY_EVENT = /* @__PURE__ */ new Map([
|
|
1349
|
+
[GatewayDispatchEvents.ChannelUpdate, "channel"],
|
|
1350
|
+
[GatewayDispatchEvents.ChannelDelete, "channel"],
|
|
1351
|
+
[GatewayDispatchEvents.ThreadUpdate, "channel"],
|
|
1352
|
+
[GatewayDispatchEvents.ThreadDelete, "channel"],
|
|
1353
|
+
[GatewayDispatchEvents.GuildUpdate, "guild"],
|
|
1354
|
+
[GatewayDispatchEvents.GuildEmojisUpdate, "guild-emojis"],
|
|
1355
|
+
[GatewayDispatchEvents.GuildMemberAdd, "member"],
|
|
1356
|
+
[GatewayDispatchEvents.GuildMemberRemove, "member"],
|
|
1357
|
+
[GatewayDispatchEvents.GuildMemberUpdate, "member"]
|
|
1358
|
+
]);
|
|
1359
|
+
const DISCORD_APPLICATION_COMMAND_LIMIT_REACHED = 30032;
|
|
1360
|
+
function stableCommandKey(command) {
|
|
1361
|
+
return `${command.type ?? ApplicationCommandType.ChatInput}:${command.name}`;
|
|
1147
1362
|
}
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
return
|
|
1363
|
+
function stableCommandSetHash(commands) {
|
|
1364
|
+
const stable = commands.toSorted((a, b) => stableCommandKey(a).localeCompare(stableCommandKey(b))).map((command) => stableComparableObject(command));
|
|
1365
|
+
return createHash("sha256").update(JSON.stringify(stable)).digest("hex");
|
|
1151
1366
|
}
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
const bodyObject = data.body;
|
|
1157
|
-
const topLevelFiles = Array.isArray(bodyObject.files) ? bodyObject.files : void 0;
|
|
1158
|
-
const nestedData = bodyObject.data && typeof bodyObject.data === "object" ? bodyObject.data : void 0;
|
|
1159
|
-
const nestedFiles = nestedData && Array.isArray(nestedData.files) ? nestedData.files : void 0;
|
|
1160
|
-
const files = topLevelFiles ?? nestedFiles;
|
|
1161
|
-
const filesContainer = topLevelFiles ? bodyObject : nestedFiles ? nestedData : void 0;
|
|
1162
|
-
if (files?.length && filesContainer) {
|
|
1163
|
-
if (data.multipartStyle === "form") {
|
|
1164
|
-
const formData = new FormData();
|
|
1165
|
-
for (const [key, value] of Object.entries(filesContainer)) {
|
|
1166
|
-
if (key === "files" || value === void 0 || value === null) continue;
|
|
1167
|
-
formData.append(key, typeof value === "string" ? value : JSON.stringify(value));
|
|
1168
|
-
}
|
|
1169
|
-
for (const file of files) {
|
|
1170
|
-
const item = file;
|
|
1171
|
-
const name = typeof item.name === "string" && item.name ? item.name : "file";
|
|
1172
|
-
formData.append(typeof item.fieldName === "string" && item.fieldName ? item.fieldName : "file", fileBlob(item), name);
|
|
1173
|
-
}
|
|
1174
|
-
return formData;
|
|
1175
|
-
}
|
|
1176
|
-
const payloadFilesContainer = { ...filesContainer };
|
|
1177
|
-
const payloadJson = topLevelFiles ? payloadFilesContainer : {
|
|
1178
|
-
...bodyObject,
|
|
1179
|
-
data: payloadFilesContainer
|
|
1180
|
-
};
|
|
1181
|
-
const formData = new FormData();
|
|
1182
|
-
const existingAttachments = Array.isArray(payloadFilesContainer.attachments) ? [...payloadFilesContainer.attachments] : [];
|
|
1183
|
-
const uploaded = files.map((file, index) => {
|
|
1184
|
-
const item = file;
|
|
1185
|
-
const name = typeof item.name === "string" && item.name ? item.name : `file-${index}`;
|
|
1186
|
-
const id = existingAttachments.length + index;
|
|
1187
|
-
formData.append(`files[${id}]`, fileBlob(item), name);
|
|
1188
|
-
const attachment = {
|
|
1189
|
-
id,
|
|
1190
|
-
filename: name
|
|
1191
|
-
};
|
|
1192
|
-
if (typeof item.description === "string") attachment.description = item.description;
|
|
1193
|
-
if (typeof item.duration_secs === "number") attachment.duration_secs = item.duration_secs;
|
|
1194
|
-
if (typeof item.waveform === "string") attachment.waveform = item.waveform;
|
|
1195
|
-
return attachment;
|
|
1196
|
-
});
|
|
1197
|
-
payloadFilesContainer.attachments = [...existingAttachments, ...uploaded];
|
|
1198
|
-
delete payloadFilesContainer.files;
|
|
1199
|
-
formData.append("payload_json", JSON.stringify(payloadJson));
|
|
1200
|
-
return formData;
|
|
1201
|
-
}
|
|
1202
|
-
}
|
|
1203
|
-
headers.set("Content-Type", "application/json");
|
|
1204
|
-
return JSON.stringify(data.body);
|
|
1205
|
-
}
|
|
1206
|
-
// extensions/discord/src/internal/rest-errors.ts
|
|
1207
|
-
const DISCORD_UNKNOWN_MESSAGE = 10008;
|
|
1208
|
-
const DISCORD_UNKNOWN_VOICE_STATE = 10065;
|
|
1209
|
-
const DISCORD_ERROR_BODY_MAX_DEPTH = 64;
|
|
1210
|
-
const DISCORD_ERROR_BODY_MAX_NODES = 1e4;
|
|
1211
|
-
const DISCORD_ERROR_BODY_MAX_DEPTH_MARKER = "[Discord error body redacted: maximum depth exceeded]";
|
|
1212
|
-
const DISCORD_ERROR_BODY_MAX_NODES_MARKER = "[Discord error body redacted: node limit exceeded]";
|
|
1213
|
-
const DISCORD_ERROR_BODY_PRIORITY_KEYS = /* @__PURE__ */ new Set([
|
|
1214
|
-
"message",
|
|
1215
|
-
"code",
|
|
1216
|
-
"retry_after",
|
|
1217
|
-
"global"
|
|
1367
|
+
const unorderedCommandArrayFields = /* @__PURE__ */ new Set([
|
|
1368
|
+
"channel_types",
|
|
1369
|
+
"contexts",
|
|
1370
|
+
"integration_types"
|
|
1218
1371
|
]);
|
|
1219
|
-
const
|
|
1220
|
-
"
|
|
1221
|
-
"
|
|
1222
|
-
"
|
|
1372
|
+
const optionComparisonOmittedFields = /* @__PURE__ */ new Set([
|
|
1373
|
+
"contexts",
|
|
1374
|
+
"default_member_permissions",
|
|
1375
|
+
"description_localized",
|
|
1376
|
+
"integration_types",
|
|
1377
|
+
"name_localized"
|
|
1223
1378
|
]);
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
if (state.remainingNodes <= 0) return DISCORD_ERROR_BODY_MAX_NODES_MARKER;
|
|
1240
|
-
state.remainingNodes -= 1;
|
|
1241
|
-
if (typeof body === "string") return redactSensitiveFieldValue(sensitiveAncestorKey ?? fieldKey, body);
|
|
1242
|
-
if (sensitiveAncestorKey && (typeof body === "number" || typeof body === "boolean" || typeof body === "bigint")) return redactSensitiveFieldValue(sensitiveAncestorKey, String(body));
|
|
1243
|
-
if (!body || typeof body !== "object") return body;
|
|
1244
|
-
if (depth >= DISCORD_ERROR_BODY_MAX_DEPTH) return DISCORD_ERROR_BODY_MAX_DEPTH_MARKER;
|
|
1245
|
-
if (state.seen.has(body)) return "[Circular]";
|
|
1246
|
-
state.seen.add(body);
|
|
1247
|
-
let redacted;
|
|
1248
|
-
if (Array.isArray(body)) {
|
|
1249
|
-
const items = [];
|
|
1250
|
-
for (const entry of body) {
|
|
1251
|
-
if (state.remainingNodes <= 0) {
|
|
1252
|
-
items.push(DISCORD_ERROR_BODY_MAX_NODES_MARKER);
|
|
1253
|
-
break;
|
|
1254
|
-
}
|
|
1255
|
-
items.push(redactDiscordErrorBody(entry, fieldKey, sensitiveAncestorKey, state, depth + 1));
|
|
1256
|
-
}
|
|
1257
|
-
redacted = items;
|
|
1258
|
-
} else {
|
|
1259
|
-
const usedKeys = /* @__PURE__ */ new Set();
|
|
1260
|
-
const collisionCounts = /* @__PURE__ */ new Map();
|
|
1261
|
-
const entries = [];
|
|
1262
|
-
const appendEntry = (nestedKey) => {
|
|
1263
|
-
if (state.remainingNodes <= 0) return false;
|
|
1264
|
-
const outputKey = reserveRedactedKey(redactSensitiveFieldValue(sensitiveAncestorKey ?? "", nestedKey), usedKeys, collisionCounts);
|
|
1265
|
-
const nestedSensitiveKey = redactSensitiveFieldValue(nestedKey, "") !== "" ? nestedKey : sensitiveAncestorKey;
|
|
1266
|
-
entries.push([outputKey, redactDiscordErrorBody(body[nestedKey], nestedKey, nestedSensitiveKey, state, depth + 1)]);
|
|
1267
|
-
return true;
|
|
1268
|
-
};
|
|
1269
|
-
let truncated = false;
|
|
1270
|
-
for (const priorityKey of DISCORD_ERROR_BODY_PRIORITY_KEYS) if (Object.hasOwn(body, priorityKey) && !appendEntry(priorityKey)) {
|
|
1271
|
-
truncated = true;
|
|
1272
|
-
break;
|
|
1273
|
-
}
|
|
1274
|
-
if (!truncated) for (const nestedKey in body) {
|
|
1275
|
-
if (!Object.hasOwn(body, nestedKey) || DISCORD_ERROR_BODY_PRIORITY_KEYS.has(nestedKey)) continue;
|
|
1276
|
-
if (!appendEntry(nestedKey)) {
|
|
1277
|
-
truncated = true;
|
|
1278
|
-
break;
|
|
1279
|
-
}
|
|
1280
|
-
}
|
|
1281
|
-
if (truncated) {
|
|
1282
|
-
const markerKey = reserveRedactedKey(DISCORD_ERROR_BODY_MAX_NODES_MARKER, usedKeys, collisionCounts);
|
|
1283
|
-
entries.push([markerKey, DISCORD_ERROR_BODY_MAX_NODES_MARKER]);
|
|
1284
|
-
}
|
|
1285
|
-
redacted = Object.fromEntries(entries);
|
|
1286
|
-
}
|
|
1287
|
-
state.seen.delete(body);
|
|
1288
|
-
return redacted;
|
|
1289
|
-
}
|
|
1290
|
-
function readDiscordCode(body) {
|
|
1291
|
-
return parseStrictNonNegativeInteger$1(asOptionalObjectRecord(body)?.code);
|
|
1292
|
-
}
|
|
1293
|
-
function readDiscordMessage(body, fallback) {
|
|
1294
|
-
const value = asOptionalObjectRecord(body)?.message;
|
|
1295
|
-
return typeof value === "string" && value.trim() ? value : fallback;
|
|
1296
|
-
}
|
|
1297
|
-
function readErrorDiscordCode(err) {
|
|
1298
|
-
return parseStrictNonNegativeInteger$1(asOptionalObjectRecord(err)?.discordCode);
|
|
1299
|
-
}
|
|
1300
|
-
function isUnknownDiscordMessageError(err) {
|
|
1301
|
-
return readErrorDiscordCode(err) === DISCORD_UNKNOWN_MESSAGE;
|
|
1302
|
-
}
|
|
1303
|
-
function isUnknownDiscordVoiceStateError(err) {
|
|
1304
|
-
return readErrorDiscordCode(err) === DISCORD_UNKNOWN_VOICE_STATE || /unknown voice state/i.test(formatErrorMessage(err));
|
|
1305
|
-
}
|
|
1306
|
-
function readRetryAfter(body, response, fallbackSeconds = 0) {
|
|
1307
|
-
return parseDiscordRetryAfterBodySeconds(asOptionalObjectRecord(body)?.retry_after) ?? parseRetryAfterHeaderSeconds(response.headers.get("Retry-After")) ?? fallbackSeconds;
|
|
1308
|
-
}
|
|
1309
|
-
function readDiscordRateLimitBucket(response) {
|
|
1310
|
-
const value = response.headers.get("X-RateLimit-Bucket")?.trim();
|
|
1311
|
-
return value ? redactIdentifier(value, { len: 32 }) : null;
|
|
1312
|
-
}
|
|
1313
|
-
function readDiscordRateLimitScope(response) {
|
|
1314
|
-
const value = response.headers.get("X-RateLimit-Scope");
|
|
1315
|
-
return value && DISCORD_RATE_LIMIT_SCOPES.has(value) ? value : null;
|
|
1379
|
+
const nullableLocalizationFields = /* @__PURE__ */ new Set(["description_localizations", "name_localizations"]);
|
|
1380
|
+
function comparableCommand(value) {
|
|
1381
|
+
if (!value || typeof value !== "object") return value;
|
|
1382
|
+
const omit = /* @__PURE__ */ new Set([
|
|
1383
|
+
"application_id",
|
|
1384
|
+
"description_localized",
|
|
1385
|
+
"dm_permission",
|
|
1386
|
+
"guild_id",
|
|
1387
|
+
"id",
|
|
1388
|
+
"name_localized",
|
|
1389
|
+
"nsfw",
|
|
1390
|
+
"version",
|
|
1391
|
+
"default_permission"
|
|
1392
|
+
]);
|
|
1393
|
+
return stableComparableObject(Object.fromEntries(Object.entries(value).filter(([key, entry]) => !omit.has(key) && entry !== void 0)));
|
|
1316
1394
|
}
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
const
|
|
1320
|
-
const
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
this.name = "DiscordError";
|
|
1324
|
-
this.status = response.status;
|
|
1325
|
-
this.statusCode = response.status;
|
|
1326
|
-
this.rawBody = redactedBody;
|
|
1327
|
-
this.rawError = redactedBody;
|
|
1328
|
-
this.discordCode = readDiscordCode(body);
|
|
1329
|
-
}
|
|
1330
|
-
};
|
|
1331
|
-
var RateLimitError = class extends DiscordError {
|
|
1332
|
-
constructor(response, body) {
|
|
1333
|
-
super(response, body);
|
|
1334
|
-
this.name = "RateLimitError";
|
|
1335
|
-
this.retryAfter = readRetryAfter(body, response, 1);
|
|
1336
|
-
this.scope = body.global ? "global" : readDiscordRateLimitScope(response);
|
|
1337
|
-
this.bucket = readDiscordRateLimitBucket(response);
|
|
1395
|
+
function stableComparableObject(value, pathValue = []) {
|
|
1396
|
+
if (Array.isArray(value)) {
|
|
1397
|
+
const normalized = value.map((entry) => stableComparableObject(entry, pathValue));
|
|
1398
|
+
const key = pathValue.at(-1);
|
|
1399
|
+
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)));
|
|
1400
|
+
return normalized;
|
|
1338
1401
|
}
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
return `${hasLeadingSlash ? "/" : ""}${segments.join("/")}`;
|
|
1349
|
-
}
|
|
1350
|
-
function createRouteKey(method, path) {
|
|
1351
|
-
const pathname = path.split("?")[0] ?? path;
|
|
1352
|
-
return `${method.toUpperCase()} ${redactWebhookTokenInPath(pathname)}`;
|
|
1353
|
-
}
|
|
1354
|
-
function readTopLevelRouteKey(path) {
|
|
1355
|
-
const [pathname = path] = path.split("?");
|
|
1356
|
-
const [first, id, token] = pathname.replace(/^\/+/, "").split("/");
|
|
1357
|
-
if (!first || !id) return pathname;
|
|
1358
|
-
if (first === "channels" || first === "guilds" || first === "webhooks") return first === "webhooks" && token ? `${first}/${id}/${redactIdentifier(token, { len: DISCORD_ROUTE_IDENTIFIER_HASH_LENGTH })}` : `${first}/${id}`;
|
|
1359
|
-
return first;
|
|
1360
|
-
}
|
|
1361
|
-
function createBucketKey(bucket, path) {
|
|
1362
|
-
return `${bucket}:${readTopLevelRouteKey(path)}`;
|
|
1363
|
-
}
|
|
1364
|
-
function readHeaderNumber(headers, name) {
|
|
1365
|
-
const value = headers.get(name);
|
|
1366
|
-
if (!value) return;
|
|
1367
|
-
const trimmed = value.trim();
|
|
1368
|
-
if (!RATE_LIMIT_HEADER_NUMBER_RE.test(trimmed)) return;
|
|
1369
|
-
const parsed = Number(trimmed);
|
|
1370
|
-
return Number.isFinite(parsed) && Math.abs(parsed) <= Number.MAX_SAFE_INTEGER ? parsed : void 0;
|
|
1371
|
-
}
|
|
1372
|
-
function resolveRateLimitResetAt(delayMs) {
|
|
1373
|
-
const clampedDelayMs = Math.ceil(Math.max(0, delayMs));
|
|
1374
|
-
if (!Number.isSafeInteger(clampedDelayMs)) return;
|
|
1375
|
-
if (clampedDelayMs === 0) return asDateTimestampMs(Date.now());
|
|
1376
|
-
return resolveExpiresAtMsFromDurationMs(clampedDelayMs);
|
|
1377
|
-
}
|
|
1378
|
-
function readResetAt(response) {
|
|
1379
|
-
const resetAfter = readHeaderNumber(response.headers, "X-RateLimit-Reset-After");
|
|
1380
|
-
if (resetAfter !== void 0) return resolveRateLimitResetAt(resetAfter * 1e3);
|
|
1381
|
-
const reset = readHeaderNumber(response.headers, "X-RateLimit-Reset");
|
|
1382
|
-
return reset !== void 0 ? asDateTimestampMs(reset * 1e3) : void 0;
|
|
1383
|
-
}
|
|
1384
|
-
function appendQuery(path, query) {
|
|
1385
|
-
if (!query || Object.keys(query).length === 0) return path;
|
|
1386
|
-
const search = new URLSearchParams();
|
|
1387
|
-
for (const [key, value] of Object.entries(query)) search.set(key, String(value));
|
|
1388
|
-
return `${path}?${search.toString()}`;
|
|
1402
|
+
const object = asOptionalObjectRecord(value);
|
|
1403
|
+
if (!object) return value;
|
|
1404
|
+
return Object.fromEntries(Object.entries(object).filter(([key, entry]) => {
|
|
1405
|
+
if (entry === void 0) return false;
|
|
1406
|
+
if (entry === null && nullableLocalizationFields.has(key)) return false;
|
|
1407
|
+
if (pathValue.includes("options") && optionComparisonOmittedFields.has(key)) return false;
|
|
1408
|
+
if ((key === "required" || key === "autocomplete") && entry === false) return false;
|
|
1409
|
+
return true;
|
|
1410
|
+
}).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])]));
|
|
1389
1411
|
}
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
const
|
|
1396
|
-
|
|
1397
|
-
"
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
"critical",
|
|
1407
|
-
"standard",
|
|
1408
|
-
"standard",
|
|
1409
|
-
"standard",
|
|
1410
|
-
"background"
|
|
1411
|
-
];
|
|
1412
|
-
function countPending(bucket) {
|
|
1413
|
-
return requestPriorities.reduce((count, lane) => count + bucket.pending[lane].length, 0);
|
|
1414
|
-
}
|
|
1415
|
-
var RestScheduler = class {
|
|
1416
|
-
constructor(executor) {
|
|
1417
|
-
this.executor = executor;
|
|
1418
|
-
this.activeWorkers = 0;
|
|
1419
|
-
this.buckets = /* @__PURE__ */ new Map();
|
|
1420
|
-
this.globalRateLimitUntil = 0;
|
|
1421
|
-
this.laneCursor = 0;
|
|
1422
|
-
this.queuedByLane = {
|
|
1423
|
-
critical: 0,
|
|
1424
|
-
standard: 0,
|
|
1425
|
-
background: 0
|
|
1426
|
-
};
|
|
1427
|
-
this.queueGeneration = 0;
|
|
1428
|
-
this.queuedRequests = 0;
|
|
1429
|
-
this.routeBuckets = /* @__PURE__ */ new Map();
|
|
1430
|
-
}
|
|
1431
|
-
enqueue(params) {
|
|
1432
|
-
if (this.queuedRequests >= MAX_QUEUE_SIZE) throw new Error("Discord request queue is full");
|
|
1433
|
-
const routeKey = createRouteKey(params.method, params.path);
|
|
1434
|
-
const bucket = this.getBucket(this.routeBuckets.get(routeKey) ?? routeKey);
|
|
1435
|
-
return new Promise((resolve, reject) => {
|
|
1436
|
-
this.queuedRequests += 1;
|
|
1437
|
-
this.queuedByLane[params.priority] += 1;
|
|
1438
|
-
bucket.pending[params.priority].push({
|
|
1439
|
-
...params,
|
|
1440
|
-
enqueuedAt: Date.now(),
|
|
1441
|
-
generation: this.queueGeneration,
|
|
1442
|
-
routeKey,
|
|
1443
|
-
retryCount: 0,
|
|
1444
|
-
resolve,
|
|
1445
|
-
reject
|
|
1446
|
-
});
|
|
1447
|
-
this.drainQueues();
|
|
1448
|
-
});
|
|
1449
|
-
}
|
|
1450
|
-
clearQueue() {
|
|
1451
|
-
this.queueGeneration += 1;
|
|
1452
|
-
if (this.drainTimer) {
|
|
1453
|
-
clearTimeout(this.drainTimer);
|
|
1454
|
-
this.drainTimer = void 0;
|
|
1455
|
-
}
|
|
1456
|
-
this.rejectPending(/* @__PURE__ */ new Error("Discord request queue cleared"));
|
|
1457
|
-
}
|
|
1458
|
-
abortPending() {
|
|
1459
|
-
this.queueGeneration += 1;
|
|
1460
|
-
this.rejectPending(new DOMException("Aborted", "AbortError"));
|
|
1461
|
-
}
|
|
1462
|
-
get queueSize() {
|
|
1463
|
-
return this.queuedRequests;
|
|
1464
|
-
}
|
|
1465
|
-
getBucket(key) {
|
|
1466
|
-
const existing = this.buckets.get(key);
|
|
1467
|
-
if (existing) return existing;
|
|
1468
|
-
const bucket = {
|
|
1469
|
-
active: 0,
|
|
1470
|
-
pending: {
|
|
1471
|
-
critical: [],
|
|
1472
|
-
standard: [],
|
|
1473
|
-
background: []
|
|
1474
|
-
},
|
|
1475
|
-
resetAt: 0,
|
|
1476
|
-
routeKeys: /* @__PURE__ */ new Set([key])
|
|
1477
|
-
};
|
|
1478
|
-
this.buckets.set(key, bucket);
|
|
1479
|
-
return bucket;
|
|
1480
|
-
}
|
|
1481
|
-
hasBucketReference(key) {
|
|
1482
|
-
for (const bucketKey of this.routeBuckets.values()) if (bucketKey === key) return true;
|
|
1483
|
-
return false;
|
|
1484
|
-
}
|
|
1485
|
-
isBucketRateLimited(bucket, now = Date.now()) {
|
|
1486
|
-
return bucket.remaining === 0 && bucket.resetAt > now;
|
|
1487
|
-
}
|
|
1488
|
-
bindRouteToBucket(routeKey, bucketKey) {
|
|
1489
|
-
const target = this.getBucket(bucketKey);
|
|
1490
|
-
target.routeKeys.add(routeKey);
|
|
1491
|
-
this.routeBuckets.set(routeKey, bucketKey);
|
|
1492
|
-
const routeBucket = this.buckets.get(routeKey);
|
|
1493
|
-
if (routeBucket && routeBucket !== target) {
|
|
1494
|
-
for (const lane of requestPriorities) {
|
|
1495
|
-
target.pending[lane].push(...routeBucket.pending[lane]);
|
|
1496
|
-
routeBucket.pending[lane] = [];
|
|
1497
|
-
}
|
|
1498
|
-
if (routeBucket.active === 0) this.buckets.delete(routeKey);
|
|
1499
|
-
}
|
|
1500
|
-
return target;
|
|
1501
|
-
}
|
|
1502
|
-
recordResponse(routeKey, path, response, parsed) {
|
|
1503
|
-
const bucketHeader = readDiscordRateLimitBucket(response);
|
|
1504
|
-
const bucket = bucketHeader ? this.bindRouteToBucket(routeKey, createBucketKey(bucketHeader, path)) : this.getBucket(this.routeBuckets.get(routeKey) ?? routeKey);
|
|
1505
|
-
const limit = readHeaderNumber(response.headers, "X-RateLimit-Limit");
|
|
1506
|
-
if (limit !== void 0) bucket.limit = limit;
|
|
1507
|
-
const remaining = readHeaderNumber(response.headers, "X-RateLimit-Remaining");
|
|
1508
|
-
if (remaining !== void 0) bucket.remaining = remaining;
|
|
1509
|
-
const resetAt = readResetAt(response);
|
|
1510
|
-
if (resetAt !== void 0) bucket.resetAt = resetAt;
|
|
1511
|
-
if (response.status !== 429) return;
|
|
1512
|
-
const retryAt = resolveRateLimitResetAt(Math.max(0, readRetryAfter(parsed, response, 1) * 1e3));
|
|
1513
|
-
if (retryAt === void 0) return;
|
|
1514
|
-
if (response.headers.get("X-RateLimit-Global") === "true" || isGlobalRateLimit(parsed)) {
|
|
1515
|
-
this.globalRateLimitUntil = Math.max(this.globalRateLimitUntil, retryAt);
|
|
1516
|
-
return;
|
|
1517
|
-
}
|
|
1518
|
-
bucket.remaining = 0;
|
|
1519
|
-
bucket.resetAt = Math.max(bucket.resetAt, retryAt);
|
|
1520
|
-
}
|
|
1521
|
-
getBucketWaitMs(bucket, now) {
|
|
1522
|
-
if (bucket.remaining === 0 && bucket.resetAt > now) return bucket.resetAt - now;
|
|
1523
|
-
if (bucket.remaining === 0 && bucket.resetAt <= now) bucket.remaining = bucket.limit;
|
|
1524
|
-
return 0;
|
|
1525
|
-
}
|
|
1526
|
-
scheduleDrain(delayMs = 0) {
|
|
1527
|
-
if (this.drainTimer) return;
|
|
1528
|
-
this.drainTimer = setTimeout(() => {
|
|
1529
|
-
this.drainTimer = void 0;
|
|
1530
|
-
this.drainQueues();
|
|
1531
|
-
}, resolveTimerTimeoutMs(delayMs, 0, 0));
|
|
1532
|
-
this.drainTimer.unref?.();
|
|
1533
|
-
}
|
|
1534
|
-
drainQueues() {
|
|
1535
|
-
while (this.activeWorkers < MAX_CONCURRENT_WORKERS) {
|
|
1536
|
-
const next = this.takeNextQueuedRequest();
|
|
1537
|
-
if (!next.queued) {
|
|
1538
|
-
if (next.waitMs !== void 0 && Number.isFinite(next.waitMs)) this.scheduleDrain(next.waitMs);
|
|
1539
|
-
break;
|
|
1540
|
-
}
|
|
1541
|
-
const { bucket, queued } = next;
|
|
1542
|
-
if (bucket.remaining !== void 0 && bucket.remaining > 0) bucket.remaining -= 1;
|
|
1543
|
-
bucket.active += 1;
|
|
1544
|
-
this.activeWorkers += 1;
|
|
1545
|
-
this.runQueuedRequest(queued, bucket);
|
|
1546
|
-
}
|
|
1547
|
-
}
|
|
1548
|
-
takeNextQueuedRequest() {
|
|
1549
|
-
const now = Date.now();
|
|
1550
|
-
if (this.globalRateLimitUntil > now) return { waitMs: this.globalRateLimitUntil - now };
|
|
1551
|
-
this.pruneIdleBuckets(now);
|
|
1552
|
-
let nextDelayMs;
|
|
1553
|
-
const buckets = Array.from(this.buckets.values()).filter((bucket) => countPending(bucket) > 0);
|
|
1554
|
-
if (buckets.length === 0) return {};
|
|
1555
|
-
for (let laneOffset = 0; laneOffset < laneSchedule.length; laneOffset += 1) {
|
|
1556
|
-
const lane = laneSchedule[(this.laneCursor + laneOffset) % laneSchedule.length];
|
|
1557
|
-
if (!lane || this.queuedByLane[lane] <= 0) continue;
|
|
1558
|
-
for (const bucket of buckets) {
|
|
1559
|
-
const queue = bucket.pending[lane];
|
|
1560
|
-
this.dropStaleHeadRequests(queue, lane, now);
|
|
1561
|
-
if (queue.length === 0 || bucket.active > 0) continue;
|
|
1562
|
-
const waitMs = this.getBucketWaitMs(bucket, now);
|
|
1563
|
-
if (waitMs > 0) {
|
|
1564
|
-
nextDelayMs = Math.min(nextDelayMs ?? waitMs, waitMs);
|
|
1565
|
-
continue;
|
|
1566
|
-
}
|
|
1567
|
-
const queued = queue.shift();
|
|
1568
|
-
if (!queued) continue;
|
|
1569
|
-
this.queuedByLane[lane] = Math.max(0, this.queuedByLane[lane] - 1);
|
|
1570
|
-
this.laneCursor = (this.laneCursor + laneOffset + 1) % laneSchedule.length;
|
|
1571
|
-
return {
|
|
1572
|
-
bucket,
|
|
1573
|
-
queued
|
|
1574
|
-
};
|
|
1575
|
-
}
|
|
1576
|
-
}
|
|
1577
|
-
return { waitMs: nextDelayMs };
|
|
1578
|
-
}
|
|
1579
|
-
dropStaleHeadRequests(queue, lane, now) {
|
|
1580
|
-
if (lane !== "background") return;
|
|
1581
|
-
while (queue.length > 0 && now - (queue[0]?.enqueuedAt ?? now) > BACKGROUND_STALE_AFTER_MS) {
|
|
1582
|
-
const stale = queue.shift();
|
|
1583
|
-
if (!stale) continue;
|
|
1584
|
-
this.queuedRequests = Math.max(0, this.queuedRequests - 1);
|
|
1585
|
-
this.queuedByLane[lane] = Math.max(0, this.queuedByLane[lane] - 1);
|
|
1586
|
-
stale.reject(/* @__PURE__ */ new Error(`Dropped stale ${lane} request after ${now - stale.enqueuedAt}ms`));
|
|
1587
|
-
}
|
|
1588
|
-
}
|
|
1589
|
-
pruneIdleBuckets(now = Date.now()) {
|
|
1590
|
-
for (const [key, bucket] of this.buckets) {
|
|
1591
|
-
if (bucket.active !== 0 || countPending(bucket) > 0) continue;
|
|
1592
|
-
if (this.isBucketRateLimited(bucket, now)) continue;
|
|
1593
|
-
for (const routeKey of bucket.routeKeys) if (this.routeBuckets.get(routeKey) === key) {
|
|
1594
|
-
this.routeBuckets.delete(routeKey);
|
|
1595
|
-
bucket.routeKeys.delete(routeKey);
|
|
1596
|
-
}
|
|
1597
|
-
if (this.routeBuckets.get(key) !== key && !this.hasBucketReference(key)) this.buckets.delete(key);
|
|
1598
|
-
}
|
|
1599
|
-
}
|
|
1600
|
-
async runQueuedRequest(queued, bucket) {
|
|
1601
|
-
let requeued = false;
|
|
1602
|
-
try {
|
|
1603
|
-
queued.resolve(await this.executor(queued));
|
|
1604
|
-
} catch (error) {
|
|
1605
|
-
if (error instanceof RateLimitError && this.requeueRateLimitedRequest(queued)) {
|
|
1606
|
-
requeued = true;
|
|
1607
|
-
return;
|
|
1608
|
-
}
|
|
1609
|
-
queued.reject(error);
|
|
1610
|
-
} finally {
|
|
1611
|
-
bucket.active = Math.max(0, bucket.active - 1);
|
|
1612
|
-
this.activeWorkers = Math.max(0, this.activeWorkers - 1);
|
|
1613
|
-
if (!requeued) this.queuedRequests = Math.max(0, this.queuedRequests - 1);
|
|
1614
|
-
if (bucket.active === 0 && countPending(bucket) === 0) {
|
|
1615
|
-
for (const routeKey of bucket.routeKeys) if (this.routeBuckets.get(routeKey) === routeKey) this.routeBuckets.delete(routeKey);
|
|
1616
|
-
}
|
|
1617
|
-
this.drainQueues();
|
|
1618
|
-
}
|
|
1619
|
-
}
|
|
1620
|
-
requeueRateLimitedRequest(queued) {
|
|
1621
|
-
if (queued.generation !== this.queueGeneration || queued.retryCount >= MAX_RATE_LIMIT_RETRIES) return false;
|
|
1622
|
-
const bucketKey = this.routeBuckets.get(queued.routeKey) ?? queued.routeKey;
|
|
1623
|
-
this.getBucket(bucketKey).pending[queued.priority].push({
|
|
1624
|
-
...queued,
|
|
1625
|
-
enqueuedAt: Date.now(),
|
|
1626
|
-
retryCount: queued.retryCount + 1
|
|
1627
|
-
});
|
|
1628
|
-
this.queuedByLane[queued.priority] += 1;
|
|
1629
|
-
return true;
|
|
1630
|
-
}
|
|
1631
|
-
rejectPending(error) {
|
|
1632
|
-
for (const bucket of this.buckets.values()) for (const lane of requestPriorities) for (const queued of bucket.pending[lane].splice(0)) {
|
|
1633
|
-
queued.reject(error);
|
|
1634
|
-
this.queuedRequests = Math.max(0, this.queuedRequests - 1);
|
|
1635
|
-
this.queuedByLane[lane] = Math.max(0, this.queuedByLane[lane] - 1);
|
|
1636
|
-
}
|
|
1637
|
-
}
|
|
1638
|
-
};
|
|
1639
|
-
function isGlobalRateLimit(parsed) {
|
|
1640
|
-
return parsed && typeof parsed === "object" && "global" in parsed ? Boolean(parsed.global) : false;
|
|
1641
|
-
}
|
|
1642
|
-
// extensions/discord/src/internal/rest.ts
|
|
1643
|
-
const defaultOptions = {
|
|
1644
|
-
baseUrl: "https://discord.com/api",
|
|
1645
|
-
timeout: 15e3,
|
|
1646
|
-
queueRequests: true
|
|
1647
|
-
};
|
|
1648
|
-
const DISCORD_REST_RESPONSE_BODY_MAX_BYTES = 8388608;
|
|
1649
|
-
const GZIP_MAGIC = [31, 139];
|
|
1650
|
-
function createResponseBodyOverflowError(size) {
|
|
1651
|
-
return /* @__PURE__ */ new Error(`Discord REST response body exceeds ${DISCORD_REST_RESPONSE_BODY_MAX_BYTES} bytes (received ${size})`);
|
|
1652
|
-
}
|
|
1653
|
-
async function readResponseBodyText(response, idleTimeoutMs) {
|
|
1654
|
-
const buffer = await readResponseWithLimit(response, DISCORD_REST_RESPONSE_BODY_MAX_BYTES, {
|
|
1655
|
-
chunkTimeoutMs: idleTimeoutMs,
|
|
1656
|
-
onOverflow: ({ size }) => createResponseBodyOverflowError(size),
|
|
1657
|
-
onIdleTimeout: ({ chunkTimeoutMs }) => /* @__PURE__ */ new Error(`Discord REST response stalled: no data received for ${chunkTimeoutMs}ms`)
|
|
1658
|
-
});
|
|
1659
|
-
if (!buffer.byteLength) return "";
|
|
1660
|
-
if (buffer[0] === GZIP_MAGIC[0] && buffer[1] === GZIP_MAGIC[1]) try {
|
|
1661
|
-
return gunzipSync(buffer, { maxOutputLength: DISCORD_REST_RESPONSE_BODY_MAX_BYTES }).toString("utf8");
|
|
1662
|
-
} catch (err) {
|
|
1663
|
-
if (err instanceof RangeError && "code" in err && err.code === "ERR_BUFFER_TOO_LARGE") throw createResponseBodyOverflowError("decompressed output");
|
|
1664
|
-
throw err;
|
|
1665
|
-
}
|
|
1666
|
-
return buffer.toString("utf8");
|
|
1667
|
-
}
|
|
1668
|
-
function coerceResponseBody(raw) {
|
|
1669
|
-
if (!raw) return;
|
|
1670
|
-
try {
|
|
1671
|
-
return JSON.parse(raw);
|
|
1672
|
-
} catch {
|
|
1673
|
-
return raw;
|
|
1674
|
-
}
|
|
1675
|
-
}
|
|
1676
|
-
var RequestClient = class {
|
|
1677
|
-
constructor(token, options) {
|
|
1678
|
-
this.requestControllers = /* @__PURE__ */ new Set();
|
|
1679
|
-
const endpoint = getDiscordEndpointRuntime();
|
|
1680
|
-
const resolvedOptions = endpoint ? {
|
|
1681
|
-
...options,
|
|
1682
|
-
apiBaseUrl: endpoint.descriptor.restApiBaseUrl,
|
|
1683
|
-
fetch: endpoint.fetch
|
|
1684
|
-
} : options;
|
|
1685
|
-
this.token = token.replace(/^Bot\s+/i, "");
|
|
1686
|
-
this.customFetch = resolvedOptions?.fetch;
|
|
1687
|
-
this.guardedEndpoint = endpoint !== void 0;
|
|
1688
|
-
this.options = normalizeRequestClientOptions(resolvedOptions);
|
|
1689
|
-
this.scheduler = new RestScheduler(async (request) => await this.executeRequest(request.method, request.path, {
|
|
1690
|
-
data: request.data?.data,
|
|
1691
|
-
query: request.query
|
|
1692
|
-
}, request.routeKey, request.data?.assertCurrent, request.data?.effect));
|
|
1693
|
-
}
|
|
1694
|
-
async get(path, query) {
|
|
1695
|
-
return await this.request("GET", path, { query });
|
|
1696
|
-
}
|
|
1697
|
-
async post(path, data, query) {
|
|
1698
|
-
return await this.request("POST", path, {
|
|
1699
|
-
data,
|
|
1700
|
-
query
|
|
1701
|
-
});
|
|
1702
|
-
}
|
|
1703
|
-
async patch(path, data, query) {
|
|
1704
|
-
return await this.request("PATCH", path, {
|
|
1705
|
-
data,
|
|
1706
|
-
query
|
|
1707
|
-
});
|
|
1708
|
-
}
|
|
1709
|
-
async put(path, data, query) {
|
|
1710
|
-
return await this.request("PUT", path, {
|
|
1711
|
-
data,
|
|
1712
|
-
query
|
|
1713
|
-
});
|
|
1714
|
-
}
|
|
1715
|
-
async delete(path, data, query) {
|
|
1716
|
-
return await this.request("DELETE", path, {
|
|
1717
|
-
data,
|
|
1718
|
-
query
|
|
1719
|
-
});
|
|
1720
|
-
}
|
|
1721
|
-
async request(method, path, params) {
|
|
1722
|
-
const routeKey = createRouteKey(method, path);
|
|
1723
|
-
const assertActionAuthority = captureDiscordRequestAuthority();
|
|
1724
|
-
const assertReadAuthority = captureChannelReadAuthority();
|
|
1725
|
-
const effect = captureEffectAuthority();
|
|
1726
|
-
const assertCurrent = assertActionAuthority ? () => {
|
|
1727
|
-
assertActionAuthority();
|
|
1728
|
-
assertReadAuthority?.();
|
|
1729
|
-
} : assertReadAuthority;
|
|
1730
|
-
assertCurrent?.();
|
|
1731
|
-
if (!this.options.queueRequests) return await this.executeRequest(method, path, params, routeKey, assertCurrent, effect);
|
|
1732
|
-
return await this.scheduler.enqueue({
|
|
1733
|
-
method,
|
|
1734
|
-
path,
|
|
1735
|
-
priority: getRequestPriority(method, path),
|
|
1736
|
-
query: params.query,
|
|
1737
|
-
data: {
|
|
1738
|
-
data: params.data,
|
|
1739
|
-
assertCurrent,
|
|
1740
|
-
effect
|
|
1741
|
-
}
|
|
1742
|
-
});
|
|
1743
|
-
}
|
|
1744
|
-
async executeRequest(method, path, params, routeKey = createRouteKey(method, path), assertCurrent, effect = captureEffectAuthority()) {
|
|
1745
|
-
const url = `${this.options.apiBaseUrl}${appendQuery(path, params.query)}`;
|
|
1746
|
-
const headers = new Headers({ "User-Agent": "OpenClaw Discord" });
|
|
1747
|
-
if (this.token !== "webhook") headers.set("Authorization", `Bot ${this.token}`);
|
|
1748
|
-
const body = serializeRequestBody(params.data, headers);
|
|
1749
|
-
const controller = new AbortController();
|
|
1750
|
-
const timeout = setTimeout(() => controller.abort(), this.options.timeout);
|
|
1751
|
-
timeout.unref?.();
|
|
1752
|
-
const signal = this.options.signal ? AbortSignal.any([this.options.signal, controller.signal]) : controller.signal;
|
|
1753
|
-
this.requestControllers.add(controller);
|
|
1754
|
-
try {
|
|
1755
|
-
assertCurrent?.();
|
|
1756
|
-
const init = {
|
|
1757
|
-
method,
|
|
1758
|
-
headers,
|
|
1759
|
-
body,
|
|
1760
|
-
signal
|
|
1761
|
-
};
|
|
1762
|
-
const request = () => {
|
|
1763
|
-
assertCurrent?.();
|
|
1764
|
-
return this.customFetch && assertCurrent ? this.customFetch(url, init, assertCurrent) : (this.customFetch ?? fetch)(url, init);
|
|
1765
|
-
};
|
|
1766
|
-
const response = this.guardedEndpoint ? await effect.run(request) : await effect.initiate(request);
|
|
1767
|
-
const parsed = coerceResponseBody(await readResponseBodyText(response, this.options.timeout).catch((error) => {
|
|
1768
|
-
if (response.ok) throw error;
|
|
1769
|
-
return "";
|
|
1770
|
-
}));
|
|
1771
|
-
this.scheduler.recordResponse(routeKey, path, response, parsed);
|
|
1772
|
-
if (response.status === 204) return;
|
|
1773
|
-
if (response.status === 429) {
|
|
1774
|
-
const rateLimitBody = isDiscordRateLimitBody(parsed) ? parsed : void 0;
|
|
1775
|
-
throw new RateLimitError(response, {
|
|
1776
|
-
message: readDiscordMessage(rateLimitBody, "Rate limited"),
|
|
1777
|
-
retry_after: readRetryAfter(rateLimitBody, response, 1),
|
|
1778
|
-
code: readDiscordCode(rateLimitBody),
|
|
1779
|
-
global: Boolean(rateLimitBody?.global)
|
|
1780
|
-
});
|
|
1781
|
-
}
|
|
1782
|
-
if (!response.ok) throw new DiscordError(response, parsed);
|
|
1783
|
-
return parsed;
|
|
1784
|
-
} catch (error) {
|
|
1785
|
-
if (error instanceof Error) throw error;
|
|
1786
|
-
throw new Error(`Discord request failed: ${inspect(error)}`, { cause: error });
|
|
1787
|
-
} finally {
|
|
1788
|
-
clearTimeout(timeout);
|
|
1789
|
-
this.requestControllers.delete(controller);
|
|
1790
|
-
}
|
|
1791
|
-
}
|
|
1792
|
-
clearQueue() {
|
|
1793
|
-
this.scheduler.clearQueue();
|
|
1412
|
+
/**
|
|
1413
|
+
* Normalize descriptions to match Discord's server-side storage semantics.
|
|
1414
|
+
* Discord collapses whitespace and removes whitespace between CJK characters.
|
|
1415
|
+
*/
|
|
1416
|
+
function normalizeDescriptionForComparison(description) {
|
|
1417
|
+
const collapsed = description.replace(/\s+/g, " ");
|
|
1418
|
+
const cjkBoundaryWhitespace = /([\u3000-\u303F\u4E00-\u9FFF\uFF00-\uFFEF])\s+([\u3000-\u303F\u4E00-\u9FFF\uFF00-\uFFEF])/g;
|
|
1419
|
+
return collapsed.replace(cjkBoundaryWhitespace, "$1$2").replace(cjkBoundaryWhitespace, "$1$2").trim();
|
|
1420
|
+
}
|
|
1421
|
+
function commandsEqual(a, b) {
|
|
1422
|
+
return JSON.stringify(comparableCommand(a)) === JSON.stringify(comparableCommand(b));
|
|
1423
|
+
}
|
|
1424
|
+
var ComponentRegistry = class {
|
|
1425
|
+
constructor() {
|
|
1426
|
+
this.entries = /* @__PURE__ */ new Map();
|
|
1427
|
+
this.wildcardEntries = [];
|
|
1794
1428
|
}
|
|
1795
|
-
|
|
1796
|
-
|
|
1429
|
+
register(entry) {
|
|
1430
|
+
const key = (entry.customIdParser ?? parseCustomId)(entry.customId).key;
|
|
1431
|
+
const entries = key === "*" ? this.wildcardEntries : this.entries.get(key) ?? [];
|
|
1432
|
+
if (!entries.includes(entry)) {
|
|
1433
|
+
entries.push(entry);
|
|
1434
|
+
if (key !== "*") this.entries.set(key, entries);
|
|
1435
|
+
}
|
|
1797
1436
|
}
|
|
1798
|
-
|
|
1799
|
-
this.
|
|
1800
|
-
|
|
1801
|
-
|
|
1437
|
+
resolve(customId, options) {
|
|
1438
|
+
for (const entries of this.entries.values()) {
|
|
1439
|
+
const match = entries.find((entry) => {
|
|
1440
|
+
if (options?.componentType !== void 0 && entry.type !== options.componentType) return false;
|
|
1441
|
+
const parser = entry.customIdParser ?? parseCustomId;
|
|
1442
|
+
return parser(entry.customId).key === parser(customId).key;
|
|
1443
|
+
});
|
|
1444
|
+
if (match) return match;
|
|
1445
|
+
}
|
|
1446
|
+
return this.wildcardEntries.find((entry) => options?.componentType === void 0 || entry.type === options.componentType);
|
|
1802
1447
|
}
|
|
1803
1448
|
};
|
|
1804
|
-
function normalizeRequestClientOptions(options) {
|
|
1805
|
-
const merged = {
|
|
1806
|
-
...defaultOptions,
|
|
1807
|
-
...options
|
|
1808
|
-
};
|
|
1809
|
-
return {
|
|
1810
|
-
...merged,
|
|
1811
|
-
apiBaseUrl: options?.apiBaseUrl ?? `${options?.baseUrl ?? defaultOptions.baseUrl}/v10`,
|
|
1812
|
-
timeout: clampTimerTimeoutMs(merged.timeout, 1) ?? resolveTimerTimeoutMs(defaultOptions.timeout, 1)
|
|
1813
|
-
};
|
|
1814
|
-
}
|
|
1815
|
-
function getRequestPriority(method, path) {
|
|
1816
|
-
const normalizedMethod = method.toUpperCase();
|
|
1817
|
-
const normalizedPath = path.toLowerCase();
|
|
1818
|
-
if (/^\/interactions\/\d+\/[^/]+\/callback$/.test(normalizedPath)) return "critical";
|
|
1819
|
-
return normalizedMethod === "GET" ? "background" : "standard";
|
|
1820
|
-
}
|
|
1821
|
-
// extensions/discord/src/internal/client.ts
|
|
1822
|
-
var Plugin = class {};
|
|
1823
1449
|
var Client = class {
|
|
1824
1450
|
constructor(options, handlers, plugins = []) {
|
|
1825
1451
|
this.plugins = [];
|
|
1826
1452
|
this.componentHandler = new ComponentRegistry();
|
|
1453
|
+
this.commandDeployHashLoaded = false;
|
|
1454
|
+
this.entityEntries = /* @__PURE__ */ new Map();
|
|
1455
|
+
this.lastEntitySweepAt = 0;
|
|
1827
1456
|
this.modalHandler = new ComponentRegistry();
|
|
1828
1457
|
if (!options.clientId) throw new Error("Missing Discord application ID");
|
|
1829
1458
|
if (!options.token) throw new Error("Missing Discord bot token");
|
|
@@ -1831,17 +1460,11 @@ var Client = class {
|
|
|
1831
1460
|
this.commands = handlers.commands ?? [];
|
|
1832
1461
|
this.listeners = handlers.listeners ?? [];
|
|
1833
1462
|
this.rest = new RequestClient(options.token, options.requestOptions);
|
|
1834
|
-
|
|
1835
|
-
this.
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
}
|
|
1839
|
-
this.commandDeployer = new DiscordCommandDeployer({
|
|
1840
|
-
clientId: this.options.clientId,
|
|
1841
|
-
commands: this.commands,
|
|
1842
|
-
hashStore: this.options.commandDeployHashStore,
|
|
1843
|
-
rest: () => this.rest
|
|
1844
|
-
});
|
|
1463
|
+
const eventQueue = this.options.eventQueue;
|
|
1464
|
+
this.eventQueue = eventQueue ? {
|
|
1465
|
+
permits: createPermitPool(eventQueue.maxConcurrency ?? 50),
|
|
1466
|
+
maxQueueSize: eventQueue.maxQueueSize ?? 1e4
|
|
1467
|
+
} : void 0;
|
|
1845
1468
|
for (const component of handlers.components ?? []) this.componentHandler.register(component);
|
|
1846
1469
|
for (const modal of handlers.modals ?? []) this.modalHandler.register(modal);
|
|
1847
1470
|
for (const plugin of plugins) {
|
|
@@ -1852,273 +1475,159 @@ var Client = class {
|
|
|
1852
1475
|
getPlugin(id) {
|
|
1853
1476
|
return this.plugins.find((plugin) => plugin.id === id);
|
|
1854
1477
|
}
|
|
1855
|
-
getRuntimeMetrics() {
|
|
1856
|
-
return { eventQueue: this.eventQueue?.getMetrics() };
|
|
1857
|
-
}
|
|
1858
1478
|
async fetchUser(id) {
|
|
1859
|
-
return await this.
|
|
1479
|
+
return await this.fetchCachedEntity(`user:${id}`, async () => {
|
|
1480
|
+
const raw = await getUser(this.rest, id);
|
|
1481
|
+
return new User(this, raw);
|
|
1482
|
+
});
|
|
1860
1483
|
}
|
|
1861
1484
|
async fetchChannel(id) {
|
|
1862
|
-
return await this.
|
|
1485
|
+
return await this.fetchCachedEntity(`channel:${id}`, async () => {
|
|
1486
|
+
const raw = await getChannel(this.rest, id);
|
|
1487
|
+
return channelFactory(this, raw);
|
|
1488
|
+
});
|
|
1863
1489
|
}
|
|
1864
1490
|
async fetchGuild(id) {
|
|
1865
|
-
return await this.
|
|
1491
|
+
return await this.fetchCachedEntity(`guild:${id}`, async () => {
|
|
1492
|
+
const raw = await getGuild(this.rest, id);
|
|
1493
|
+
return new Guild(this, raw);
|
|
1494
|
+
});
|
|
1866
1495
|
}
|
|
1867
1496
|
async fetchMember(guildId, userId) {
|
|
1868
|
-
return await this.
|
|
1497
|
+
return await this.fetchCachedEntity(`member:${guildId}:${userId}`, async () => {
|
|
1498
|
+
const raw = await getGuildMember(this.rest, guildId, userId);
|
|
1499
|
+
return new GuildMember(this, raw);
|
|
1500
|
+
});
|
|
1869
1501
|
}
|
|
1870
1502
|
async fetchGuildEmojis(guildId, fetcher) {
|
|
1871
|
-
return await this.
|
|
1503
|
+
return await this.fetchCachedEntity(`guild-emojis:${guildId}`, fetcher);
|
|
1504
|
+
}
|
|
1505
|
+
invalidateEntityCacheForGatewayEvent(type, data) {
|
|
1506
|
+
const kind = CACHE_KIND_BY_EVENT.get(type);
|
|
1507
|
+
if (!kind) return;
|
|
1508
|
+
const raw = asRecord(data);
|
|
1509
|
+
if (kind === "member") {
|
|
1510
|
+
const guildId = raw.guild_id;
|
|
1511
|
+
const user = asRecord(raw.user);
|
|
1512
|
+
if (typeof guildId === "string" && typeof user.id === "string") {
|
|
1513
|
+
this.entityEntries.delete(`member:${guildId}:${user.id}`);
|
|
1514
|
+
this.entityEntries.delete(`user:${user.id}`);
|
|
1515
|
+
}
|
|
1516
|
+
} else {
|
|
1517
|
+
const id = kind === "guild-emojis" ? raw.guild_id : raw.id;
|
|
1518
|
+
if (typeof id === "string") this.entityEntries.delete(`${kind}:${id}`);
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
async fetchCachedEntity(key, fetcher) {
|
|
1522
|
+
const now = Date.now();
|
|
1523
|
+
const cached = this.entityEntries.get(key);
|
|
1524
|
+
if (cached && cached.expiresAt > now) return cached.value;
|
|
1525
|
+
if (cached) this.entityEntries.delete(key);
|
|
1526
|
+
const value = await fetcher();
|
|
1527
|
+
this.sweepExpiredEntities(now);
|
|
1528
|
+
this.entityEntries.set(key, {
|
|
1529
|
+
expiresAt: now + DEFAULT_REST_CACHE_TTL_MS,
|
|
1530
|
+
value
|
|
1531
|
+
});
|
|
1532
|
+
if (this.entityEntries.size > DEFAULT_MAX_ENTRIES) this.entityEntries.delete(this.entityEntries.keys().next().value);
|
|
1533
|
+
return value;
|
|
1534
|
+
}
|
|
1535
|
+
sweepExpiredEntities(now) {
|
|
1536
|
+
if (now - this.lastEntitySweepAt < DEFAULT_SWEEP_INTERVAL_MS) return;
|
|
1537
|
+
this.lastEntitySweepAt = now;
|
|
1538
|
+
for (const [key, entry] of this.entityEntries) if (entry.expiresAt <= now) this.entityEntries.delete(key);
|
|
1872
1539
|
}
|
|
1873
1540
|
async deployCommands() {
|
|
1874
|
-
|
|
1541
|
+
const commands = this.commands.filter((command) => command.name !== "*").map((command) => command.serialize());
|
|
1542
|
+
const hash = stableCommandSetHash(commands);
|
|
1543
|
+
await this.loadPersistedHash();
|
|
1544
|
+
if (this.commandDeployHash === hash) return;
|
|
1545
|
+
await this.reconcileGlobalCommands(commands);
|
|
1546
|
+
this.commandDeployHash = hash;
|
|
1547
|
+
try {
|
|
1548
|
+
await this.options.commandDeployHashStore?.register(this.commandDeployCacheKey, hash);
|
|
1549
|
+
} catch {}
|
|
1550
|
+
}
|
|
1551
|
+
get commandDeployCacheKey() {
|
|
1552
|
+
return `app:${this.options.clientId}:global:reconcile`;
|
|
1553
|
+
}
|
|
1554
|
+
async reconcileGlobalCommands(desired) {
|
|
1555
|
+
const existing = await this.requestCommandDeploy("get", Routes.applicationCommands(this.options.clientId));
|
|
1556
|
+
const existingByKey = new Map(existing.map((command) => [stableCommandKey(command), command]));
|
|
1557
|
+
const desiredCommands = desired.map((command) => ({
|
|
1558
|
+
command,
|
|
1559
|
+
key: stableCommandKey(command)
|
|
1560
|
+
}));
|
|
1561
|
+
const desiredKeys = new Set(desiredCommands.map(({ key }) => key));
|
|
1562
|
+
for (const { command, key } of desiredCommands) {
|
|
1563
|
+
const current = existingByKey.get(key);
|
|
1564
|
+
if (current && !commandsEqual(current, command)) await this.requestCommandDeploy("patch", Routes.applicationCommand(this.options.clientId, current.id), command);
|
|
1565
|
+
}
|
|
1566
|
+
for (const { command, key } of desiredCommands) {
|
|
1567
|
+
if (existingByKey.has(key)) continue;
|
|
1568
|
+
try {
|
|
1569
|
+
await this.requestCommandDeploy("post", Routes.applicationCommands(this.options.clientId), command);
|
|
1570
|
+
} catch (error) {
|
|
1571
|
+
if (!(error !== null && typeof error === "object" && "discordCode" in error && error.discordCode === DISCORD_APPLICATION_COMMAND_LIMIT_REACHED)) throw error;
|
|
1572
|
+
await this.requestCommandDeploy("put", Routes.applicationCommands(this.options.clientId), desired);
|
|
1573
|
+
return;
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
for (const command of existing) if (!desiredKeys.has(stableCommandKey(command))) await this.requestCommandDeploy("delete", Routes.applicationCommand(this.options.clientId, command.id));
|
|
1577
|
+
}
|
|
1578
|
+
async loadPersistedHash() {
|
|
1579
|
+
if (this.commandDeployHashLoaded) return;
|
|
1580
|
+
this.commandDeployHashLoaded = true;
|
|
1581
|
+
try {
|
|
1582
|
+
this.commandDeployHash = await this.options.commandDeployHashStore?.lookup(this.commandDeployCacheKey);
|
|
1583
|
+
} catch {}
|
|
1584
|
+
}
|
|
1585
|
+
async requestCommandDeploy(method, path, body) {
|
|
1586
|
+
const rest = this.rest;
|
|
1587
|
+
const timeoutMs = rest.options.timeout;
|
|
1588
|
+
const startedAt = Date.now();
|
|
1589
|
+
try {
|
|
1590
|
+
return method === "get" || body === void 0 ? await rest[method](path) : await rest[method](path, { body });
|
|
1591
|
+
} catch (error) {
|
|
1592
|
+
if (error && typeof error === "object") {
|
|
1593
|
+
if (body !== void 0 && (!("deployRequestBody" in error) || error.deployRequestBody === void 0)) Object.assign(error, { deployRequestBody: body });
|
|
1594
|
+
Object.assign(error, {
|
|
1595
|
+
deployRestMethod: method,
|
|
1596
|
+
deployRestPath: path,
|
|
1597
|
+
deployRequestMs: Date.now() - startedAt,
|
|
1598
|
+
...Number.isFinite(timeoutMs) ? { deployTimeoutMs: timeoutMs } : {}
|
|
1599
|
+
});
|
|
1600
|
+
}
|
|
1601
|
+
throw error;
|
|
1602
|
+
}
|
|
1875
1603
|
}
|
|
1876
1604
|
async handleInteraction(rawData) {
|
|
1877
1605
|
await dispatchInteraction(this, rawData);
|
|
1878
1606
|
}
|
|
1879
1607
|
async dispatchGatewayEvent(type, data) {
|
|
1880
|
-
this.
|
|
1608
|
+
this.invalidateEntityCacheForGatewayEvent(type, data);
|
|
1881
1609
|
const listeners = this.listeners.filter((entry) => entry.type === type);
|
|
1882
1610
|
if (!this.eventQueue) {
|
|
1883
1611
|
for (const listener of listeners) await listener.handle(data, this);
|
|
1884
1612
|
return;
|
|
1885
1613
|
}
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1614
|
+
const queue = this.eventQueue;
|
|
1615
|
+
await Promise.all(listeners.map(async (listener) => {
|
|
1616
|
+
if (queue.permits.pendingCount >= queue.maxQueueSize) throw new Error(`Discord event queue is full for ${type}; maxQueueSize=${queue.maxQueueSize}`);
|
|
1617
|
+
const listenerName = listener.constructor.name || "AnonymousListener";
|
|
1618
|
+
const release = await queue.permits.acquire();
|
|
1619
|
+
const startedAt = Date.now();
|
|
1620
|
+
try {
|
|
1890
1621
|
await listener.handle(data, this);
|
|
1622
|
+
const durationMs = Date.now() - startedAt;
|
|
1623
|
+
if (durationMs < 3e4) return;
|
|
1624
|
+
console.warn(`[EventQueue] Slow listener detected: ${listenerName} took ${durationMs}ms for event ${type}`);
|
|
1625
|
+
} catch (error) {
|
|
1626
|
+
console.error(`[EventQueue] Listener ${listenerName} failed for event ${type}:`, error);
|
|
1627
|
+
} finally {
|
|
1628
|
+
release?.();
|
|
1891
1629
|
}
|
|
1892
|
-
}))
|
|
1893
|
-
}
|
|
1894
|
-
};
|
|
1895
|
-
// extensions/discord/src/internal/components.message.ts
|
|
1896
|
-
var BaseButton = class extends BaseMessageInteractiveComponent {
|
|
1897
|
-
constructor(..._args) {
|
|
1898
|
-
super(..._args);
|
|
1899
|
-
this.type = ComponentType.Button;
|
|
1900
|
-
this.style = ButtonStyle.Primary;
|
|
1901
|
-
this.disabled = false;
|
|
1902
|
-
}
|
|
1903
|
-
serialize() {
|
|
1904
|
-
const link = this instanceof LinkButton;
|
|
1905
|
-
return stripUndefinedFields({
|
|
1906
|
-
type: this.type,
|
|
1907
|
-
style: this.style,
|
|
1908
|
-
custom_id: link ? void 0 : this.customId,
|
|
1909
|
-
label: this.label,
|
|
1910
|
-
emoji: this.emoji,
|
|
1911
|
-
disabled: this.disabled || void 0,
|
|
1912
|
-
url: link ? this.url : void 0
|
|
1913
|
-
});
|
|
1914
|
-
}
|
|
1915
|
-
};
|
|
1916
|
-
var Button = class extends BaseButton {};
|
|
1917
|
-
var LinkButton = class extends BaseButton {
|
|
1918
|
-
constructor(..._args2) {
|
|
1919
|
-
super(..._args2);
|
|
1920
|
-
this.customId = "";
|
|
1921
|
-
this.style = ButtonStyle.Link;
|
|
1922
|
-
}
|
|
1923
|
-
async run() {
|
|
1924
|
-
throw new Error("Link buttons do not run handlers");
|
|
1925
|
-
}
|
|
1926
|
-
};
|
|
1927
|
-
var AnySelectMenu = class extends BaseMessageInteractiveComponent {
|
|
1928
|
-
constructor(..._args3) {
|
|
1929
|
-
super(..._args3);
|
|
1930
|
-
this.disabled = false;
|
|
1931
|
-
}
|
|
1932
|
-
serializeOptions() {
|
|
1933
|
-
return {
|
|
1934
|
-
type: this.type,
|
|
1935
|
-
default_values: this.defaultValues
|
|
1936
|
-
};
|
|
1937
|
-
}
|
|
1938
|
-
serialize() {
|
|
1939
|
-
return stripUndefinedFields({
|
|
1940
|
-
...this.serializeOptions(),
|
|
1941
|
-
custom_id: this.customId,
|
|
1942
|
-
placeholder: this.placeholder,
|
|
1943
|
-
min_values: this.minValues,
|
|
1944
|
-
max_values: this.maxValues,
|
|
1945
|
-
disabled: this.disabled || void 0,
|
|
1946
|
-
required: this.required
|
|
1947
|
-
});
|
|
1948
|
-
}
|
|
1949
|
-
};
|
|
1950
|
-
var StringSelectMenu = class extends AnySelectMenu {
|
|
1951
|
-
constructor(..._args4) {
|
|
1952
|
-
super(..._args4);
|
|
1953
|
-
this.type = ComponentType.StringSelect;
|
|
1954
|
-
}
|
|
1955
|
-
serializeOptions() {
|
|
1956
|
-
return {
|
|
1957
|
-
type: this.type,
|
|
1958
|
-
options: this.options
|
|
1959
|
-
};
|
|
1960
|
-
}
|
|
1961
|
-
};
|
|
1962
|
-
var UserSelectMenu = class extends AnySelectMenu {
|
|
1963
|
-
constructor(..._args5) {
|
|
1964
|
-
super(..._args5);
|
|
1965
|
-
this.type = ComponentType.UserSelect;
|
|
1966
|
-
}
|
|
1967
|
-
};
|
|
1968
|
-
var RoleSelectMenu = class extends AnySelectMenu {
|
|
1969
|
-
constructor(..._args6) {
|
|
1970
|
-
super(..._args6);
|
|
1971
|
-
this.type = ComponentType.RoleSelect;
|
|
1972
|
-
}
|
|
1973
|
-
};
|
|
1974
|
-
var MentionableSelectMenu = class extends AnySelectMenu {
|
|
1975
|
-
constructor(..._args7) {
|
|
1976
|
-
super(..._args7);
|
|
1977
|
-
this.type = ComponentType.MentionableSelect;
|
|
1978
|
-
}
|
|
1979
|
-
};
|
|
1980
|
-
var ChannelSelectMenu = class extends AnySelectMenu {
|
|
1981
|
-
constructor(..._args8) {
|
|
1982
|
-
super(..._args8);
|
|
1983
|
-
this.type = ComponentType.ChannelSelect;
|
|
1984
|
-
}
|
|
1985
|
-
serializeOptions() {
|
|
1986
|
-
return {
|
|
1987
|
-
type: this.type,
|
|
1988
|
-
default_values: this.defaultValues,
|
|
1989
|
-
channel_types: this.channelTypes
|
|
1990
|
-
};
|
|
1991
|
-
}
|
|
1992
|
-
};
|
|
1993
|
-
var Row = class extends BaseComponent {
|
|
1994
|
-
constructor(components = []) {
|
|
1995
|
-
super();
|
|
1996
|
-
this.components = components;
|
|
1997
|
-
this.type = ComponentType.ActionRow;
|
|
1998
|
-
this.isV2 = false;
|
|
1999
|
-
}
|
|
2000
|
-
addComponent(component) {
|
|
2001
|
-
this.components.push(component);
|
|
2002
|
-
}
|
|
2003
|
-
serialize() {
|
|
2004
|
-
return {
|
|
2005
|
-
type: this.type,
|
|
2006
|
-
components: this.components.map((entry) => entry.serialize())
|
|
2007
|
-
};
|
|
2008
|
-
}
|
|
2009
|
-
};
|
|
2010
|
-
var V2Component = class extends BaseComponent {
|
|
2011
|
-
constructor(..._args9) {
|
|
2012
|
-
super(..._args9);
|
|
2013
|
-
this.isV2 = true;
|
|
2014
|
-
}
|
|
2015
|
-
};
|
|
2016
|
-
var TextDisplay = class extends V2Component {
|
|
2017
|
-
constructor(content) {
|
|
2018
|
-
super();
|
|
2019
|
-
this.content = content;
|
|
2020
|
-
this.type = ComponentType.TextDisplay;
|
|
2021
|
-
}
|
|
2022
|
-
serialize() {
|
|
2023
|
-
return stripUndefinedFields({
|
|
2024
|
-
type: this.type,
|
|
2025
|
-
content: this.content
|
|
2026
|
-
});
|
|
2027
|
-
}
|
|
2028
|
-
};
|
|
2029
|
-
var Separator = class extends V2Component {
|
|
2030
|
-
constructor(options) {
|
|
2031
|
-
super();
|
|
2032
|
-
this.type = ComponentType.Separator;
|
|
2033
|
-
this.divider = true;
|
|
2034
|
-
this.spacing = "small";
|
|
2035
|
-
this.spacing = options?.spacing ?? this.spacing;
|
|
2036
|
-
this.divider = options?.divider ?? this.divider;
|
|
2037
|
-
}
|
|
2038
|
-
serialize() {
|
|
2039
|
-
return stripUndefinedFields({
|
|
2040
|
-
type: this.type,
|
|
2041
|
-
divider: this.divider,
|
|
2042
|
-
spacing: this.spacing === "large" ? 2 : this.spacing === "small" ? 1 : this.spacing
|
|
2043
|
-
});
|
|
2044
|
-
}
|
|
2045
|
-
};
|
|
2046
|
-
var Thumbnail = class extends V2Component {
|
|
2047
|
-
constructor(url) {
|
|
2048
|
-
super();
|
|
2049
|
-
this.url = url;
|
|
2050
|
-
this.type = ComponentType.Thumbnail;
|
|
2051
|
-
}
|
|
2052
|
-
serialize() {
|
|
2053
|
-
return stripUndefinedFields({
|
|
2054
|
-
type: this.type,
|
|
2055
|
-
media: this.url ? { url: this.url } : void 0
|
|
2056
|
-
});
|
|
2057
|
-
}
|
|
2058
|
-
};
|
|
2059
|
-
var Section = class extends V2Component {
|
|
2060
|
-
constructor(components = [], accessory) {
|
|
2061
|
-
super();
|
|
2062
|
-
this.components = components;
|
|
2063
|
-
this.accessory = accessory;
|
|
2064
|
-
this.type = ComponentType.Section;
|
|
2065
|
-
}
|
|
2066
|
-
serialize() {
|
|
2067
|
-
return stripUndefinedFields({
|
|
2068
|
-
type: this.type,
|
|
2069
|
-
components: this.components.map((entry) => entry.serialize()),
|
|
2070
|
-
accessory: this.accessory?.serialize()
|
|
2071
|
-
});
|
|
2072
|
-
}
|
|
2073
|
-
};
|
|
2074
|
-
var MediaGallery = class extends V2Component {
|
|
2075
|
-
constructor(items = []) {
|
|
2076
|
-
super();
|
|
2077
|
-
this.items = items;
|
|
2078
|
-
this.type = ComponentType.MediaGallery;
|
|
2079
|
-
}
|
|
2080
|
-
serialize() {
|
|
2081
|
-
return {
|
|
2082
|
-
type: this.type,
|
|
2083
|
-
items: this.items.map((entry) => ({
|
|
2084
|
-
media: { url: entry.url },
|
|
2085
|
-
description: entry.description,
|
|
2086
|
-
spoiler: entry.spoiler
|
|
2087
|
-
}))
|
|
2088
|
-
};
|
|
2089
|
-
}
|
|
2090
|
-
};
|
|
2091
|
-
var File = class extends V2Component {
|
|
2092
|
-
constructor(file, spoiler = false) {
|
|
2093
|
-
super();
|
|
2094
|
-
this.file = file;
|
|
2095
|
-
this.spoiler = spoiler;
|
|
2096
|
-
this.type = ComponentType.File;
|
|
2097
|
-
}
|
|
2098
|
-
serialize() {
|
|
2099
|
-
return stripUndefinedFields({
|
|
2100
|
-
type: this.type,
|
|
2101
|
-
file: this.file ? { url: this.file } : void 0,
|
|
2102
|
-
spoiler: this.spoiler || void 0
|
|
2103
|
-
});
|
|
2104
|
-
}
|
|
2105
|
-
};
|
|
2106
|
-
var Container = class extends V2Component {
|
|
2107
|
-
constructor(components = [], options) {
|
|
2108
|
-
super();
|
|
2109
|
-
this.components = components;
|
|
2110
|
-
this.type = ComponentType.Container;
|
|
2111
|
-
this.spoiler = false;
|
|
2112
|
-
this.accentColor = options?.accentColor;
|
|
2113
|
-
this.spoiler = options?.spoiler ?? false;
|
|
2114
|
-
}
|
|
2115
|
-
serialize() {
|
|
2116
|
-
return stripUndefinedFields({
|
|
2117
|
-
type: this.type,
|
|
2118
|
-
components: this.components.map((entry) => entry.serialize()),
|
|
2119
|
-
accent_color: colorToNumber(this.accentColor),
|
|
2120
|
-
spoiler: this.spoiler || void 0
|
|
2121
|
-
});
|
|
1630
|
+
}));
|
|
2122
1631
|
}
|
|
2123
1632
|
};
|
|
2124
1633
|
// extensions/discord/src/internal/components.modal.ts
|
|
@@ -2213,117 +1722,33 @@ var GuildCreateListener = class extends BaseListener {
|
|
|
2213
1722
|
this.type = GatewayDispatchEvents.GuildCreate;
|
|
2214
1723
|
}
|
|
2215
1724
|
};
|
|
2216
|
-
var GuildDeleteListener = class extends BaseListener {
|
|
2217
|
-
constructor(..._args3) {
|
|
2218
|
-
super(..._args3);
|
|
2219
|
-
this.type = GatewayDispatchEvents.GuildDelete;
|
|
2220
|
-
}
|
|
2221
|
-
};
|
|
2222
|
-
var MessageCreateListener = class extends BaseListener {
|
|
2223
|
-
constructor(..._args4) {
|
|
2224
|
-
super(..._args4);
|
|
2225
|
-
this.type = GatewayDispatchEvents.MessageCreate;
|
|
2226
|
-
}
|
|
2227
|
-
};
|
|
2228
|
-
var InteractionCreateListener = class extends BaseListener {
|
|
2229
|
-
constructor(..._args5) {
|
|
2230
|
-
super(..._args5);
|
|
2231
|
-
this.type = GatewayDispatchEvents.InteractionCreate;
|
|
2232
|
-
}
|
|
2233
|
-
};
|
|
2234
|
-
var MessageReactionAddListener = class extends BaseListener {
|
|
2235
|
-
constructor(..._args6) {
|
|
2236
|
-
super(..._args6);
|
|
2237
|
-
this.type = GatewayDispatchEvents.MessageReactionAdd;
|
|
2238
|
-
}
|
|
2239
|
-
};
|
|
2240
|
-
var MessageReactionRemoveListener = class extends BaseListener {
|
|
2241
|
-
constructor(..._args7) {
|
|
2242
|
-
super(..._args7);
|
|
2243
|
-
this.type = GatewayDispatchEvents.MessageReactionRemove;
|
|
2244
|
-
}
|
|
2245
|
-
};
|
|
2246
|
-
var PresenceUpdateListener = class extends BaseListener {
|
|
2247
|
-
constructor(..._args8) {
|
|
2248
|
-
super(..._args8);
|
|
2249
|
-
this.type = GatewayDispatchEvents.PresenceUpdate;
|
|
2250
|
-
}
|
|
2251
|
-
};
|
|
2252
|
-
var VoiceStateUpdateListener = class extends BaseListener {
|
|
2253
|
-
constructor(..._args9) {
|
|
2254
|
-
super(..._args9);
|
|
2255
|
-
this.type = GatewayDispatchEvents.VoiceStateUpdate;
|
|
2256
|
-
}
|
|
2257
|
-
};
|
|
2258
|
-
var ThreadUpdateListener = class extends BaseListener {
|
|
2259
|
-
constructor(..._args10) {
|
|
2260
|
-
super(..._args10);
|
|
2261
|
-
this.type = GatewayDispatchEvents.ThreadUpdate;
|
|
2262
|
-
}
|
|
2263
|
-
};
|
|
2264
|
-
var ThreadDeleteListener = class extends BaseListener {
|
|
2265
|
-
constructor(..._args11) {
|
|
2266
|
-
super(..._args11);
|
|
2267
|
-
this.type = GatewayDispatchEvents.ThreadDelete;
|
|
2268
|
-
}
|
|
2269
|
-
};
|
|
2270
1725
|
// extensions/discord/src/internal/discord.ts
|
|
2271
1726
|
var discord_exports = /* @__PURE__ */ __exportAll({
|
|
2272
1727
|
AutocompleteInteraction: () => AutocompleteInteraction,
|
|
2273
1728
|
BaseCommand: () => BaseCommand,
|
|
2274
1729
|
BaseComponentInteraction: () => BaseComponentInteraction,
|
|
2275
1730
|
BaseMessageInteractiveComponent: () => BaseMessageInteractiveComponent,
|
|
2276
|
-
Button: () => Button,
|
|
2277
|
-
ButtonInteraction: () => ButtonInteraction,
|
|
2278
|
-
ChannelSelectMenu: () => ChannelSelectMenu,
|
|
2279
|
-
CheckboxGroup: () => CheckboxGroup,
|
|
2280
1731
|
Client: () => Client,
|
|
2281
1732
|
Command: () => Command,
|
|
2282
1733
|
CommandInteraction: () => CommandInteraction,
|
|
2283
1734
|
CommandWithSubcommands: () => CommandWithSubcommands,
|
|
2284
|
-
|
|
1735
|
+
DISCORD_REST_TIMEOUT_MS: () => DISCORD_REST_TIMEOUT_MS,
|
|
2285
1736
|
DiscordError: () => DiscordError,
|
|
2286
1737
|
Embed: () => Embed,
|
|
2287
|
-
File: () => File,
|
|
2288
1738
|
Guild: () => Guild,
|
|
2289
1739
|
GuildCreateListener: () => GuildCreateListener,
|
|
2290
|
-
GuildDeleteListener: () => GuildDeleteListener,
|
|
2291
1740
|
GuildMember: () => GuildMember,
|
|
2292
|
-
InteractionCreateListener: () => InteractionCreateListener,
|
|
2293
|
-
Label: () => Label,
|
|
2294
|
-
LinkButton: () => LinkButton,
|
|
2295
|
-
MediaGallery: () => MediaGallery,
|
|
2296
|
-
MentionableSelectMenu: () => MentionableSelectMenu,
|
|
2297
1741
|
Message: () => Message,
|
|
2298
|
-
MessageCreateListener: () => MessageCreateListener,
|
|
2299
|
-
MessageReactionAddListener: () => MessageReactionAddListener,
|
|
2300
|
-
MessageReactionRemoveListener: () => MessageReactionRemoveListener,
|
|
2301
1742
|
Modal: () => Modal,
|
|
2302
1743
|
ModalInteraction: () => ModalInteraction,
|
|
2303
|
-
Plugin: () => Plugin,
|
|
2304
|
-
PresenceUpdateListener: () => PresenceUpdateListener,
|
|
2305
|
-
RadioGroup: () => RadioGroup,
|
|
2306
1744
|
RateLimitError: () => RateLimitError,
|
|
2307
1745
|
ReadyListener: () => ReadyListener,
|
|
2308
1746
|
RequestClient: () => RequestClient,
|
|
2309
1747
|
Role: () => Role,
|
|
2310
|
-
RoleSelectMenu: () => RoleSelectMenu,
|
|
2311
|
-
Row: () => Row,
|
|
2312
|
-
Section: () => Section,
|
|
2313
|
-
Separator: () => Separator,
|
|
2314
|
-
StringSelectMenu: () => StringSelectMenu,
|
|
2315
|
-
StringSelectMenuInteraction: () => StringSelectMenuInteraction,
|
|
2316
|
-
TextDisplay: () => TextDisplay,
|
|
2317
|
-
TextInput: () => TextInput,
|
|
2318
|
-
ThreadDeleteListener: () => ThreadDeleteListener,
|
|
2319
|
-
ThreadUpdateListener: () => ThreadUpdateListener,
|
|
2320
|
-
Thumbnail: () => Thumbnail,
|
|
2321
1748
|
User: () => User,
|
|
2322
|
-
|
|
2323
|
-
VoiceStateUpdateListener: () => VoiceStateUpdateListener,
|
|
1749
|
+
asSerializableComponent: () => asSerializableComponent,
|
|
2324
1750
|
channelFactory: () => channelFactory,
|
|
2325
1751
|
createChannelMessage: () => createChannelMessage,
|
|
2326
|
-
createChannelWebhook: () => createChannelWebhook,
|
|
2327
1752
|
createInteraction: () => createInteraction,
|
|
2328
1753
|
createOwnMessageReaction: () => createOwnMessageReaction,
|
|
2329
1754
|
createThread: () => createThread,
|
|
@@ -2341,12 +1766,10 @@ var discord_exports = /* @__PURE__ */ __exportAll({
|
|
|
2341
1766
|
getThreadMember: () => getThreadMember,
|
|
2342
1767
|
getUser: () => getUser,
|
|
2343
1768
|
hasDiscordV2Components: () => hasDiscordV2Components,
|
|
2344
|
-
isUnknownDiscordMessageError: () => isUnknownDiscordMessageError,
|
|
2345
1769
|
isUnknownDiscordVoiceStateError: () => isUnknownDiscordVoiceStateError,
|
|
2346
1770
|
listGuildEmojis: () => listGuildEmojis,
|
|
2347
1771
|
listMessageReactionUsers: () => listMessageReactionUsers,
|
|
2348
1772
|
normalizeDiscordMessageId: () => normalizeDiscordMessageId,
|
|
2349
|
-
parseCustomId: () => parseCustomId,
|
|
2350
1773
|
pinChannelMessage: () => pinChannelMessage,
|
|
2351
1774
|
resolveFocusedCommandOptionAutocompleteHandler: () => resolveFocusedCommandOptionAutocompleteHandler,
|
|
2352
1775
|
serializePayload: () => serializePayload,
|
|
@@ -2354,4 +1777,4 @@ var discord_exports = /* @__PURE__ */ __exportAll({
|
|
|
2354
1777
|
});
|
|
2355
1778
|
import * as import_discord_api_types_v10 from "discord-api-types/v10";
|
|
2356
1779
|
__reExport(discord_exports, import_discord_api_types_v10);
|
|
2357
|
-
export {
|
|
1780
|
+
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 };
|