@effect/chat-discord 0.0.0 → 4.1.5

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.
Files changed (132) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +27 -0
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/52_graphql/10_basics.ts +117 -0
  69. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  70. package/ai-docs/src/52_graphql/30_batching.ts +118 -0
  71. package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
  72. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  73. package/ai-docs/src/52_graphql/index.md +6 -0
  74. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  75. package/ai-docs/src/60_child-process/index.md +3 -0
  76. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  77. package/ai-docs/src/70_cli/index.md +5 -0
  78. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  79. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  80. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  81. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  82. package/ai-docs/src/71_ai/index.md +5 -0
  83. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  84. package/ai-docs/src/80_cluster/index.md +4 -0
  85. package/ai-docs/src/index.md +10 -0
  86. package/ai-docs/tsconfig.json +28 -0
  87. package/dist/DiscordChat.d.ts +530 -0
  88. package/dist/DiscordChat.d.ts.map +1 -0
  89. package/dist/DiscordChat.js +574 -0
  90. package/dist/DiscordChat.js.map +1 -0
  91. package/dist/index.d.ts +10 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +11 -0
  94. package/dist/index.js.map +1 -0
  95. package/dist/internal/adapter.d.ts +2 -0
  96. package/dist/internal/adapter.d.ts.map +1 -0
  97. package/dist/internal/adapter.js +492 -0
  98. package/dist/internal/adapter.js.map +1 -0
  99. package/dist/internal/errors.d.ts +2 -0
  100. package/dist/internal/errors.d.ts.map +1 -0
  101. package/dist/internal/errors.js +236 -0
  102. package/dist/internal/errors.js.map +1 -0
  103. package/dist/internal/interactions.d.ts +2 -0
  104. package/dist/internal/interactions.d.ts.map +1 -0
  105. package/dist/internal/interactions.js +490 -0
  106. package/dist/internal/interactions.js.map +1 -0
  107. package/dist/internal/length.d.ts +2 -0
  108. package/dist/internal/length.d.ts.map +1 -0
  109. package/dist/internal/length.js +31 -0
  110. package/dist/internal/length.js.map +1 -0
  111. package/dist/internal/mentions.d.ts +2 -0
  112. package/dist/internal/mentions.d.ts.map +1 -0
  113. package/dist/internal/mentions.js +93 -0
  114. package/dist/internal/mentions.js.map +1 -0
  115. package/dist/internal/normalize.d.ts +2 -0
  116. package/dist/internal/normalize.d.ts.map +1 -0
  117. package/dist/internal/normalize.js +322 -0
  118. package/dist/internal/normalize.js.map +1 -0
  119. package/dist/internal/options.d.ts +2 -0
  120. package/dist/internal/options.d.ts.map +1 -0
  121. package/dist/internal/options.js +25 -0
  122. package/dist/internal/options.js.map +1 -0
  123. package/package.json +63 -1
  124. package/src/DiscordChat.ts +703 -0
  125. package/src/index.ts +12 -0
  126. package/src/internal/adapter.ts +653 -0
  127. package/src/internal/errors.ts +184 -0
  128. package/src/internal/interactions.ts +451 -0
  129. package/src/internal/length.ts +33 -0
  130. package/src/internal/mentions.ts +101 -0
  131. package/src/internal/normalize.ts +363 -0
  132. package/src/internal/options.ts +29 -0
