composure 0.2.4

Discord bots over HTTP Interactions, no gateway: slash commands, components, modals and JSX-like views, on Cloudflare Workers (WASM) or any server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! Routes: everything an App lists, and the App itself (ADR 0013).

use std::sync::Arc;

use crate::outline::outlined;

use crate::types::{
    ApplicationCommandInteraction, ApplicationCommandType, Event, InteractionResponse,
    MessageComponentInteraction, ModalSubmitInteraction,
};

use super::{
    Command, CommandDefinition, ComponentHandler, Ctx, ErrorRenderer, EventCtx, HandlerError,
    Invocation, ModalHandler, ScopedDefinition, ViewHandler, ViewInfo, custom_id,
    set::{scope_eq, str_eq},
};

/// What a Route is, as the compile-time checks of the App listing it see it
#[derive(Debug, Clone, Copy)]
pub enum RouteInfo {
    /// A `#[command]` or `#[group]`
    Command {
        /// The Command's name
        name: &'static str,
        /// Chat input, user, or message
        kind: ApplicationCommandType,
        /// Its named Scope; `None` is global
        scope: Option<&'static str>,
    },
    /// A `#[component]` handler
    Component {
        /// The `custom_id` prefix it answers
        prefix: &'static str,
    },
    /// A `#[modal]` handler
    Modal {
        /// The `custom_id` prefix it answers
        prefix: &'static str,
    },
    /// A `#[view]`
    View(ViewInfo),
    /// An `#[app]`
    App {
        /// What it lists
        routes: &'static [RouteInfo],
        /// Whether this App sets `events`
        events: bool,
        /// Whether this App sets `errors`
        errors: bool,
    },
}

impl RouteInfo {
    /// A `#[command]` or `#[group]`
    pub const fn command<C: CommandDefinition>() -> Self {
        Self::Command {
            name: C::NAME,
            kind: C::KIND,
            scope: C::SCOPE,
        }
    }

    /// Whether this Route (or one an App lists) answers commands and autocomplete; Apps skip
    /// the others at compile time
    pub const fn has_commands(&self) -> bool {
        answers(self, Kind::Commands)
    }

    /// Whether this Route (or one an App lists) answers components
    pub const fn has_components(&self) -> bool {
        answers(self, Kind::Components)
    }

    /// Whether this Route (or one an App lists) answers modal submits
    pub const fn has_modals(&self) -> bool {
        answers(self, Kind::Modals)
    }

    /// Whether this App or one it lists sets `events`
    pub const fn has_events(&self) -> bool {
        match self {
            Self::App { routes, events, .. } => *events || count(routes, &Query::Events) > 0,
            _ => false,
        }
    }
}

/// What an App lists: a Command, Group, Component or Modal Handler, View, or another App.
/// Implemented by `#[command]`, `#[group]`, `#[component]`, `#[modal]`, `#[view]` and `#[app]`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a Command, Group, Component or Modal Handler, View, or App",
    label = "listed in `#[app(handlers(..))]`",
    note = "list items made with `#[command]`, `#[group]`, `#[component]`, `#[modal]`, `#[view]` or `#[app]`"
)]
pub trait RouteDefinition {
    /// What it is, for the App's compile-time checks
    const ROUTE: RouteInfo;

    /// The `errors` renderer an App sets, or one an App it lists (at any depth) sets; `None` for
    /// everything else
    const ERRORS: Option<ErrorRenderer> = None;

    /// Appends the Command Definitions of this Route (and of the Routes an App lists), for Sync
    fn definitions(_into: &mut Vec<ScopedDefinition>) {}
}

/// Answers the Interactions routed to it, or `None` when they are not its own. Every method
/// defaults to `None`; each kind of Route overrides the ones it answers. `errors` is the root App's
/// [`ErrorRenderer`], for Background Work that fails after the response.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be routed with State `{S}`",
    label = "listed in an `#[app]` served with State `{S}`"
)]
pub trait Route<S>: RouteDefinition {
    /// Runs the Command with the invoked name and type
    fn dispatch(
        _interaction: &Arc<ApplicationCommandInteraction>,
        _state: &S,
        _errors: ErrorRenderer,
    ) -> impl Future<Output = Option<Result<InteractionResponse, HandlerError>>> + Send {
        async { None }
    }

    /// Runs the invoked Command's Autocomplete Handler for the focused Option
    fn dispatch_autocomplete(
        _interaction: &Arc<ApplicationCommandInteraction>,
        _state: &S,
        _errors: ErrorRenderer,
    ) -> impl Future<Output = Option<Result<InteractionResponse, HandlerError>>> + Send {
        async { None }
    }

    /// Runs the Component Handler (or View handler) the `custom_id` prefix names
    fn dispatch_component(
        _interaction: &Arc<MessageComponentInteraction>,
        _state: &S,
        _errors: ErrorRenderer,
    ) -> impl Future<Output = Option<Result<InteractionResponse, HandlerError>>> + Send {
        async { None }
    }

