@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,184 @@
1
+ import {
2
+ ChatError,
3
+ type ChatErrorReason,
4
+ fileRefused as fileRefusedDetail,
5
+ Forbidden,
6
+ InvalidRequest,
7
+ InvalidResponse,
8
+ NoAdapter,
9
+ NotFound,
10
+ PlatformUnavailable,
11
+ RateLimited,
12
+ TooLarge,
13
+ Transport,
14
+ Unauthenticated,
15
+ Unknown,
16
+ Unsupported
17
+ } from "effect/chat/ChatError"
18
+ import * as Duration from "effect/Duration"
19
+ import { isObject } from "effect/Predicate"
20
+ import { platform } from "./normalize.ts"
21
+
22
+ /** Discord's JSON error codes, by what they mean. */
23
+ const notFoundCodes = new Set([10003, 10004, 10007, 10008, 10013, 10014, 10015])
24
+ const forbiddenCodes = new Set([20001, 20028, 50001, 50005, 50013, 50021, 50083, 160005, 160006])
25
+ const unauthenticatedCodes = new Set([0, 40001])
26
+ const tooLargeFiles = new Set([40005, 50045])
27
+
28
+ /** A 50035 whose errors say a field is too long. */
29
+ const isTooLong = (data: { readonly [x: PropertyKey]: unknown }): boolean =>
30
+ JSON.stringify(data.errors ?? {}).includes("MAX_LENGTH")
31
+
32
+ const withCause = (cause: unknown) => (cause === undefined ? {} : { cause })
33
+
34
+ /**
35
+ * The reason for an answer Discord sent: a JSON error `code` when there is
36
+ * one, otherwise the HTTP status. `detail` is the code, or `http_{status}`.
37
+ *
38
+ * @internal
39
+ */
40
+ export const reasonForResponse = (
41
+ status: number,
42
+ data: unknown,
43
+ options: { readonly write: boolean; readonly cause?: unknown }
44
+ ): ChatErrorReason => {
45
+ const body = isObject(data) ? data : {}
46
+ const code = typeof body.code === "number" ? body.code : undefined
47
+ const cause = withCause(options.cause)
48
+ if (status === 429) {
49
+ const seconds = typeof body.retry_after === "number" ? body.retry_after : undefined
50
+ return new RateLimited({
51
+ detail: code === undefined ? "http_429" : String(code),
52
+ ...cause,
53
+ ...(seconds === undefined || seconds < 0 ? {} : { retryAfter: Duration.millis(Math.ceil(seconds * 1000)) })
54
+ })
55
+ }
56
+ if (status >= 500) {
57
+ return new PlatformUnavailable({ retry: options.write ? "uncertain" : "retry", detail: `http_${status}`, ...cause })
58
+ }
59
+ const detail = code === undefined ? `http_${status}` : String(code)
60
+ if (code !== undefined) {
61
+ if (notFoundCodes.has(code)) return new NotFound({ detail, ...cause })
62
+ if (forbiddenCodes.has(code)) return new Forbidden({ detail, ...cause })
63
+ if (tooLargeFiles.has(code)) return new TooLarge({ subject: "files", detail, ...cause })
64
+ if (code === 50035 && isTooLong(body)) return new TooLarge({ subject: "text", detail, ...cause })
65
+ if (unauthenticatedCodes.has(code) && status === 401) return new Unauthenticated({ detail, ...cause })
66
+ }
67
+ if (status === 401) return new Unauthenticated({ detail, ...cause })
68
+ if (status === 403) return new Forbidden({ detail, ...cause })
69
+ if (status === 404) return new NotFound({ detail, ...cause })
70
+ if (status === 413) return new TooLarge({ subject: "files", detail, ...cause })
71
+ return new InvalidRequest({ detail, ...cause })
72
+ }
73
+
74
+ /**
75
+ * A request that failed before an answer came.
76
+ *
77
+ * @internal
78
+ */
79
+ export const transport = (write: boolean, detail: string, cause?: unknown): ChatErrorReason =>
80
+ new Transport({ retry: write ? "uncertain" : "retry", detail, ...withCause(cause) })
81
+
82
+ /**
83
+ * An answer the adapter cannot read. A write may have landed.
84
+ *
85
+ * @internal
86
+ */
87
+ export const invalidResponse = (write: boolean, detail: string, cause?: unknown): ChatErrorReason => {
88
+ const fields = { detail, ...withCause(cause) }
89
+ return write ? new Unknown(fields) : new InvalidResponse(fields)
90
+ }
91
+
92
+ /**
93
+ * The reason for a dfx `DiscordRESTError`, read structurally so no dfx
94
+ * type is needed: an `ErrorResponse` or `RatelimitedResponse` carries
95
+ * Discord's body in `data`, and an `HttpClientError` carries a `reason`.
96
+ *
97
+ * @internal
98
+ */
99
+ export const reasonForRestError = (error: unknown, options: { readonly write: boolean }): ChatErrorReason => {
100
+ const tagged = isObject(error) ? error : {}
101
+ const tag = tagged._tag
102
+ const response = isObject(tagged.response) ? tagged.response : undefined
103
+ const status = typeof response?.status === "number" ? response.status : undefined
104
+ if (tag === "ErrorResponse" || tag === "RatelimitedResponse") {
105
+ return reasonForResponse(status ?? (tag === "RatelimitedResponse" ? 429 : 400), tagged.data, {
106
+ write: options.write,
107
+ cause: error
108
+ })
109
+ }
110
+ if (tag === "HttpClientError" && isObject(tagged.reason)) {
111
+ const reason = tagged.reason
112
+ const reasonResponse = isObject(reason.response) ? reason.response : undefined
113
+ const reasonStatus = typeof reasonResponse?.status === "number" ? reasonResponse.status : undefined
114
+ // An error status whose body is not JSON, such as a 413 from the edge, is still Discord's answer.
115
+ if (reasonStatus !== undefined && reasonStatus >= 400 && reasonStatus < 500) {
116
+ return reasonForResponse(reasonStatus, undefined, { write: options.write, cause: error })
117
+ }
118
+ switch (reason._tag) {
119
+ case "StatusCodeError":
120
+ return reasonForResponse(reasonStatus ?? 500, undefined, { write: options.write, cause: error })
121
+ case "TransportError":
122
+ return transport(options.write, "transport", error)
123
+ case "EncodeError":
124
+ case "InvalidUrlError":
125
+ return new InvalidRequest({ detail: String(reason._tag), cause: error })
126
+ default:
127
+ return invalidResponse(options.write, String(reason._tag), error)
128
+ }
129
+ }
130
+ return new Unknown({ detail: "unknown", cause: error })
131
+ }
132
+
133
+ /** @internal */
134
+ export const chatError = (op: string, reason: ChatErrorReason): ChatError => new ChatError({ platform, op, reason })
135
+
136
+ /** @internal */
137
+ export const invalidRequest = (detail: string): ChatErrorReason => new InvalidRequest({ detail })
138
+
139
+ /** @internal */
140
+ export const notFound = (detail: string): ChatErrorReason => new NotFound({ detail })
141
+
142
+ /**
143
+ * Whether a failure carries Discord's JSON error code `code`.
144
+ *
145
+ * @internal
146
+ */
147
+ export const hasCode = (code: number) => (error: ChatError): boolean => error.reason.detail === String(code)
148
+
149
+ /**
150
+ * A `denied` reason from a post that carries files, as a refused file: the
151
+ * same reason with detail `file_refused`, and the reason it replaces, with
152
+ * Discord's code, as its `cause`. Any other reason is returned as it is.
153
+ *
154
+ * @internal
155
+ */
156
+ export const fileRefused = (reason: ChatErrorReason): ChatErrorReason => {
157
+ if (reason.retry !== "denied" || reason.detail === fileRefusedDetail) return reason
158
+ const fields = { detail: fileRefusedDetail, cause: reason }
159
+ switch (reason._tag) {
160
+ case "Unsupported":
161
+ return new Unsupported({ capability: reason.capability, ...fields })
162
+ case "Transport":
163
+ return new Transport({ retry: reason.retry, ...fields })
164
+ case "PlatformUnavailable":
165
+ return new PlatformUnavailable({ retry: reason.retry, ...fields })
166
+ case "NoAdapter":
167
+ return new NoAdapter(fields)
168
+ case "Unauthenticated":
169
+ return new Unauthenticated(fields)
170
+ case "Forbidden":
171
+ return new Forbidden(fields)
172
+ case "NotFound":
173
+ return new NotFound(fields)
174
+ case "TooLarge":
175
+ return new TooLarge({ ...(reason.subject === undefined ? {} : { subject: reason.subject }), ...fields })
176
+ case "InvalidRequest":
177
+ return new InvalidRequest(fields)
178
+ case "InvalidResponse":
179
+ return new InvalidResponse(fields)
180
+ case "RateLimited":
181
+ case "Unknown":
182
+ return reason
183
+ }
184
+ }
@@ -0,0 +1,451 @@
1
+ import type * as Discord from "dfx/types"
2
+ import type { ChatErrorReason } from "effect/chat/ChatError"
3
+ import { InvalidRequest, TooLarge } from "effect/chat/ChatError"
4
+ import * as ChatInteraction from "effect/chat/ChatInteraction"
5
+ import type * as ChatUi from "effect/chat/ChatUi"
6
+ import * as Option from "effect/Option"
7
+ import * as Schema from "effect/Schema"
8
+ import { codePoints, cut, messageLength } from "./length.ts"
9
+ import * as Normalize from "./normalize.ts"
10
+
11
+ /**
12
+ * The one character between an id and its value in a `custom_id`, for a
13
+ * button and for a modal's metadata. An id may not hold it, so the first one
14
+ * in a `custom_id` is the join.
15
+ *
16
+ * @internal
17
+ */
18
+ export const join = "\u241F"
19
+
20
+ /** @internal */
21
+ export const limits = {
22
+ actionsPerMessage: 25,
23
+ actionDataLength: 99,
24
+ modalMetadataLength: 99,
25
+ modalFields: 5
26
+ } as const
27
+
28
+ /** Discord's limits on rows, a row's buttons, a modal's title and an input's label. */
29
+ const rowsPerMessage = 5
30
+ const buttonsPerRow = 5
31
+ const titleLength = 45
32
+ const labelLength = 45
33
+
34
+ /** Discord's interaction callback types. */
35
+ const DEFERRED_UPDATE_MESSAGE = 6
36
+ const CHANNEL_MESSAGE_WITH_SOURCE = 4
37
+ const DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE = 5
38
+ const MODAL = 9
39
+ const EPHEMERAL = 1 << 6
40
+
41
+ /** The ephemeral flag for a private answer, none otherwise. */
42
+ const visibilityFlags = (visibility: ChatInteraction.Visibility): number => visibility === "ephemeral" ? EPHEMERAL : 0
43
+
44
+ /** `custom_id` for an id and an optional value. */
45
+ const customId = (id: string, value: string | undefined): string => value === undefined ? id : id + join + value
46
+
47
+ /** An id and its value from a `custom_id`, split at the first join. */
48
+ const splitCustomId = (customId: string): { readonly id: string; readonly value?: string } => {
49
+ const at = customId.indexOf(join)
50
+ return at === -1 ? { id: customId } : { id: customId.slice(0, at), value: customId.slice(at + 1) }
51
+ }
52
+
53
+ const buttonStyle = (style: ChatUi.ButtonStyle | undefined): Discord.ButtonStyleTypes =>
54
+ style === "primary" ? 1 : style === "danger" ? 4 : 2
55
+
56
+ type Row = Discord.ActionRowComponentForMessageRequest
57
+ type Component = Row["components"][number]
58
+
59
+ /**
60
+ * A message's elements as action rows, or why they can't go: five buttons to
61
+ * a row and a select alone in its row, in the order given, up to five rows.
62
+ *
63
+ * @internal
64
+ */
65
+ export const rows = (actions: ReadonlyArray<ChatUi.Action>): Array<Row> | ChatErrorReason => {
66
+ if (actions.length > limits.actionsPerMessage) return new TooLarge({ detail: "too_many_actions" })
67
+ const out: Array<{ type: 1; components: Array<Component> }> = []
68
+ let open: Array<Component> | undefined
69
+ for (const action of actions) {
70
+ if (action._tag === "Select") {
71
+ const id = codePoints(action.id)
72
+ if (action.options.some((option) => id + codePoints(option.value) > limits.actionDataLength)) {
73
+ return new TooLarge({ detail: "action_data_too_long" })
74
+ }
75
+ open = undefined
76
+ out.push({
77
+ type: 1,
78
+ components: [{
79
+ type: 3,
80
+ custom_id: action.id,
81
+ ...(action.placeholder === undefined ? {} : { placeholder: action.placeholder }),
82
+ options: action.options.map((option) => ({
83
+ label: option.label,
84
+ value: option.value,
85
+ ...(option.value === action.selected ? { default: true } : {})
86
+ })),
87
+ min_values: 1,
88
+ max_values: 1
89
+ }]
90
+ })
91
+ continue
92
+ }
93
+ let button: Component
94
+ if (action._tag === "LinkButton") {
95
+ button = { type: 2, style: 5, label: action.label, url: action.url }
96
+ } else {
97
+ if (action.id.includes(join)) return new InvalidRequest({ detail: "invalid_action_id" })
98
+ if (codePoints(action.id) + codePoints(action.value ?? "") > limits.actionDataLength) {
99
+ return new TooLarge({ detail: "action_data_too_long" })
100
+ }
101
+ button = {
102
+ type: 2,
103
+ style: buttonStyle(action.style),
104
+ label: action.label,
105
+ custom_id: customId(action.id, action.value)
106
+ }
107
+ }
108
+ if (open === undefined || open.length === buttonsPerRow) {
109
+ open = [button]
110
+ out.push({ type: 1, components: open })
111
+ } else {
112
+ open.push(button)
113
+ }
114
+ }
115
+ return out.length > rowsPerMessage ? new TooLarge({ detail: "too_many_actions" }) : out
116
+ }
117
+
118
+ /**
119
+ * Discord's Markdown escape for any ASCII punctuation, so a modal's text
120
+ * shows as written.
121
+ */
122
+ const plain = (text: string): string => text.replace(/[!-/:-@[-`{-~]/g, "\\$&")
123
+
124
+ type ModalData = Discord.ModalInteractionCallbackRequestData
125
+
126
+ /**
127
+ * The callback data that opens `modal`, or why it can't open. Inputs are
128
+ * Label components around a text input or a string select, and a `Text` is
129
+ * a text display. Discord has no submit label, so `submitLabel` is not sent.
130
+ *
131
+ * @internal
132
+ */
133
+ export const modalData = (modal: ChatUi.Modal): ModalData | ChatErrorReason => {
134
+ if (modal.id.includes(join)) return new InvalidRequest({ detail: "invalid_modal_id" })
135
+ if (codePoints(modal.id) + codePoints(modal.metadata ?? "") > limits.modalMetadataLength) {
136
+ return new TooLarge({ detail: "modal_metadata_too_long" })
137
+ }
138
+ if (modal.elements.length > limits.modalFields) return new TooLarge({ detail: "too_many_fields" })
139
+ if (codePoints(modal.title) > titleLength) return new TooLarge({ detail: "title_too_long" })
140
+ const components: Array<ModalData["components"][number]> = []
141
+ for (const element of modal.elements) {
142
+ if (element._tag === "Text") {
143
+ components.push({ type: 10, content: plain(element.text) })
144
+ continue
145
+ }
146
+ if (codePoints(element.label) > labelLength) return new TooLarge({ detail: "label_too_long" })
147
+ const required = element.optional !== true
148
+ components.push({
149
+ type: 18,
150
+ label: element.label,
151
+ component: element._tag === "TextInput"
152
+ ? {
153
+ type: 4,
154
+ custom_id: element.id,
155
+ style: element.multiline === true ? 2 : 1,
156
+ required,
157
+ ...(element.placeholder === undefined ? {} : { placeholder: element.placeholder }),
158
+ ...(element.initial === undefined ? {} : { value: element.initial }),
159
+ ...(element.minLength === undefined ? {} : { min_length: element.minLength }),
160
+ ...(element.maxLength === undefined ? {} : { max_length: element.maxLength })
161
+ }
162
+ : {
163
+ type: 3,
164
+ custom_id: element.id,
165
+ required,
166
+ min_values: required ? 1 : 0,
167
+ max_values: 1,
168
+ ...(element.placeholder === undefined ? {} : { placeholder: element.placeholder }),
169
+ options: element.options.map((option) => ({
170
+ label: option.label,
171
+ value: option.value,
172
+ ...(option.value === element.initial ? { default: true } : {})
173
+ }))
174
+ }
175
+ })
176
+ }
177
+ return { custom_id: customId(modal.id, modal.metadata), title: modal.title, components }
178
+ }
179
+
180
+ type Callback = Discord.CreateInteractionResponseRequest
181
+
182
+ /** @internal */
183
+ export const ackCallback: Callback = { type: DEFERRED_UPDATE_MESSAGE }
184
+
185
+ /** @internal */
186
+ export const modalCallback = (data: ModalData): Callback => ({ type: MODAL, data })
187
+
188
+ /**
189
+ * The answer to an `errors` reply: a private message listing each one, as
190
+ * plain text, cut to fit one message. The modal closes.
191
+ *
192
+ * @internal
193
+ */
194
+ export const errorsCallback = (errors: Readonly<Record<string, string>>): Callback => ({
195
+ type: CHANNEL_MESSAGE_WITH_SOURCE,
196
+ data: {
197
+ content: cut(Object.values(errors).map((message) => "- " + plain(message)).join("\n"), messageLength),
198
+ allowed_mentions: { parse: [] },
199
+ flags: EPHEMERAL
200
+ }
201
+ })
202
+
203
+ /**
204
+ * A message as an interaction's answer sends it: with the ephemeral flag
205
+ * when private.
206
+ *
207
+ * @internal
208
+ */
209
+ export const withVisibility = <M extends { readonly flags: number }>(
210
+ message: M,
211
+ visibility: ChatInteraction.Visibility
212
+ ): M => ({ ...message, flags: message.flags | visibilityFlags(visibility) })
213
+
214
+ /**
215
+ * The answer to a `respond` reply: the message a `post` sends, with the
216
+ * ephemeral flag when private.
217
+ *
218
+ * @internal
219
+ */
220
+ export const respondCallback = (message: {
221
+ readonly content: string
222
+ readonly allowed_mentions: Discord.MessageAllowedMentionsRequest
223
+ readonly flags: number
224
+ readonly components?: ReadonlyArray<Row> | undefined
225
+ }, visibility: ChatInteraction.Visibility): Callback => ({
226
+ type: CHANNEL_MESSAGE_WITH_SOURCE,
227
+ data: withVisibility(message, visibility)
228
+ })
229
+
230
+ /**
231
+ * The answer to a `defer` reply. The visibility is fixed here and holds for
232
+ * the edit that follows.
233
+ *
234
+ * @internal
235
+ */
236
+ export const deferCallback = (visibility: ChatInteraction.Visibility): Callback => ({
237
+ type: DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE,
238
+ ...(visibility === "ephemeral" ? { data: { flags: EPHEMERAL } } : {})
239
+ })
240
+
241
+ // Inbound
242
+
243
+ const { optional } = Normalize
244
+
245
+ const Input = Schema.Struct({
246
+ type: Schema.Number,
247
+ custom_id: optional(Schema.String),
248
+ value: optional(Schema.String),
249
+ values: optional(Schema.Array(Schema.String))
250
+ })
251
+
252
+ const ModalComponent = Schema.Struct({
253
+ type: Schema.Number,
254
+ component: optional(Input),
255
+ components: optional(Schema.Array(Input))
256
+ })
257
+
258
+ const CommandOption = Schema.Struct({
259
+ type: Schema.Number,
260
+ name: optional(Schema.String),
261
+ value: optional(Schema.Unknown)
262
+ })
263
+
264
+ const InteractionFields = Schema.Struct({
265
+ id: Schema.String,
266
+ application_id: optional(Schema.String),
267
+ type: Schema.Number,
268
+ token: Schema.String,
269
+ channel_id: optional(Schema.String),
270
+ member: optional(Schema.Struct({ user: optional(Schema.Struct({ id: Schema.String })) })),
271
+ user: optional(Schema.Struct({ id: Schema.String })),
272
+ message: optional(Schema.Struct({ id: Schema.String, channel_id: optional(Schema.String) })),
273
+ data: Schema.Struct({
274
+ custom_id: optional(Schema.String),
275
+ component_type: optional(Schema.Number),
276
+ values: optional(Schema.Array(Schema.String)),
277
+ components: optional(Schema.Array(ModalComponent)),
278
+ name: optional(Schema.String),
279
+ type: optional(Schema.Number),
280
+ options: optional(Schema.Array(CommandOption))
281
+ })
282
+ })
283
+
284
+ const decodeFields = Schema.decodeUnknownOption(InteractionFields)
285
+
286
+ /** Discord's interaction types for a command, a component click and a modal submit. */
287
+ const APPLICATION_COMMAND = 2
288
+ const MESSAGE_COMPONENT = 3
289
+ const MODAL_SUBMIT = 5
290
+ /** Discord's command type for a slash command, and its option type for a string. */
291
+ const CHAT_INPUT = 1
292
+ const STRING = 3
293
+
294
+ /**
295
+ * Credentials for answering an interaction.
296
+ *
297
+ * @internal
298
+ */
299
+ export const answerTo = (raw: unknown): { readonly id: string; readonly token: string } | undefined =>
300
+ Option.getOrUndefined(Option.map(decodeFields(raw), ({ id, token }) => ({ id, token })))
301
+
302
+ /**
303
+ * Credentials for editing a deferred command's response.
304
+ *
305
+ * @internal
306
+ */
307
+ export const followUpTo = (
308
+ raw: unknown
309
+ ): { readonly id: string; readonly applicationId: string; readonly token: string } | undefined =>
310
+ Option.getOrUndefined(
311
+ Option.flatMap(decodeFields(raw), ({ application_id, id, token }) =>
312
+ typeof application_id === "string" && application_id !== ""
313
+ ? Option.some({ id, applicationId: application_id, token })
314
+ : Option.none())
315
+ )
316
+
317
+ /**
318
+ * The text of a slash command's options: none, or one string. Undefined for
319
+ * anything else.
320
+ */
321
+ const commandText = (options: ReadonlyArray<typeof CommandOption.Type> | null | undefined): string | undefined => {
322
+ if (options === null || options === undefined || options.length === 0) return ""
323
+ const [option] = options
324
+ return options.length === 1 && option.type === STRING && typeof option.value === "string" ? option.value : undefined
325
+ }
326
+
327
+ /**
328
+ * The interaction a payload is, when it is a click on a button or string
329
+ * select, a submit of a modal, or a slash command with at most one string
330
+ * option. Anything else, a message or user command for one, is none.
331
+ *
332
+ * @internal
333
+ */
334
+ export const normalize = (raw: unknown): Option.Option<ChatInteraction.Interaction> => {
335
+ const decoded = decodeFields(raw)
336
+ if (Option.isNone(decoded)) return Option.none()
337
+ const fields = decoded.value
338
+ const message = fields.message
339
+ const userId = fields.member?.user?.id ?? fields.user?.id
340
+ const channelId = message?.channel_id ?? fields.channel_id
341
+ if (userId === undefined || channelId === null || channelId === undefined) return Option.none()
342
+ const { data } = fields
343
+ if (fields.type === APPLICATION_COMMAND) {
344
+ const text = commandText(data.options)
345
+ // A missing command type is taken as a slash command, which is Discord's default.
346
+ return (data.type ?? CHAT_INPUT) !== CHAT_INPUT || typeof data.name !== "string" || data.name === "" ||
347
+ text === undefined
348
+ ? Option.none()
349
+ : Option.some(ChatInteraction.CommandInvoked.make({
350
+ id: data.name,
351
+ text,
352
+ thread: Normalize.thread(channelId),
353
+ userId,
354
+ raw: raw as Schema.Json
355
+ }))
356
+ }
357
+ const customIdValue = data.custom_id
358
+ if (customIdValue === null || customIdValue === undefined) return Option.none()
359
+ if (fields.type === MODAL_SUBMIT) return submitted(fields, customIdValue, channelId, userId, raw)
360
+ if (message === null || message === undefined) return Option.none()
361
+ const origin = { thread: Normalize.thread(channelId), messageId: message.id, userId, raw: raw as Schema.Json }
362
+ if (fields.type === MESSAGE_COMPONENT && data.component_type === 2) {
363
+ const { id, value } = splitCustomId(customIdValue)
364
+ return Option.some(ChatInteraction.ButtonClicked.make({ id, ...(value === undefined ? {} : { value }), ...origin }))
365
+ }
366
+ if (fields.type === MESSAGE_COMPONENT && data.component_type === 3) {
367
+ const value = data.values?.[0]
368
+ return value === undefined
369
+ ? Option.none()
370
+ : Option.some(ChatInteraction.SelectChanged.make({ id: customIdValue, value, ...origin }))
371
+ }
372
+ return Option.none()
373
+ }
374
+
375
+ /** A modal's submit. One a command opened has no `message`, and no `messageId`. */
376
+ const submitted = (
377
+ fields: typeof InteractionFields.Type,
378
+ customIdValue: string,
379
+ channelId: string,
380
+ userId: string,
381
+ raw: unknown
382
+ ): Option.Option<ChatInteraction.Interaction> => {
383
+ const values: Record<string, string> = {}
384
+ for (const component of fields.data.components ?? []) {
385
+ const inputs = component.component === null || component.component === undefined
386
+ ? component.components ?? []
387
+ : [component.component]
388
+ for (const input of inputs) {
389
+ const value = input.value ?? input.values?.[0]
390
+ if (typeof input.custom_id === "string" && value !== null && value !== undefined && value !== "") {
391
+ // An own property, so an id such as `__proto__` keeps its answer.
392
+ Object.defineProperty(values, input.custom_id, {
393
+ value,
394
+ enumerable: true,
395
+ writable: true,
396
+ configurable: true
397
+ })
398
+ }
399
+ }
400
+ }
401
+ const { id, value: metadata } = splitCustomId(customIdValue)
402
+ const message = fields.message
403
+ return Option.some(ChatInteraction.ModalSubmitted.make({
404
+ id,
405
+ ...(metadata === undefined ? {} : { metadata }),
406
+ values,
407
+ thread: Normalize.thread(channelId),
408
+ ...(message === null || message === undefined ? {} : { messageId: message.id }),
409
+ userId,
410
+ raw: raw as Schema.Json
411
+ }))
412
+ }
413
+
414
+ interface CommandRequest {
415
+ readonly type: 1
416
+ readonly name: string
417
+ readonly description: string
418
+ readonly options?: ReadonlyArray<{
419
+ readonly type: 3
420
+ readonly name: string
421
+ readonly description: string
422
+ readonly required: boolean
423
+ }>
424
+ }
425
+
426
+ /**
427
+ * The create payload of each command in `group`, in the group's order.
428
+ *
429
+ * @internal
430
+ */
431
+ export const commandRequests = (group: ChatInteraction.Group<any>): ReadonlyArray<CommandRequest> => {
432
+ const out: Array<CommandRequest> = []
433
+ for (const definition of (group.definitions as ReadonlyMap<string, ChatInteraction.Definition>).values()) {
434
+ if (definition.kind !== "command") continue
435
+ const { argument } = definition
436
+ out.push({
437
+ type: CHAT_INPUT,
438
+ name: definition.id,
439
+ description: definition.description,
440
+ ...(argument === undefined ? {} : {
441
+ options: [{
442
+ type: STRING,
443
+ name: argument.name,
444
+ description: argument.description,
445
+ required: argument.required
446
+ }]
447
+ })
448
+ })
449
+ }
450
+ return out
451
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Discord's limit on `content`, in code points, inclusive.
3
+ *
4
+ * @internal
5
+ */
6
+ export const messageLength = 2000
7
+
8
+ /** The index past the code point at `i`: a surrogate pair is one, a lone surrogate one too. */
9
+ const next = (text: string, i: number): number => text.codePointAt(i)! > 0xffff ? i + 2 : i + 1
10
+
11
+ /**
12
+ * Code points, which is what Discord counts: a recorded probe took 2,000
13
+ * astral emoji (4,000 UTF-16 units) and refused 1,999 letters and a flag.
14
+ *
15
+ * @internal
16
+ */
17
+ export const codePoints = (text: string): number => {
18
+ let count = 0
19
+ for (let i = 0; i < text.length; i = next(text, i)) count++
20
+ return count
21
+ }
22
+
23
+ /**
24
+ * Cuts `text` to at most `max` code points.
25
+ *
26
+ * @internal
27
+ */
28
+ export const cut = (text: string, max: number): string => {
29
+ for (let i = 0, count = 0; i < text.length; i = next(text, i), count++) {
30
+ if (count === max) return text.slice(0, i)
31
+ }
32
+ return text
33
+ }