@@ -0,0 +1,703 @@
1
+ /**
2
+ * The Discord adapter for `effect/chat`: the `Registry` layer, the
3
+ * structural dispatch and interaction entries, the pure normalisers, the
4
+ * gateway layers, address helpers and the scoped post options. It runs on
5
+ * dfx: every REST call goes through the `DiscordREST` in context.
6
+ *
7
+ * **Details**
8
+ *
9
+ * - Gateway intents: `GUILDS`, `GUILD_MESSAGES`, `GUILD_MESSAGE_REACTIONS`,
10
+ * `DIRECT_MESSAGES`, `DIRECT_MESSAGE_REACTIONS` and `MESSAGE_CONTENT`.
11
+ * They are set in the consumer's dfx config.
12
+ * - `MESSAGE_CONTENT` is a privileged intent: switch it on for the
13
+ * application in Discord's developer portal. Without it, `text` is empty
14
+ * on every message that doesn't mention the bot, and attachments are
15
+ * missing.
16
+ * - Bot permissions: View Channel, Send Messages, Send Messages in Threads,
17
+ * Create Public Threads, Read Message History and Attach Files.
18
+ * - Slash commands need the `applications.commands` scope, and are
19
+ * registered by the consumer with the payloads `commandRequests` gives.
20
+ *
21
+ * @stability unstable
22
+ * @since 4.1.5
23
+ */
24
+ import { DiscordConfig } from "dfx/DiscordConfig"
25
+ import { DiscordGateway } from "dfx/DiscordGateway"
26
+ import { DispatchHook } from "dfx/DiscordGateway/Shard/DispatchHook"
27
+ import { DiscordREST } from "dfx/DiscordREST"
28
+ import * as Cause from "effect/Cause"
29
+ import { Registry } from "effect/chat/ChatAdapter"
30
+ import type { ChatError } from "effect/chat/ChatError"
31
+ import type { ChatEvent, MessageCreated, ReactionAdded } from "effect/chat/ChatEvent"
32
+ import { ChatHandler, NotAccepted } from "effect/chat/ChatHandler"
33
+ import * as ChatInteraction from "effect/chat/ChatInteraction"
34
+ import type { ParseMention } from "effect/chat/ChatTest"
35
+ import type { ChatThread } from "effect/chat/ChatThread"
36
+ import * as Context from "effect/Context"
37
+ import * as Duration from "effect/Duration"
38
+ import * as Effect from "effect/Effect"
39
+ import { dual } from "effect/Function"
40
+ import * as HttpClient from "effect/http/HttpClient"
41
+ import * as Layer from "effect/Layer"
42
+ import * as Option from "effect/Option"
43
+ import * as Result from "effect/Result"
44
+ import * as Schema from "effect/Schema"
45
+ import * as Stream from "effect/Stream"
46
+ import * as Adapter from "./internal/adapter.ts"
47
+ import * as Errors from "./internal/errors.ts"
48
+ import * as Interactions from "./internal/interactions.ts"
49
+ import * as Mentions from "./internal/mentions.ts"
50
+ import * as Normalize from "./internal/normalize.ts"
51
+ import { CurrentPostOptions } from "./internal/options.ts"
52
+
53
+ /**
54
+ * The Discord side of the adapter, for what the core has no op for.
55
+ *
56
+ * **Details**
57
+ *
58
+ * - `botUserId` comes from `GET /users/@me`, read once. A failed read is
59
+ * tried again next time.
60
+ * - `dispatch` takes one gateway dispatch, `{ t, d }`, and hands its
61
+ * events to the `ChatHandler` one at a time. It reads `d` with a Schema
62
+ * and ignores what it doesn't know, so it takes no dfx type.
63
+ * - When a `MESSAGE_CREATE` carries no `channel_type`, `dispatch` looks
64
+ * the channel up, cached and with a five second timeout. A failed lookup
65
+ * is logged and fails with `NotAccepted`. A lookup that would fail the same
66
+ * way again, such as a deleted channel, is logged and the event dropped.
67
+ * - `interaction` takes one `INTERACTION_CREATE` payload, from the gateway
68
+ * or from an HTTP interactions endpoint. It reads it with a Schema, so it
69
+ * takes no dfx type, and ignores an interaction it can't express: a
70
+ * message or user command, an autocomplete request, a slash command with
71
+ * anything but at most one string option. It calls the handler through
72
+ * `ChatInteraction.handle` and answers through the interaction callback
73
+ * endpoint, which has to land inside Discord's 3 seconds: `deadline` is
74
+ * the handler's share, 2 seconds by default.
75
+ * - A click is answered with callback type 6, or type 9 for `OpenModal`.
76
+ * A submit's `close` is type 6. An `errors` reply is type 4 with the
77
+ * ephemeral flag, listing each message as plain text, and the modal closes: Discord
78
+ * can't show an error inside a modal, so the descriptor has no
79
+ * `modalErrors`.
80
+ * - A slash command goes to `Handler.command`. `respond` is callback type
81
+ * 4 with the message a `post` sends, `defer` type 5 and `OpenModal` type
82
+ * 9, each with the ephemeral flag when private. An `Ack`, which is what a
83
+ * command nobody handles gets, sends nothing, so a command another library
84
+ * owns is left to it. `withPostOptions` does not reach a command's
85
+ * answer, `respond` or `followUp`: a mention in it renders and notifies
86
+ * nobody.
87
+ * - Commands were recorded in a guild channel over the gateway. A command
88
+ * in a direct is from Discord's docs and was not run.
89
+ * - A click on a private answer carries the message, with the ephemeral flag
90
+ * (64). Its `messageId` tells which answer was clicked. Discord's docs
91
+ * reach an interaction's messages only through its token, under
92
+ * `/webhooks`, and say nothing of the channel routes `Chat.edit`,
93
+ * `delete` and `fetchMessage` use on an ephemeral message. Treat the id
94
+ * as one no message op works with. This is from the docs: no op on it was
95
+ * run.
96
+ * - `followUp` edits the deferred command's original response, with the
97
+ * application id and token from its `raw`, so a second call replaces the
98
+ * first answer. It fails `NotFound` with detail `interaction_expired`
99
+ * from 15 minutes after the command, read from the interaction's id,
100
+ * without calling Discord. Otherwise it makes one HTTP request, through
101
+ * the layer's `HttpClient` and not dfx's client, and never sends it
102
+ * again, unless that `HttpClient` retries by itself: a 429 fails
103
+ * `RateLimited`, for the caller to retry or not.
104
+ * Discord answers 401 with code 50027 past 15 minutes, which is
105
+ * `interaction_expired` too. Code 10015 is mapped from the docs and was
106
+ * not seen.
107
+ * - A modal that can't be built, a reply to a command that fails the checks
108
+ * of a `post`, or a callback that fails, goes to `Handler.refused`. A
109
+ * callback that comes back 404 `Unknown interaction` was late: that is
110
+ * `NotFound` with detail `interaction_expired`. A failed ack is logged.
111
+ * - `guild` reads the channel, cached. `None` for a direct.
112
+ *
113
+ * @stability unstable
114
+ * @category services
115
+ * @since 4.1.5
116
+ */
117
+ export class DiscordChat extends Context.Service<DiscordChat, {
118
+ readonly botUserId: Effect.Effect<string, ChatError>
119
+ readonly dispatch: (dispatch: {
120
+ readonly t: string
121
+ readonly d: unknown
122
+ }) => Effect.Effect<void, NotAccepted, ChatHandler>
123
+ readonly interaction: (interaction: unknown, options?: {
124
+ /** The handler's share of Discord's 3 seconds. Default 2 seconds. */
125
+ readonly deadline?: Duration.Duration | undefined
126
+ }) => Effect.Effect<void, never, ChatInteraction.Handler>
127
+ readonly guild: (thread: ChatThread) => Effect.Effect<Option.Option<string>, ChatError>
128
+ }>()("@effect/chat-discord/DiscordChat") {}
129
+
130
+ /** The dispatches `normalize` reads. */
131
+ const handled = new Set(["MESSAGE_CREATE", "MESSAGE_REACTION_ADD", "MESSAGE_REACTION_REMOVE"])
132
+
133
+ const lookupTimeout = Duration.seconds(5)
134
+
135
+ /**
136
+ * Registers the Discord adapter in the `Registry`.
137
+ *
138
+ * **Details**
139
+ *
140
+ * - Every REST call but `followUp` goes through the `DiscordREST` in
141
+ * context. dfx waits on its rate-limit buckets and sends again after a
142
+ * 429, so a rate limit shows up as a slower call.
143
+ * - `HttpClient` downloads attachments from Discord's CDN, with no token,
144
+ * and sends `followUp`'s edit, which needs no bot token either. That edit
145
+ * skips dfx's client so a 429 is not sent again past the 15 minutes. It
146
+ * goes to the `rest.baseUrl` of the `DiscordConfig` in context, or
147
+ * Discord's own API when there is none.
148
+ * - Content goes out as written: Discord reads Markdown itself. Every write
149
+ * sends `allowed_mentions: { parse: [] }` and the `SUPPRESS_EMBEDS`
150
+ * flag, on the post and on every edit, unless `withPostOptions` says
151
+ * otherwise. A reply does not ping its author.
152
+ * - `post` and `edit` fail with `TooLarge` before calling Discord past
153
+ * 2,000 code points.
154
+ * - A refused file fails `denied` with detail `file_refused` and leaves
155
+ * nothing posted: more than 10 files or 10 MiB, by the adapter's own
156
+ * check, or any `denied` answer to a post with files. The reason Discord
157
+ * gave is the `cause`.
158
+ * - A message's elements go out as classic components beside `content`,
159
+ * in action rows: five buttons to a row and a select alone in its row, in
160
+ * the order given, up to five rows. More fail `TooLarge` before the call.
161
+ * An `edit` without `actions` removes the ones there were.
162
+ * - A button's id and encoded value share one `custom_id`, joined by one
163
+ * character, and so do a modal's id and its metadata. An id may not
164
+ * contain U+241F, the join. `limits.actionDataLength` and
165
+ * `limits.modalMetadataLength` are 99 code points, the 100 of
166
+ * `custom_id` less the join.
167
+ * - Button styles: `default` is secondary, `primary` primary and
168
+ * `danger` danger.
169
+ * - A modal's inputs are Label components around a text input or a string
170
+ * select, and a `text` is a text display. Inputs and texts together are
171
+ * 5 at most. A modal over that, or with a title or label over 45
172
+ * characters, reaches `Handler.refused` as `TooLarge`. Discord has no
173
+ * submit label, so `submitLabel` is not shown.
174
+ * - `replyTo` sends a message reference. Discord refuses a reply to a
175
+ * message that is gone, unless `withPostOptions({ failIfNotExists: false })`
176
+ * lets it through as a plain message.
177
+ * - Only `DEFAULT`, `REPLY`, `CHAT_INPUT_COMMAND` and
178
+ * `CONTEXT_MENU_COMMAND` messages are messages. A forward, a poll, a
179
+ * sticker or a components-only message is `DEFAULT` and comes through,
180
+ * often with `text: ""`. Its content stays on `raw`.
181
+ * - A deferred command reply arrives empty. Its text comes in a later edit,
182
+ * which is not delivered, so only `history` and `fetchMessage` have it.
183
+ * - A webhook message has the webhook id as its author id and `isBot`.
184
+ * `getUser` on that id fails `NotFound`.
185
+ * - A mention is reported when its token is in `content` outside code and
186
+ * Discord says it resolved. A reply that pings its author is not a
187
+ * mention. Only the bot's user mention is `isSelf`: a mention of its
188
+ * managed role is the consumer's to recognise.
189
+ * - The address of a thread is its channel id. `startThread` names the
190
+ * thread after the message's text, cut to 100 characters, and gives the
191
+ * existing thread when the message already has one.
192
+ * - `history` of a thread started from a message puts the opener, from the
193
+ * parent channel, in place of Discord's placeholder. When the opener is
194
+ * deleted it starts at the first reply. A forum post's starter is in the
195
+ * thread itself.
196
+ * - `getUser` with `in` gives the guild nick, and its `raw` is Discord's
197
+ * guild member, whose `roles` are the member's role ids. Without `in`, in
198
+ * a direct, or for someone who left the guild, `raw` is the user.
199
+ * - The layer provides the `DiscordChat` service as well as registering the
200
+ * adapter, and makes every call through the `DiscordREST` it is given. A
201
+ * consumer that needs more of Discord than `Chat` has reads either from
202
+ * context beside `Chat`. dfx keeps one rate-limit state for both.
203
+ * - There is no native streaming: streamed replies post, then edit, at
204
+ * least 1.5 seconds apart.
205
+ *
206
+ * @stability unstable
207
+ * @category layers
208
+ * @since 4.1.5
209
+ */
210
+ export const layer: Layer.Layer<DiscordChat, never, DiscordREST | HttpClient.HttpClient | Registry> = Layer.effect(
211
+ DiscordChat,
212
+ Effect.gen(function*() {
213
+ const rest = yield* DiscordREST
214
+ const http = yield* HttpClient.HttpClient
215
+ const registry = yield* Registry
216
+ let cached: string | undefined
217
+ const botUserId: Effect.Effect<string, ChatError> = Effect.suspend(() => {
218
+ if (cached !== undefined) return Effect.succeed(cached)
219
+ return rest.getMyUser().pipe(
220
+ Effect.mapError((error) => Errors.chatError("botUserId", Errors.reasonForRestError(error, { write: false }))),
221
+ Effect.flatMap((user) => {
222
+ if (typeof user.id !== "string" || user.id === "") {
223
+ return Effect.fail(Errors.chatError("botUserId", Errors.invalidResponse(false, "missing_user_id")))
224
+ }
225
+ cached = user.id
226
+ return Effect.succeed(user.id)
227
+ })
228
+ )
229
+ })
230
+ const config = yield* Effect.serviceOption(DiscordConfig)
231
+ const baseUrl = Option.match(config, { onNone: () => Adapter.defaultBaseUrl, onSome: (_) => _.rest.baseUrl })
232
+ const { adapter, channelType, guild, interaction } = yield* Adapter.make({ rest, http, baseUrl, botUserId })
233
+ yield* registry.register(adapter)
234
+
235
+ const refuse = (message: string, error: ChatError) =>
236
+ Effect.andThen(Effect.logWarning(message, error), Effect.fail(new NotAccepted()))
237
+
238
+ const dispatch = Effect.fnUntraced(function*(payload: { readonly t: string; readonly d: unknown }) {
239
+ if (!handled.has(payload.t)) return
240
+ const handler = yield* ChatHandler
241
+ const self = yield* Effect.catch(botUserId, (error) => refuse("discord dispatch: bot user lookup failed", error))
242
+ let result = Normalize.normalize(payload, { botUserId: self })
243
+ if (result._tag === "MissingChannelType") {
244
+ const lookup = yield* channelType(result.channelId).pipe(
245
+ Effect.timeoutOrElse({
246
+ duration: lookupTimeout,
247
+ orElse: () => Effect.fail(Errors.chatError("dispatch", Errors.transport(false, "lookup_timeout")))
248
+ }),
249
+ Effect.map(Option.some),
250
+ Effect.catch((error) =>
251
+ error.retry === "denied"
252
+ ? Effect.as(
253
+ Effect.logWarning("discord dispatch: channel lookup denied, event dropped", error),
254
+ Option.none()
255
+ )
256
+ : refuse("discord dispatch: channel lookup failed", error)
257
+ )
258
+ )
259
+ if (Option.isNone(lookup)) return
260
+ result = Normalize.normalize(payload, { botUserId: self, channelType: lookup.value })
261
+ if (result._tag === "MissingChannelType") return
262
+ }
263
+ for (const event of result.events) yield* handler.handle(event)
264
+ })
265
+
266
+ return DiscordChat.of({ botUserId, dispatch, interaction, guild })
267
+ })
268
+ )
269
+
270
+ /**
271
+ * The address of a Discord channel, thread or direct: its channel id.
272
+ *
273
+ * @stability unstable
274
+ * @category constructors
275
+ * @since 4.1.5
276
+ */
277
+ export const thread: (channelId: string) => ChatThread = Normalize.thread
278
+
279
+ /**
280
+ * Error for a message whose channel type is in neither the payload nor the
281
+ * context, from `normalize`.
282
+ *
283
+ * @stability unstable
284
+ * @category errors
285
+ * @since 4.1.5
286
+ */
287
+ export class MissingChannelType extends Schema.TaggedError<MissingChannelType>(
288
+ "@effect/chat-discord/DiscordChat/MissingChannelType"
289
+ )("MissingChannelType", { channelId: Schema.String }) {}
290
+
291
+ /**
292
+ * The normaliser behind `dispatch`, without delivering.
293
+ *
294
+ * **Details**
295
+ *
296
+ * - Pure: it never looks a channel up. It reads the channel type from the
297
+ * payload's `channel_type`, then from `context.channelType`, Discord's
298
+ * numeric type, and fails with `MissingChannelType` when neither has one.
299
+ * - Types 10, 11 and 12 are a `thread`, 1 and 3 a `direct`, and every
300
+ * other type a `channel`.
301
+ * - `MESSAGE_CREATE`, `MESSAGE_REACTION_ADD` and
302
+ * `MESSAGE_REACTION_REMOVE` give an event. Every other dispatch, and a
303
+ * message type that is not a message, gives none.
304
+ * - A custom emoji is `custom:{name}`, its id left on `raw.emoji.id`.
305
+ * - `raw` is `d`, undecoded.
306
+ *
307
+ * @stability unstable
308
+ * @category normalization
309
+ * @since 4.1.5
310
+ */
311
+ export const normalize = (
312
+ dispatch: { readonly t: string; readonly d: unknown },
313
+ context: { readonly botUserId: string; readonly channelType?: number | undefined }
314
+ ): Result.Result<ReadonlyArray<ChatEvent>, MissingChannelType> => {
315
+ const result = Normalize.normalize(dispatch, context)
316
+ return result._tag === "Events"
317
+ ? Result.succeed(result.events)
318
+ : Result.fail(new MissingChannelType({ channelId: result.channelId }))
319
+ }
320
+
321
+ /**
322
+ * The member on a message's or added reaction's `raw`: the guild, the
323
+ * roles and the nick.
324
+ *
325
+ * **Details**
326
+ *
327
+ * Pure, with no REST call. `None` for a direct, a webhook message, or a
328
+ * payload with no member. Discord sends no member on a removed reaction, so
329
+ * it takes none.
330
+ *
331
+ * @stability unstable
332
+ * @category accessors
333
+ * @since 4.1.5
334
+ */
335
+ export const member = (event: MessageCreated | ReactionAdded): Option.Option<{
336
+ readonly guildId: string
337
+ readonly roles: ReadonlyArray<string>
338
+ readonly nick?: string | undefined
339
+ }> => Normalize.memberOf(event.raw)
340
+
341
+ /**
342
+ * The guild on an event's `raw`.
343
+ *
344
+ * **Details**
345
+ *
346
+ * Pure, with no REST call. It works for every event, webhook messages and
347
+ * removed reactions included. `None` for a direct.
348
+ *
349
+ * @stability unstable
350
+ * @category accessors
351
+ * @since 4.1.5
352
+ */
353
+ export const guildId = (event: ChatEvent): Option.Option<string> => Normalize.guildIdOf(event.raw)
354
+
355
+ /**
356
+ * For a long-running process: subscribes to dfx's gateway and feeds every
357
+ * dispatch to `DiscordChat.dispatch`, one at a time.
358
+ *
359
+ * **Details**
360
+ *
361
+ * - Intents and sharding stay in the consumer's dfx config. So does the
362
+ * gateway session: dfx keeps the session id, the resume URL and the
363
+ * sequence in the `ShardStateStore` given to `DiscordGatewayLive`.
364
+ * - It reads dfx's stream of dispatches, which a dispatch reaches after its
365
+ * sequence is stored. An event that fails with `NotAccepted` is logged
366
+ * and dropped, and so is one the process stops in the middle of: Discord
367
+ * does not send it again.
368
+ *
369
+ * @see {@link layerDispatchHook} for a host that is stopped and started again
370
+ *
371
+ * @stability unstable
372
+ * @category layers
373
+ * @since 4.1.5
374
+ */
375
+ export const layerGateway: Layer.Layer<never, never, DiscordGateway | DiscordChat | ChatHandler> = Layer.effectDiscard(
376
+ Effect.gen(function*() {
377
+ const gateway = yield* DiscordGateway
378
+ const discord = yield* DiscordChat
379
+ const handler = yield* ChatHandler
380
+ yield* gateway.dispatch.pipe(
381
+ Stream.runForEach((payload) => {
382
+ const t: unknown = payload.t
383
+ if (typeof t !== "string") return Effect.void
384
+ return discord.dispatch({ t, d: payload.d }).pipe(
385
+ Effect.provideService(ChatHandler, handler),
386
+ Effect.catchCause((cause) => Effect.logWarning("discord gateway: event dropped", cause))
387
+ )
388
+ }),
389
+ Effect.forkScoped
390
+ )
391
+ })
392
+ )
393
+
394
+ /**
395
+ * For a host that is stopped and started again, a Durable Object for one:
396
+ * feeds every dispatch to `DiscordChat.dispatch` from dfx's `DispatchHook`,
397
+ * before the shard stores the dispatch's sequence.
398
+ *
399
+ * **When to use**
400
+ *
401
+ * Use when an event must not be lost to a restart, in place of
402
+ * `layerGateway`. Never provide both: every event would be delivered twice.
403
+ *
404
+ * **Details**
405
+ *
406
+ * - Provide it to the dfx layer that builds the shards, `DiscordGatewayLive`
407
+ * or `ShardLive`, beside a `ShardStateStore` over storage that outlives
408
+ * the host. dfx keeps the session id, the resume URL and the sequence
409
+ * there, so a host built again sends RESUME, not IDENTIFY, and Discord
410
+ * sends what it missed.
411
+ * - The handler runs before the sequence is stored. A host stopped in the
412
+ * middle of an event never stored that event's sequence, so the RESUME
413
+ * brings the event back.
414
+ * - An event that fails with `NotAccepted` fails the hook. dfx drops the
415
+ * connection, resumes from the last stored sequence and gets the event
416
+ * again, after 1 second, doubling with every failure in a row up to 2
417
+ * minutes. An event that is refused every time holds back every event
418
+ * after it.
419
+ * - A defect in the handler is logged and the event dropped, as a replay
420
+ * would only fail the same way.
421
+ * - Delivery is at least once. A host stopped after the handler returned and
422
+ * before the sequence was stored gets that event a second time, so a
423
+ * handler that can't take an event twice remembers the ids it took.
424
+ * - The hook runs on the shard's read loop, one dispatch at a time. A
425
+ * handler slower than Discord's heartbeat interval, about 41 seconds,
426
+ * makes the shard reconnect.
427
+ * - Interactions stay with `layerGatewayInteractions`: each has 3 seconds,
428
+ * so there is nothing to resume.
429
+ *
430
+ * **Gotchas**
431
+ *
432
+ * - Discord replays only while it keeps the session. When it refuses the
433
+ * RESUME, dfx identifies again and the events in between are gone.
434
+ * - Waking the host, restarting a shard that went quiet and backing off
435
+ * after a close Discord won't change its mind on, an invalid token (4004)
436
+ * or a disallowed intent (4014), stay with the host: dfx reconnects
437
+ * whatever the close code.
438
+ *
439
+ * **Example** (Resuming from the host's own storage)
440
+ *
441
+ * ```ts
442
+ * import { DiscordChat } from "@effect/chat-discord"
443
+ * import { ShardLive } from "dfx/DiscordGateway/Shard"
444
+ * import { type ShardState, ShardStateStore } from "dfx/DiscordGateway/Shard/StateStore"
445
+ * import { Effect, Layer, Option } from "effect"
446
+ *
447
+ * // Stands in for storage that outlives the host.
448
+ * const storage = new Map<string, ShardState>()
449
+ *
450
+ * const SessionStore = Layer.succeed(
451
+ * ShardStateStore,
452
+ * ShardStateStore.of({
453
+ * forShard: ([id, count]) => {
454
+ * const key = `${id}/${count}`
455
+ * return {
456
+ * get: Effect.sync(() => Option.fromUndefinedOr(storage.get(key))),
457
+ * set: (state) => Effect.sync(() => void storage.set(key, state)),
458
+ * clear: Effect.sync(() => void storage.delete(key))
459
+ * }
460
+ * }
461
+ * })
462
+ * )
463
+ *
464
+ * // Still needs `DiscordChat`, a `ChatHandler` and the rest of dfx's gateway.
465
+ * export const ShardResuming = ShardLive.pipe(
466
+ * Layer.provide([DiscordChat.layerDispatchHook, SessionStore])
467
+ * )
468
+ * ```
469
+ *
470
+ * @see {@link layerGateway} for a process that runs until it is told to stop
471
+ *
472
+ * @stability unstable
473
+ * @category layers
474
+ * @since 4.1.5
475
+ */
476
+ export const layerDispatchHook: Layer.Layer<never, never, DiscordChat | ChatHandler> = Layer.effect(
477
+ DispatchHook,
478
+ Effect.gen(function*() {
479
+ const discord = yield* DiscordChat
480
+ const handler = yield* ChatHandler
481
+ return (payload) => {
482
+ const t: unknown = payload.t
483
+ if (typeof t !== "string" || !handled.has(t)) return Effect.void
484
+ return discord.dispatch({ t, d: payload.d }).pipe(
485
+ Effect.provideService(ChatHandler, handler),
486
+ // Refused or interrupted: the sequence stays unstored and a RESUME replays the event.
487
+ Effect.catchCause((cause): Effect.Effect<void, NotAccepted> =>
488
+ Cause.hasFails(cause) || Cause.hasInterrupts(cause)
489
+ ? Effect.failCause(cause)
490
+ : Effect.logError("discord gateway: handler defect, event dropped", cause)
491
+ ),
492
+ Effect.orDie
493
+ )
494
+ }
495
+ })
496
+ )
497
+
498
+ /**
499
+ * For a long-running process: subscribes to dfx's gateway and feeds every
500
+ * `INTERACTION_CREATE` to `DiscordChat.interaction`.
501
+ *
502
+ * **Details**
503
+ *
504
+ * Interactions run concurrently, since each has its own 3 seconds. It is
505
+ * separate from `layerGateway`, so a consumer with no buttons needs no
506
+ * `ChatInteraction.Handler`.
507
+ *
508
+ * @stability unstable
509
+ * @category layers
510
+ * @since 4.1.5
511
+ */
512
+ export const layerGatewayInteractions: Layer.Layer<
513
+ never,
514
+ never,
515
+ DiscordGateway | DiscordChat | ChatInteraction.Handler
516
+ > = Layer.effectDiscard(
517
+ Effect.gen(function*() {
518
+ const gateway = yield* DiscordGateway
519
+ const discord = yield* DiscordChat
520
+ const handler = yield* ChatInteraction.Handler
521
+ yield* gateway.fromDispatch("INTERACTION_CREATE").pipe(
522
+ Stream.mapEffect(
523
+ (payload) =>
524
+ discord.interaction(payload).pipe(
525
+ Effect.provideService(ChatInteraction.Handler, handler),
526
+ Effect.catchCause((cause) => Effect.logWarning("discord gateway: interaction dropped", cause))
527
+ ),
528
+ { concurrency: "unbounded" }
529
+ ),
530
+ Stream.runDrain,
531
+ Effect.forkScoped
532
+ )
533
+ })
534
+ )
535
+
536
+ /**
537
+ * The normaliser behind `DiscordChat.interaction`.
538
+ *
539
+ * **Details**
540
+ *
541
+ * - Pure. A click on a button gives `ButtonClicked`, with the id and value
542
+ * split from the `custom_id`. A string select gives `SelectChanged`, and
543
+ * a modal's submit `ModalSubmitted`, its metadata split from the modal's
544
+ * `custom_id`.
545
+ * - The thread and message come from the `message` Discord sends with the
546
+ * interaction, so a modal's submit carries the message whose element
547
+ * opened it. A modal a command opened has no message, so its submit has
548
+ * no `messageId`, and its thread is the channel.
549
+ * - A submit's `values` hold each answered input by id. An input left
550
+ * empty is absent.
551
+ * - A slash command with no options, or one string option, gives
552
+ * `CommandInvoked`: `id` is its name and `text` the option's value or
553
+ * the empty string.
554
+ * - Anything else, a message or user command, a slash command with other
555
+ * options, or a click with no message, is `None`.
556
+ * - `raw` is the payload, undecoded. For a command it holds the token that
557
+ * answers it, so it is a credential for 15 minutes.
558
+ *
559
+ * @stability unstable
560
+ * @category normalization
561
+ * @since 4.1.5
562
+ */
563
+ export const normalizeInteraction: (interaction: unknown) => Option.Option<ChatInteraction.Interaction> =
564
+ Interactions.normalize
565
+
566
+ /**
567
+ * The create payload of each command in `group`, in the group's order, for
568
+ * Discord's application commands endpoint.
569
+ *
570
+ * **Details**
571
+ *
572
+ * - Each is a `CHAT_INPUT` command with the definition's name and
573
+ * description, and one `STRING` option when it has an `argument`. Each
574
+ * fits dfx's `ApplicationCommandCreateRequest`.
575
+ * - The definitions in `group` that are not commands are skipped.
576
+ *
577
+ * **Gotchas**
578
+ *
579
+ * - The adapter registers nothing. Discord's bulk overwrite replaces the
580
+ * application's whole list, so the consumer sends these beside its other
581
+ * commands, in one call.
582
+ * - dfx's gateway runner syncs its own commands the same way when it
583
+ * starts, which would delete these. A consumer running both adds these to
584
+ * that list, or switches the sync off with `setInteractionsSync(false)`.
585
+ * - A field the definition lacks, such as `default_member_permissions`, is
586
+ * spread onto the payload by the consumer.
587
+ *
588
+ * **Example** (Registering the commands beside dfx's own)
589
+ *
590
+ * ```ts import.meta.vitest
591
+ * import { DiscordChat } from "@effect/chat-discord"
592
+ * import { DiscordREST } from "dfx/DiscordREST"
593
+ * import { Effect } from "effect"
594
+ * import { ChatInteraction } from "effect/chat"
595
+ *
596
+ * const Commands = ChatInteraction.group(
597
+ * ChatInteraction.command("summarize", { description: "Summarize this thread" })
598
+ * )
599
+ *
600
+ * export const register = Effect.gen(function*() {
601
+ * const rest = yield* DiscordREST
602
+ * const app = yield* rest.getMyApplication()
603
+ * yield* rest.bulkSetApplicationCommands(app.id, [...DiscordChat.commandRequests(Commands)])
604
+ * })
605
+ * ```
606
+ *
607
+ * @stability unstable
608
+ * @category commands
609
+ * @since 4.1.5
610
+ */
611
+ export const commandRequests: (group: ChatInteraction.Group<any>) => ReadonlyArray<{
612
+ /** `CHAT_INPUT`. */
613
+ readonly type: 1
614
+ readonly name: string
615
+ readonly description: string
616
+ /** One `STRING` option when the command has an `argument`, absent otherwise. */
617
+ readonly options?:
618
+ | ReadonlyArray<{
619
+ readonly type: 3
620
+ readonly name: string
621
+ readonly description: string
622
+ readonly required: boolean
623
+ }>
624
+ | undefined
625
+ }> = Interactions.commandRequests
626
+
627
+ /**
628
+ * Discord options for every write inside an effect.
629
+ *
630
+ * @stability unstable
631
+ * @category models
632
+ * @since 4.1.5
633
+ */
634
+ export interface DiscordPostOptions {
635
+ /**
636
+ * Who a write may notify. Default: nobody, and a reply does not ping its
637
+ * author. `everyone` allows `@everyone` and `@here`.
638
+ */
639
+ readonly notify?: {
640
+ readonly users?: ReadonlyArray<string> | undefined
641
+ readonly roles?: ReadonlyArray<string> | undefined
642
+ readonly everyone?: boolean | undefined
643
+ readonly repliedUser?: boolean | undefined
644
+ } | undefined
645
+ /**
646
+ * Link embeds. Default true, which sends the `SUPPRESS_EMBEDS` flag on
647
+ * the post and on every edit, so a link a later edit adds gets no embed
648
+ * either. False sends no flag on a post and clears it on an edit.
649
+ */
650
+ readonly suppressEmbeds?: boolean | undefined
651
+ /**
652
+ * What a post with `replyTo` does when that message is gone. Default
653
+ * true: Discord refuses the post. False sends `fail_if_not_exists: false`,
654
+ * and Discord posts the message without the reference.
655
+ */
656
+ readonly failIfNotExists?: boolean | undefined
657
+ /** For `startThread`, in minutes. Default: the channel's. */
658
+ readonly autoArchiveDuration?: 60 | 1440 | 4320 | 10080 | undefined
659
+ }
660
+
661
+ /**
662
+ * Scoped Discord options for every write inside `effect`. Nested calls
663
+ * merge, the inner one winning field by field.
664
+ *
665
+ * @stability unstable
666
+ * @category combinators
667
+ * @since 4.1.5
668
+ */
669
+ export const withPostOptions: {
670
+ /**
671
+ * Scoped Discord options for every write inside `effect`. Nested calls
672
+ * merge, the inner one winning field by field.
673
+ *
674
+ * @stability unstable
675
+ * @category combinators
676
+ * @since 4.1.5
677
+ */
678
+ (options: DiscordPostOptions): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
679
+ /**
680
+ * Scoped Discord options for every write inside `effect`. Nested calls
681
+ * merge, the inner one winning field by field.
682
+ *
683
+ * @stability unstable
684
+ * @category combinators
685
+ * @since 4.1.5
686
+ */
687
+ <A, E, R>(effect: Effect.Effect<A, E, R>, options: DiscordPostOptions): Effect.Effect<A, E, R>
688
+ } = dual(
689
+ 2,
690
+ <A, E, R>(effect: Effect.Effect<A, E, R>, options: DiscordPostOptions): Effect.Effect<A, E, R> =>
691
+ Effect.updateService(effect, CurrentPostOptions, (current) => ({ ...current, ...options }))
692
+ )
693
+
694
+ /**
695
+ * Reads one Discord mention token, `<@id>`, `<@!id>`, `<@&id>`,
696
+ * `<#id>`, `@everyone` or `@here`, for `ChatTest.checkMessage`,
697
+ * `ChatTest.checkEvent` and `ChatTest.conformance`.
698
+ *
699
+ * @stability unstable
700
+ * @category testing
701
+ * @since 4.1.5
702
+ */
703
+ export const parseMention: ParseMention = (slice) => Option.fromUndefinedOr(Mentions.parseToken(slice))