    /// Runs the Modal Handler (or View handler) the `custom_id` prefix names
    fn dispatch_modal(
        _interaction: &Arc<ModalSubmitInteraction>,
        _state: &S,
        _errors: ErrorRenderer,
    ) -> impl Future<Output = Option<Result<InteractionResponse, HandlerError>>> + Send {
        async { None }
    }

    /// Hands a Webhook Event to the App's `events`; ignored by everything else
    fn dispatch_event(
        _ctx: EventCtx<'_, S>,
        _event: Event,
    ) -> impl Future<Output = Result<(), HandlerError>> + Send {
        async { Ok(()) }
    }
}

#[derive(Clone, Copy)]
enum Kind {
    Commands,
    Components,
    Modals,
}

const fn answers(route: &RouteInfo, kind: Kind) -> bool {
    match (route, kind) {
        (RouteInfo::Command { .. }, Kind::Commands)
        | (RouteInfo::Component { .. }, Kind::Components)
        | (RouteInfo::Modal { .. }, Kind::Modals)
        | (RouteInfo::View(_), Kind::Components | Kind::Modals) => true,
        (RouteInfo::App { routes, .. }, _) => {
            let mut i = 0;
            while i < routes.len() {
                if answers(&routes[i], kind) {
                    return true;
                }
                i += 1;
            }
            false
        }
        _ => false,
    }
}

/// What every [`Route`] dispatch method resolves to; spelled out in the impls the macros generate
#[doc(hidden)]
pub type __Routed = Option<Result<InteractionResponse, HandlerError>>;

/// [`Route::dispatch`] of a Command or Group
#[doc(hidden)]
pub async fn __dispatch_command<C: Command<S>, S: Sync>(
    interaction: &Arc<ApplicationCommandInteraction>,
    state: &S,
    errors: ErrorRenderer,
) -> Option<Result<InteractionResponse, HandlerError>> {
    let data = &interaction.data;
    if data.name != C::NAME || data.t != C::KIND {
        return None;
    }
    Some(
        outlined(C::invoke(
            Invocation::new(interaction, state).with_errors(errors),
        ))
        .await,
    )
}

/// [`Route::dispatch_autocomplete`] of a Command or Group
#[doc(hidden)]
pub async fn __dispatch_autocomplete<C: Command<S>, S: Sync>(
    interaction: &Arc<ApplicationCommandInteraction>,
    state: &S,
    errors: ErrorRenderer,
) -> Option<Result<InteractionResponse, HandlerError>> {
    let data = &interaction.data;
    if data.name != C::NAME || data.t != C::KIND {
        return None;
    }
    outlined(C::autocomplete(
        Invocation::new(interaction, state).with_errors(errors),
    ))
    .await
}

/// [`Route::dispatch_component`] of a Component Handler
#[doc(hidden)]
pub async fn __dispatch_component<H: ComponentHandler<S>, S: Sync>(
    interaction: &Arc<MessageComponentInteraction>,
    state: &S,
    errors: ErrorRenderer,
) -> Option<Result<InteractionResponse, HandlerError>> {
    let (prefix, fields) = custom_id::split(&interaction.data.custom_id);
    if prefix != H::PREFIX {
        return None;
    }
    Some(
        outlined(H::invoke(
            Ctx::new(interaction, state).with_errors(errors),
            fields,
        ))
        .await,
    )
}

/// [`Route::dispatch_modal`] of a Modal Handler
#[doc(hidden)]
pub async fn __dispatch_modal<H: ModalHandler<S>, S: Sync>(
    interaction: &Arc<ModalSubmitInteraction>,
    state: &S,
    errors: ErrorRenderer,
) -> Option<Result<InteractionResponse, HandlerError>> {
    let (prefix, fields) = custom_id::split(&interaction.data.custom_id);
    if prefix != H::PREFIX {
        return None;
    }
    Some(
        outlined(H::invoke(
            Ctx::new(interaction, state).with_errors(errors),
            fields,
        ))
        .await,
    )
}

/// [`Route::dispatch_component`] of a View
#[doc(hidden)]
pub async fn __dispatch_view_component<V: ViewHandler<S>, S: Sync>(
    interaction: &Arc<MessageComponentInteraction>,
    state: &S,
    errors: ErrorRenderer,
) -> Option<Result<InteractionResponse, HandlerError>> {
    let (prefix, fields) = custom_id::split(&interaction.data.custom_id);
    if prefix != V::INFO.prefix {
        return None;
    }
    outlined(V::component(
        Ctx::new(interaction, state).with_errors(errors),
        fields,
    ))
    .await
}

/// [`Route::dispatch_modal`] of a View
#[doc(hidden)]
pub async fn __dispatch_view_modal<V: ViewHandler<S>, S: Sync>(
    interaction: &Arc<ModalSubmitInteraction>,
    state: &S,
    errors: ErrorRenderer,
) -> Option<Result<InteractionResponse, HandlerError>> {
    let (prefix, fields) = custom_id::split(&interaction.data.custom_id);
    if prefix != V::INFO.prefix {
        return None;
    }
    outlined(V::modal(
        Ctx::new(interaction, state).with_errors(errors),
        fields,
    ))
    .await
}

/// The [`ErrorRenderer`] of `R`'s tree: the `errors` an App in it sets, else
/// [`HandlerError::response`]
#[doc(hidden)]
pub const fn __errors<R: RouteDefinition + ?Sized>() -> ErrorRenderer {
    match R::ERRORS {
        Some(render) => render,
        None => HandlerError::response,
    }
}

/// Compile-time checks for an App and every App it lists: no two Commands share a name and
/// type, no Scope exceeds Discord's per-type limit, no two handlers share a `custom_id` prefix,
/// sub-Views with handlers that listed Views place are listed too, and at most one App sets
/// `events`, and at most one `errors`. Used by `#[app]`.
#[doc(hidden)]
pub const fn check_app(app: &RouteInfo) {
    let root = std::slice::from_ref(app);
    if count(root, &Query::Events) > 1 {
        panic!("more than one App sets `events`: a bot has one events URL");
    }
    if count(root, &Query::Errors) > 1 {
        panic!("more than one App sets `errors`: a bot renders its errors one way");
    }
    check_routes(root, root);
}

const fn check_routes(root: &[RouteInfo], routes: &[RouteInfo]) {
    let mut i = 0;
    while i < routes.len() {
        match &routes[i] {
            RouteInfo::App { routes, .. } => check_routes(root, routes),
            RouteInfo::Command { name, kind, scope } => {
                if count(root, &Query::Command(name, *kind)) > 1 {
                    panic!("two commands have the same name and type");
                }
                let limit = match kind {
                    ApplicationCommandType::ChatInput => 100,
                    ApplicationCommandType::User | ApplicationCommandType::Message => 15,
                };
                if count(root, &Query::Scope(*kind, *scope)) > limit {
                    panic!(
                        "too many commands of one type in one scope: Discord allows 100 chat-input, 15 user, and 15 message commands"
                    );
                }
            }
            RouteInfo::Component { prefix } => {
                if count(root, &Query::Prefix(prefix, Namespace::Component)) > 1 {
                    panic!("two handlers have the same custom_id prefix");
                }
            }
            RouteInfo::Modal { prefix } => {
                if count(root, &Query::Prefix(prefix, Namespace::Modal)) > 1 {
                    panic!("two handlers have the same custom_id prefix");
                }
            }
            RouteInfo::View(view) => {
                if count(root, &Query::Prefix(view.prefix, Namespace::Component)) > 1
                    || count(root, &Query::Prefix(view.prefix, Namespace::Modal)) > 1
                {
                    panic!("two handlers have the same custom_id prefix");
                }
                check_placed(root, view.views, 0);
            }
        }
        i += 1;
    }
}

/// Every View with handlers that a listed View places (at any depth) is listed too
const fn check_placed(root: &[RouteInfo], placed: &[ViewInfo], depth: usize) {
    if depth > 16 {
        return;
    }
    let mut i = 0;
    while i < placed.len() {
        let view = placed[i];
        if view.handled && count(root, &Query::View(view.prefix)) == 0 {
            panic!(
                "a View with handlers placed by a listed View (a `<SubView .. />` tag in its markup) is missing from `#[app(handlers(..))]`"
            );
        }
        check_placed(root, view.views, depth + 1);
        i += 1;
    }
}

#[derive(Clone, Copy)]
enum Namespace {
    Component,
    Modal,
}

/// What [`count`] looks for
enum Query<'a> {
    Command(&'a str, ApplicationCommandType),
    Scope(ApplicationCommandType, Option<&'a str>),
    /// Handlers answering this prefix: Component or Modal Handlers, and Views, which answer both
    Prefix(&'a str, Namespace),
    View(&'a str),
    /// Apps setting `events`
    Events,
    /// Apps setting `errors`
    Errors,
}

/// How many Routes in the tree match `query`
const fn count(routes: &[RouteInfo], query: &Query) -> usize {
    let mut n = 0;
    let mut i = 0;
    while i < routes.len() {
        let hit = match (&routes[i], query) {
            (
                RouteInfo::App {
                    routes,
                    events,
                    errors,
                },
                _,
            ) => {
                n += count(routes, query);
                (*events && matches!(query, Query::Events))
                    || (*errors && matches!(query, Query::Errors))
            }
            (RouteInfo::Command { name, kind, .. }, Query::Command(other, other_kind)) => {
                *kind as u8 == *other_kind as u8 && str_eq(name, other)
            }
            (RouteInfo::Command { kind, scope, .. }, Query::Scope(other_kind, other_scope)) => {
                *kind as u8 == *other_kind as u8 && scope_eq(*scope, *other_scope)
            }
            (RouteInfo::Component { prefix }, Query::Prefix(other, Namespace::Component))
            | (RouteInfo::Modal { prefix }, Query::Prefix(other, Namespace::Modal)) => {
                str_eq(prefix, other)
            }
            (RouteInfo::View(view), Query::Prefix(other, _) | Query::View(other)) => {
                str_eq(view.prefix, other)
            }
            _ => false,
        };
        if hit {
            n += 1;
        }
        i += 1;
    }
    n
}