djs-model 0.1.0-alpha.1

Discord API v10 types — users, guilds, channels, messages, interactions and gateway events.
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
//! [Application commands](https://docs.discord.com/developers/interactions/application-commands):
//! slash commands, user and message context menu commands, and Activity entry points.
//!
//! These are the commands as Discord returns them (`GET .../commands`). Their options are an
//! enum keyed by option type (D-069), with typed choices.

use std::collections::BTreeMap;

use compact_str::CompactString;
use serde::{
    Deserialize, Deserializer, Serialize, Serializer,
    de::{Error as DeError, Unexpected, Visitor},
};

use crate::{
    application::IntegrationType,
    channel::ChannelType,
    id::{ApplicationId, CommandId, CommandVersionId, GenericId, GuildId},
    interaction::InteractionContextType,
    macros::int_enum,
    permissions::Permissions,
    util::Locale,
};

/// An [application command](https://docs.discord.com/developers/interactions/application-commands#application-command-object).
///
/// Contains floats (number option bounds and choices), so it is `PartialEq` but not `Eq`
/// (D-064).
///
/// discord.js counterpart: `ApplicationCommand`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ApplicationCommand {
    /// The command's ID.
    pub id: CommandId,
    /// The kind of command (Discord's default: [`ChatInput`](CommandType::ChatInput)).
    #[serde(rename = "type", default)]
    pub kind: CommandType,
    /// The application that owns the command.
    pub application_id: ApplicationId,
    /// The guild of a guild command (`None` for global commands).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub guild_id: Option<GuildId>,
    /// The command's name (1-32 characters; lowercase for slash commands).
    pub name: CompactString,
    /// Translations of the name, keyed by locale (D-058).
    #[serde(
        default,
        skip_serializing_if = "BTreeMap::is_empty",
        deserialize_with = "crate::serde_util::null_as_default"
    )]
    pub name_localizations: BTreeMap<Locale, CompactString>,
    /// The description (1-100 characters; empty for user and message commands).
    #[serde(default)]
    pub description: CompactString,
    /// Translations of the description, keyed by locale (D-058).
    #[serde(
        default,
        skip_serializing_if = "BTreeMap::is_empty",
        deserialize_with = "crate::serde_util::null_as_default"
    )]
    pub description_localizations: BTreeMap<Locale, CompactString>,
    /// The name in the requester's locale, returned instead of
    /// [`name_localizations`](Self::name_localizations) by the endpoints that list commands
    /// (unless asked for the full translations).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name_localized: Option<CompactString>,
    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description_localized: Option<CompactString>,
    /// The parameters of a slash command (max 25).
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "crate::serde_util::null_as_default"
    )]
    pub options: Vec<CommandOption>,
    /// The permissions a member needs by default (`None`: everyone; empty: administrators
    /// only). Guild admins can override them.
    #[serde(default)]
    pub default_member_permissions: Option<Permissions>,
    /// Whether the command is available in DMs. **Deprecated** by Discord in favor of
    /// [`contexts`](Self::contexts).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dm_permission: Option<bool>,
    /// Whether the command is enabled by default. **Deprecated** by Discord in favor of
    /// [`default_member_permissions`](Self::default_member_permissions).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_permission: Option<bool>,
    /// Whether the command is age-restricted.
    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
    pub nsfw: bool,
    /// The installation contexts the command is available in.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "crate::serde_util::null_as_default"
    )]
    pub integration_types: Vec<IntegrationType>,
    /// The interaction contexts the command can be used in.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "crate::serde_util::null_as_default"
    )]
    pub contexts: Vec<InteractionContextType>,
    /// An auto-incrementing version, updated on substantial changes.
    pub version: CommandVersionId,
    /// Who handles a primary entry point command.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handler: Option<EntryPointHandlerType>,
}

int_enum! {
    /// The [type of an application command](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-types).
    ///
    /// discord.js counterpart: `ApplicationCommandType`.
    #[doc(alias = "ApplicationCommandType")]
    #[derive(Default)]
    pub enum CommandType: u8 {
        /// A slash command, shown when typing `/`.
        #[default]
        ChatInput = 1,
        /// A context menu command on users.
        User = 2,
        /// A context menu command on messages.
        Message = 3,
        /// The primary way to launch the app's Activity.
        PrimaryEntryPoint = 4,
    }
}

int_enum! {
    /// [Who handles a primary entry point command](https://docs.discord.com/developers/interactions/application-commands#application-command-object-entry-point-command-handler-types).
    ///
    /// discord.js counterpart: `EntryPointCommandHandlerType`.
    #[doc(alias = "EntryPointCommandHandlerType")]
    pub enum EntryPointHandlerType: u8 {
        /// The app handles the interaction with its interaction token.
        AppHandler = 1,
        /// Discord launches the Activity and sends a follow-up message itself.
        DiscordLaunchActivity = 2,
    }
}

/// An [option (parameter) of a slash command](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-structure),
/// one variant per option type (D-069).
///
/// discord.js counterpart: `ApplicationCommandOption` (the `ApplicationCommand*Option` types).
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
#[doc(alias = "ApplicationCommandOption")]
pub enum CommandOption {
    /// A subcommand, with its own options.
    SubCommand(SubCommandOption),
    /// A group of subcommands (its options are subcommands).
    SubCommandGroup(SubCommandOption),
    /// A string.
    String(StringOption),
    /// An integer between -2^53+1 and 2^53-1.
    Integer(IntegerOption),
    /// A boolean.
    Boolean(BasicOption),
    /// A user.
    User(BasicOption),
    /// A channel (including categories).
    Channel(ChannelOption),
    /// A role.
    Role(BasicOption),
    /// A user or a role.
    Mentionable(BasicOption),
    /// A double between -2^53 and 2^53.
    Number(NumberOption),
    /// An uploaded file.
    Attachment(AttachmentOption),
    /// An option type this version of the library does not know about.
    Unknown(UnknownOption),
}

/// The fields every [`CommandOption`] has, as returned by [`CommandOption::common`].
///
/// discord.js counterpart: none (a borrowed view of the fields every `APIApplicationCommandOption` has).
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct OptionInfo<'a> {
    /// The option's name.
    pub name: &'a str,
    /// Translations of the name.
    pub name_localizations: &'a BTreeMap<Locale, CompactString>,
    /// The option's description.
    pub description: &'a str,
    /// Translations of the description.
    pub description_localizations: &'a BTreeMap<Locale, CompactString>,
    /// The name in the requester's locale, if Discord sent it.
    pub name_localized: Option<&'a str>,
    /// The description in the requester's locale, if Discord sent it.
    pub description_localized: Option<&'a str>,
}

macro_rules! common_fields {
    ($self:ident) => {
        match $self {
            Self::SubCommand(option) | Self::SubCommandGroup(option) => OptionInfo {
                name: &option.name,
                name_localizations: &option.name_localizations,
                description: &option.description,
                description_localizations: &option.description_localizations,
                name_localized: option.name_localized.as_deref(),
                description_localized: option.description_localized.as_deref(),
            },
            Self::String(option) => OptionInfo {
                name: &option.name,
                name_localizations: &option.name_localizations,
                description: &option.description,
                description_localizations: &option.description_localizations,
                name_localized: option.name_localized.as_deref(),
                description_localized: option.description_localized.as_deref(),
            },
            Self::Integer(option) => OptionInfo {
                name: &option.name,
                name_localizations: &option.name_localizations,
                description: &option.description,
                description_localizations: &option.description_localizations,
                name_localized: option.name_localized.as_deref(),
                description_localized: option.description_localized.as_deref(),
            },
            Self::Boolean(option)
            | Self::User(option)
            | Self::Role(option)
            | Self::Mentionable(option) => OptionInfo {
                name: &option.name,
                name_localizations: &option.name_localizations,
                description: &option.description,
                description_localizations: &option.description_localizations,
                name_localized: option.name_localized.as_deref(),
                description_localized: option.description_localized.as_deref(),
            },
            Self::Channel(option) => OptionInfo {
                name: &option.name,
                name_localizations: &option.name_localizations,
                description: &option.description,
                description_localizations: &option.description_localizations,
                name_localized: option.name_localized.as_deref(),
                description_localized: option.description_localized.as_deref(),
            },
            Self::Number(option) => OptionInfo {
                name: &option.name,
                name_localizations: &option.name_localizations,
                description: &option.description,
                description_localizations: &option.description_localizations,
                name_localized: option.name_localized.as_deref(),
                description_localized: option.description_localized.as_deref(),
            },
            Self::Attachment(option) => OptionInfo {
                name: &option.name,
                name_localizations: &option.name_localizations,
                description: &option.description,
                description_localizations: &option.description_localizations,
                name_localized: option.name_localized.as_deref(),
                description_localized: option.description_localized.as_deref(),
            },
            Self::Unknown(option) => OptionInfo {
                name: &option.name,
                name_localizations: &option.name_localizations,
                description: &option.description,
                description_localizations: &option.description_localizations,
                name_localized: option.name_localized.as_deref(),
                description_localized: option.description_localized.as_deref(),
            },
        }
    };
}

impl CommandOption {
    /// Returns the option's type.
    ///
    /// discord.js counterpart: the `type` of `ApplicationCommandOption`.
    #[must_use]
    pub const fn kind(&self) -> CommandOptionType {
        match self {
            Self::SubCommand(_) => CommandOptionType::SubCommand,
            Self::SubCommandGroup(_) => CommandOptionType::SubCommandGroup,
            Self::String(_) => CommandOptionType::String,
            Self::Integer(_) => CommandOptionType::Integer,
            Self::Boolean(_) => CommandOptionType::Boolean,
            Self::User(_) => CommandOptionType::User,
            Self::Channel(_) => CommandOptionType::Channel,
            Self::Role(_) => CommandOptionType::Role,
            Self::Mentionable(_) => CommandOptionType::Mentionable,
            Self::Number(_) => CommandOptionType::Number,
            Self::Attachment(_) => CommandOptionType::Attachment,
            Self::Unknown(option) => option.kind,
        }
    }

    /// Returns the fields every option has (name, description and their translations).
    ///
    /// discord.js counterpart: none (the fields every `APIApplicationCommandOption` has).
    #[must_use]
    pub fn common(&self) -> OptionInfo<'_> {
        common_fields!(self)
    }

    /// Returns the option's name.
    ///
    /// discord.js counterpart: the `name` of `ApplicationCommandOption`.
    #[must_use]
    pub fn name(&self) -> &str {
        self.common().name
    }

    /// Returns the nested options of a subcommand or subcommand group (empty otherwise).
    ///
    /// discord.js counterpart: `ApplicationCommandSubCommand#options`.
    #[must_use]
    pub fn options(&self) -> &[Self] {
        match self {
            Self::SubCommand(option) | Self::SubCommandGroup(option) => &option.options,
            _ => &[],
        }
    }
}

int_enum! {
    /// The [type of a command option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-type).
    ///
    /// discord.js counterpart: `ApplicationCommandOptionType`.
    #[doc(alias = "ApplicationCommandOptionType")]
    pub enum CommandOptionType: u8 {
        /// [`CommandOption::SubCommand`].
        SubCommand = 1,
        /// [`CommandOption::SubCommandGroup`].
        SubCommandGroup = 2,
        /// [`CommandOption::String`].
        String = 3,
        /// [`CommandOption::Integer`].
        Integer = 4,
        /// [`CommandOption::Boolean`].
        Boolean = 5,
        /// [`CommandOption::User`].
        User = 6,
        /// [`CommandOption::Channel`].
        Channel = 7,
        /// [`CommandOption::Role`].
        Role = 8,
        /// [`CommandOption::Mentionable`].
        Mentionable = 9,
        /// [`CommandOption::Number`].
        Number = 10,
        /// [`CommandOption::Attachment`].
        Attachment = 11,
    }
}

/// A subcommand or a subcommand group.
///
/// discord.js counterpart: `APIApplicationCommandSubcommandOption` / `APIApplicationCommandSubcommandGroupOption` (discord-api-types).
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct SubCommandOption {
    /// The name (1-32 characters).
    pub name: CompactString,
    /// Translations of the name.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub name_localizations: BTreeMap<Locale, CompactString>,
    /// The description (1-100 characters).
    pub description: CompactString,
    /// Translations of the description.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub description_localizations: BTreeMap<Locale, CompactString>,
    /// The name in the requester's locale, from endpoints that do not return the full
    /// translations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_localized: Option<CompactString>,
    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description_localized: Option<CompactString>,
    /// The options of a subcommand, or the subcommands of a group.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub options: Vec<CommandOption>,
}

impl SubCommandOption {
    /// Creates a subcommand or a subcommand group, named `name` and described by `description`, without translations.
    ///
    /// Nothing is validated; `djs-builders` checks Discord's rules.
    ///
    /// discord.js counterpart: `SlashCommandSubcommandBuilder` (`@discordjs/builders`).
    #[must_use]
    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
        Self {
            name: name.into(),
            name_localizations: BTreeMap::new(),
            description: description.into(),
            description_localizations: BTreeMap::new(),
            name_localized: None,
            description_localized: None,
            options: Vec::new(),
        }
    }
}

/// A string option.
///
/// discord.js counterpart: `APIApplicationCommandStringOption` (discord-api-types).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct StringOption {
    /// The name (1-32 characters).
    pub name: CompactString,
    /// Translations of the name.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub name_localizations: BTreeMap<Locale, CompactString>,
    /// The description (1-100 characters).
    pub description: CompactString,
    /// Translations of the description.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub description_localizations: BTreeMap<Locale, CompactString>,
    /// The name in the requester's locale, from endpoints that do not return the full
    /// translations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_localized: Option<CompactString>,
    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description_localized: Option<CompactString>,
    /// Whether the option must be filled.
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    pub required: bool,
    /// The values to choose from (max 25; values up to 100 characters).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub choices: Vec<Choice<CompactString>>,
    /// The minimum length (0-6000).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_length: Option<u16>,
    /// The maximum length (1-6000).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_length: Option<u16>,
    /// Whether the app suggests values through autocomplete interactions (not with
    /// [`choices`](Self::choices)).
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    pub autocomplete: bool,
}

impl StringOption {
    /// Creates an optional string option without choices or bounds, named `name` and described by `description`, without translations.
    ///
    /// Nothing is validated; `djs-builders` checks Discord's rules.
    ///
    /// discord.js counterpart: `SlashCommandStringOption` (`@discordjs/builders`).
    #[must_use]
    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
        Self {
            name: name.into(),
            name_localizations: BTreeMap::new(),
            description: description.into(),
            description_localizations: BTreeMap::new(),
            name_localized: None,
            description_localized: None,
            required: false,
            choices: Vec::new(),
            min_length: None,
            max_length: None,
            autocomplete: false,
        }
    }
}

/// An integer option.
///
/// discord.js counterpart: `APIApplicationCommandIntegerOption` (discord-api-types).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct IntegerOption {
    /// The name (1-32 characters).
    pub name: CompactString,
    /// Translations of the name.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub name_localizations: BTreeMap<Locale, CompactString>,
    /// The description (1-100 characters).
    pub description: CompactString,
    /// Translations of the description.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub description_localizations: BTreeMap<Locale, CompactString>,
    /// The name in the requester's locale, from endpoints that do not return the full
    /// translations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_localized: Option<CompactString>,
    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description_localized: Option<CompactString>,
    /// Whether the option must be filled.
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    pub required: bool,
    /// The values to choose from (max 25).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub choices: Vec<Choice<i64>>,
    /// The minimum value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_value: Option<i64>,
    /// The maximum value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_value: Option<i64>,
    /// Whether the app suggests values through autocomplete interactions.
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    pub autocomplete: bool,
}

impl IntegerOption {
    /// Creates an optional integer option without choices or bounds, named `name` and described by `description`, without translations.
    ///
    /// Nothing is validated; `djs-builders` checks Discord's rules.
    ///
    /// discord.js counterpart: `SlashCommandIntegerOption` (`@discordjs/builders`).
    #[must_use]
    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
        Self {
            name: name.into(),
            name_localizations: BTreeMap::new(),
            description: description.into(),
            description_localizations: BTreeMap::new(),
            name_localized: None,
            description_localized: None,
            required: false,
            choices: Vec::new(),
            min_value: None,
            max_value: None,
            autocomplete: false,
        }
    }
}

/// A number (double) option.
///
/// discord.js counterpart: `APIApplicationCommandNumberOption` (discord-api-types).
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct NumberOption {
    /// The name (1-32 characters).
    pub name: CompactString,
    /// Translations of the name.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub name_localizations: BTreeMap<Locale, CompactString>,
    /// The description (1-100 characters).
    pub description: CompactString,
    /// Translations of the description.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub description_localizations: BTreeMap<Locale, CompactString>,
    /// The name in the requester's locale, from endpoints that do not return the full
    /// translations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_localized: Option<CompactString>,
    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description_localized: Option<CompactString>,
    /// Whether the option must be filled.
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    pub required: bool,
    /// The values to choose from (max 25).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub choices: Vec<Choice<f64>>,
    /// The minimum value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_value: Option<f64>,
    /// The maximum value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_value: Option<f64>,
    /// Whether the app suggests values through autocomplete interactions.
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    pub autocomplete: bool,
}

impl NumberOption {
    /// Creates an optional number option without choices or bounds, named `name` and described by `description`, without translations.
    ///
    /// Nothing is validated; `djs-builders` checks Discord's rules.
    ///
    /// discord.js counterpart: `SlashCommandNumberOption` (`@discordjs/builders`).
    #[must_use]
    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
        Self {
            name: name.into(),
            name_localizations: BTreeMap::new(),
            description: description.into(),
            description_localizations: BTreeMap::new(),
            name_localized: None,
            description_localized: None,
            required: false,
            choices: Vec::new(),
            min_value: None,
            max_value: None,
            autocomplete: false,
        }
    }
}

/// A boolean, user, role or mentionable option (they share this structure).
///
/// discord.js counterpart: `APIApplicationCommandBasicOption` (discord-api-types).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct BasicOption {
    /// The name (1-32 characters).
    pub name: CompactString,
    /// Translations of the name.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub name_localizations: BTreeMap<Locale, CompactString>,
    /// The description (1-100 characters).
    pub description: CompactString,
    /// Translations of the description.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub description_localizations: BTreeMap<Locale, CompactString>,
    /// The name in the requester's locale, from endpoints that do not return the full
    /// translations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_localized: Option<CompactString>,
    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description_localized: Option<CompactString>,
    /// Whether the option must be filled.
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    pub required: bool,
}

impl BasicOption {
    /// Creates an optional boolean, user, role or mentionable option, named `name` and described by `description`, without translations.
    ///
    /// Nothing is validated; `djs-builders` checks Discord's rules.
    ///
    /// discord.js counterpart: `SlashCommandBooleanOption` and its siblings (`@discordjs/builders`).
    #[must_use]
    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
        Self {
            name: name.into(),
            name_localizations: BTreeMap::new(),
            description: description.into(),
            description_localizations: BTreeMap::new(),
            name_localized: None,
            description_localized: None,
            required: false,
        }
    }
}

/// A channel option.
///
/// discord.js counterpart: `APIApplicationCommandChannelOption` (discord-api-types).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct ChannelOption {
    /// The name (1-32 characters).
    pub name: CompactString,
    /// Translations of the name.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub name_localizations: BTreeMap<Locale, CompactString>,
    /// The description (1-100 characters).
    pub description: CompactString,
    /// Translations of the description.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub description_localizations: BTreeMap<Locale, CompactString>,
    /// The name in the requester's locale, from endpoints that do not return the full
    /// translations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_localized: Option<CompactString>,
    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description_localized: Option<CompactString>,
    /// Whether the option must be filled.
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    pub required: bool,
    /// The channel types offered (all when empty).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub channel_types: Vec<ChannelType>,
}

impl ChannelOption {
    /// Creates an optional channel option offering every channel type, named `name` and described by `description`, without translations.
    ///
    /// Nothing is validated; `djs-builders` checks Discord's rules.
    ///
    /// discord.js counterpart: `SlashCommandChannelOption` (`@discordjs/builders`).
    #[must_use]
    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
        Self {
            name: name.into(),
            name_localizations: BTreeMap::new(),
            description: description.into(),
            description_localizations: BTreeMap::new(),
            name_localized: None,
            description_localized: None,
            required: false,
            channel_types: Vec::new(),
        }
    }
}

/// An attachment option.
///
/// discord.js counterpart: `APIApplicationCommandAttachmentOption` (discord-api-types).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct AttachmentOption {
    /// The name (1-32 characters).
    pub name: CompactString,
    /// Translations of the name.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub name_localizations: BTreeMap<Locale, CompactString>,
    /// The description (1-100 characters).
    pub description: CompactString,
    /// Translations of the description.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub description_localizations: BTreeMap<Locale, CompactString>,
    /// The name in the requester's locale, from endpoints that do not return the full
    /// translations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_localized: Option<CompactString>,
    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description_localized: Option<CompactString>,
    /// Whether the option must be filled.
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    pub required: bool,
    /// The [file types to accept](https://docs.discord.com/developers/reference#file-type-filtering)
    /// (extensions only; all when empty).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub file_types: Vec<CompactString>,
}

impl AttachmentOption {
    /// Creates an optional attachment option accepting every file type, named `name` and described by `description`, without translations.
    ///
    /// Nothing is validated; `djs-builders` checks Discord's rules.
    ///
    /// discord.js counterpart: `SlashCommandAttachmentOption` (`@discordjs/builders`).
    #[must_use]
    pub fn new(name: impl Into<CompactString>, description: impl Into<CompactString>) -> Self {
        Self {
            name: name.into(),
            name_localizations: BTreeMap::new(),
            description: description.into(),
            description_localizations: BTreeMap::new(),
            name_localized: None,
            description_localized: None,
            required: false,
            file_types: Vec::new(),
        }
    }
}

/// An option of a type this version of the library does not know about; the fields every
/// option has are kept.
///
/// discord.js counterpart: none (an option type unknown to this version, kept as received).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct UnknownOption {
    /// The raw option type.
    #[serde(skip)]
    pub kind: CommandOptionType,
    /// The name.
    pub name: CompactString,
    /// Translations of the name.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub name_localizations: BTreeMap<Locale, CompactString>,
    /// The description.
    pub description: CompactString,
    /// Translations of the description.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub description_localizations: BTreeMap<Locale, CompactString>,
    /// The name in the requester's locale, from endpoints that do not return the full
    /// translations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name_localized: Option<CompactString>,
    /// The description in the requester's locale (see [`name_localized`](Self::name_localized)).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description_localized: Option<CompactString>,
    /// Whether the option must be filled.
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    pub required: bool,
}

/// A [choice of an option](https://docs.discord.com/developers/interactions/application-commands#application-command-object-application-command-option-choice-structure)
/// (also used for autocomplete suggestions). `T` is the option's value type.
///
/// discord.js counterpart: `APIApplicationCommandOptionChoice`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
#[doc(alias = "ApplicationCommandOptionChoice")]
pub struct Choice<T> {
    /// The name shown to the user (1-100 characters).
    pub name: CompactString,
    /// Translations of the name, keyed by locale (D-058).
    #[serde(
        default,
        skip_serializing_if = "BTreeMap::is_empty",
        deserialize_with = "crate::serde_util::null_as_default"
    )]
    pub name_localizations: BTreeMap<Locale, CompactString>,
    /// The value sent to the app.
    pub value: T,
}

impl<T> Choice<T> {
    /// Creates a choice without translations.
    ///
    /// discord.js counterpart: `ApplicationCommandOptionChoiceData`.
    #[must_use]
    pub fn new(name: impl Into<CompactString>, value: T) -> Self {
        Self {
            name: name.into(),
            name_localizations: BTreeMap::new(),
            value,
        }
    }
}

/// A JSON number or string as found in choices and option bounds, before the option type tells
/// what it must be.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum RawValue {
    String(CompactString),
    Integer(i64),
    Float(f64),
}

impl<'de> Deserialize<'de> for RawValue {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct RawValueVisitor;

        impl Visitor<'_> for RawValueVisitor {
            type Value = RawValue;

            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                f.write_str("a string or a number")
            }

            fn visit_i64<E: DeError>(self, value: i64) -> Result<RawValue, E> {
                Ok(RawValue::Integer(value))
            }

            fn visit_u64<E: DeError>(self, value: u64) -> Result<RawValue, E> {
                i64::try_from(value)
                    .map(RawValue::Integer)
                    .map_err(|_| E::invalid_value(Unexpected::Unsigned(value), &self))
            }

            fn visit_f64<E: DeError>(self, value: f64) -> Result<RawValue, E> {
                Ok(RawValue::Float(value))
            }

            fn visit_str<E: DeError>(self, value: &str) -> Result<RawValue, E> {
                Ok(RawValue::String(value.into()))
            }
        }

        deserializer.deserialize_any(RawValueVisitor)
    }
}

impl RawValue {
    pub(crate) fn into_string<E: DeError>(self) -> Result<CompactString, E> {
        match self {
            Self::String(value) => Ok(value),
            Self::Integer(value) => Err(E::invalid_type(Unexpected::Signed(value), &"a string")),
            Self::Float(value) => Err(E::invalid_type(Unexpected::Float(value), &"a string")),
        }
    }

    pub(crate) fn into_integer<E: DeError>(self) -> Result<i64, E> {
        match self {
            Self::Integer(value) => Ok(value),
            Self::String(value) => Err(E::invalid_type(Unexpected::Str(&value), &"an integer")),
            Self::Float(value) => Err(E::invalid_type(Unexpected::Float(value), &"an integer")),
        }
    }

    #[expect(
        clippy::cast_precision_loss,
        reason = "Discord limits command numbers to ±2^53, which f64 represents exactly"
    )]
    pub(crate) fn into_number<E: DeError>(self) -> Result<f64, E> {
        match self {
            Self::Integer(value) => Ok(value as f64),
            Self::Float(value) => Ok(value),
            Self::String(value) => Err(E::invalid_type(Unexpected::Str(&value), &"a number")),
        }
    }
}

pub(crate) fn convert_choices<T, E: DeError>(
    choices: Vec<Choice<RawValue>>,
    convert: impl Fn(RawValue) -> Result<T, E>,
) -> Result<Vec<Choice<T>>, E> {
    choices
        .into_iter()
        .map(|choice| {
            Ok(Choice {
                name: choice.name,
                name_localizations: choice.name_localizations,
                value: convert(choice.value)?,
            })
        })
        .collect()
}

/// Every field of every option type, decoded in one pass and converted by `type` (D-069).
#[derive(Deserialize)]
struct RawOption {
    #[serde(rename = "type")]
    kind: CommandOptionType,
    name: CompactString,
    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
    name_localizations: BTreeMap<Locale, CompactString>,
    #[serde(default)]
    description: CompactString,
    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
    description_localizations: BTreeMap<Locale, CompactString>,
    #[serde(default)]
    name_localized: Option<CompactString>,
    #[serde(default)]
    description_localized: Option<CompactString>,
    #[serde(default)]
    required: bool,
    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
    choices: Vec<Choice<RawValue>>,
    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
    options: Vec<CommandOption>,
    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
    channel_types: Vec<ChannelType>,
    #[serde(default)]
    min_value: Option<RawValue>,
    #[serde(default)]
    max_value: Option<RawValue>,
    #[serde(default)]
    min_length: Option<u16>,
    #[serde(default)]
    max_length: Option<u16>,
    #[serde(default)]
    autocomplete: bool,
    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
    file_types: Vec<CompactString>,
}

impl RawOption {
    fn into_option<E: DeError>(self) -> Result<CommandOption, E> {
        let basic = |raw: Self| BasicOption {
            name: raw.name,
            name_localizations: raw.name_localizations,
            description: raw.description,
            description_localizations: raw.description_localizations,
            name_localized: raw.name_localized,
            description_localized: raw.description_localized,
            required: raw.required,
        };
        Ok(match self.kind {
            kind @ (CommandOptionType::SubCommand | CommandOptionType::SubCommandGroup) => {
                let option = SubCommandOption {
                    name: self.name,
                    name_localizations: self.name_localizations,
                    description: self.description,
                    description_localizations: self.description_localizations,
                    name_localized: self.name_localized,
                    description_localized: self.description_localized,
                    options: self.options,
                };
                if kind == CommandOptionType::SubCommand {
                    CommandOption::SubCommand(option)
                } else {
                    CommandOption::SubCommandGroup(option)
                }
            }
            CommandOptionType::String => CommandOption::String(StringOption {
                choices: convert_choices(self.choices, RawValue::into_string)?,
                name: self.name,
                name_localizations: self.name_localizations,
                description: self.description,
                description_localizations: self.description_localizations,
                name_localized: self.name_localized,
                description_localized: self.description_localized,
                required: self.required,
                min_length: self.min_length,
                max_length: self.max_length,
                autocomplete: self.autocomplete,
            }),
            CommandOptionType::Integer => CommandOption::Integer(IntegerOption {
                choices: convert_choices(self.choices, RawValue::into_integer)?,
                min_value: self.min_value.map(RawValue::into_integer).transpose()?,
                max_value: self.max_value.map(RawValue::into_integer).transpose()?,
                name: self.name,
                name_localizations: self.name_localizations,
                description: self.description,
                description_localizations: self.description_localizations,
                name_localized: self.name_localized,
                description_localized: self.description_localized,
                required: self.required,
                autocomplete: self.autocomplete,
            }),
            CommandOptionType::Number => CommandOption::Number(NumberOption {
                choices: convert_choices(self.choices, RawValue::into_number)?,
                min_value: self.min_value.map(RawValue::into_number).transpose()?,
                max_value: self.max_value.map(RawValue::into_number).transpose()?,
                name: self.name,
                name_localizations: self.name_localizations,
                description: self.description,
                description_localizations: self.description_localizations,
                name_localized: self.name_localized,
                description_localized: self.description_localized,
                required: self.required,
                autocomplete: self.autocomplete,
            }),
            CommandOptionType::Boolean => CommandOption::Boolean(basic(self)),
            CommandOptionType::User => CommandOption::User(basic(self)),
            CommandOptionType::Role => CommandOption::Role(basic(self)),
            CommandOptionType::Mentionable => CommandOption::Mentionable(basic(self)),
            CommandOptionType::Channel => CommandOption::Channel(ChannelOption {
                name: self.name,
                name_localizations: self.name_localizations,
                description: self.description,
                description_localizations: self.description_localizations,
                name_localized: self.name_localized,
                description_localized: self.description_localized,
                required: self.required,
                channel_types: self.channel_types,
            }),
            CommandOptionType::Attachment => CommandOption::Attachment(AttachmentOption {
                name: self.name,
                name_localizations: self.name_localizations,
                description: self.description,
                description_localizations: self.description_localizations,
                name_localized: self.name_localized,
                description_localized: self.description_localized,
                required: self.required,
                file_types: self.file_types,
            }),
            kind @ CommandOptionType::Unknown(_) => CommandOption::Unknown(UnknownOption {
                kind,
                name: self.name,
                name_localizations: self.name_localizations,
                description: self.description,
                description_localizations: self.description_localizations,
                name_localized: self.name_localized,
                description_localized: self.description_localized,
                required: self.required,
            }),
        })
    }
}

impl<'de> Deserialize<'de> for CommandOption {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        RawOption::deserialize(deserializer)?.into_option::<D::Error>()
    }
}

/// Serializes a variant's struct together with its `type`.
#[derive(Serialize)]
struct Tagged<'a, T> {
    #[serde(rename = "type")]
    kind: CommandOptionType,
    #[serde(flatten)]
    option: &'a T,
}

impl Serialize for CommandOption {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let kind = self.kind();
        match self {
            Self::SubCommand(option) | Self::SubCommandGroup(option) => {
                Tagged { kind, option }.serialize(serializer)
            }
            Self::String(option) => Tagged { kind, option }.serialize(serializer),
            Self::Integer(option) => Tagged { kind, option }.serialize(serializer),
            Self::Boolean(option)
            | Self::User(option)
            | Self::Role(option)
            | Self::Mentionable(option) => Tagged { kind, option }.serialize(serializer),
            Self::Channel(option) => Tagged { kind, option }.serialize(serializer),
            Self::Number(option) => Tagged { kind, option }.serialize(serializer),
            Self::Attachment(option) => Tagged { kind, option }.serialize(serializer),
            Self::Unknown(option) => Tagged { kind, option }.serialize(serializer),
        }
    }
}

/// The [permissions of an app's command(s) in a guild](https://docs.discord.com/developers/interactions/application-commands#application-command-permissions-object-guild-application-command-permissions-structure).
///
/// discord.js counterpart: `ApplicationCommandPermissions` (per guild).
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
#[doc(alias = "GuildApplicationCommandPermissions")]
pub struct GuildCommandPermissions {
    /// The command, or the application ID for permissions that apply to all its commands
    /// without their own.
    pub id: GenericId,
    /// The application the command belongs to.
    pub application_id: ApplicationId,
    /// The guild.
    pub guild_id: GuildId,
    /// The permissions (max 100).
    pub permissions: Vec<CommandPermission>,
}

/// One [command permission](https://docs.discord.com/developers/interactions/application-commands#application-command-permissions-object-application-command-permissions-structure):
/// allows or denies a command for a role, user or channel.
///
/// discord.js counterpart: `ApplicationCommandPermissions`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
#[doc(alias = "ApplicationCommandPermissions")]
pub struct CommandPermission {
    /// The role, user or channel; see [`everyone`](Self::everyone) and
    /// [`all_channels`](Self::all_channels) for the special values.
    pub id: GenericId,
    /// What [`id`](Self::id) refers to.
    #[serde(rename = "type")]
    pub kind: CommandPermissionType,
    /// `true` to allow, `false` to deny.
    pub permission: bool,
}

impl CommandPermission {
    /// Creates a permission.
    ///
    /// discord.js counterpart: `ApplicationCommandPermissions`.
    #[must_use]
    pub const fn new(id: GenericId, kind: CommandPermissionType, permission: bool) -> Self {
        Self {
            id,
            kind,
            permission,
        }
    }

    /// The ID that stands for `@everyone` (all members) in `guild_id`: the guild ID itself.
    ///
    /// discord.js counterpart: `Guild#roles.everyone`'s ID (the guild's ID).
    #[must_use]
    pub const fn everyone(guild_id: GuildId) -> GenericId {
        guild_id.cast()
    }

    /// The ID that stands for all channels in `guild_id`: the guild ID minus one, or `None`
    /// for the (impossible) guild ID `1`.
    ///
    /// discord.js counterpart: none (discord.js leaves the guild ID minus one to the bot).
    #[must_use]
    pub const fn all_channels(guild_id: GuildId) -> Option<GenericId> {
        GenericId::new_checked(guild_id.get() - 1)
    }
}

int_enum! {
    /// [What a command permission applies to](https://docs.discord.com/developers/interactions/application-commands#application-command-permissions-object-application-command-permission-type).
    ///
    /// discord.js counterpart: `ApplicationCommandPermissionType`.
    #[doc(alias = "ApplicationCommandPermissionType")]
    pub enum CommandPermissionType: u8 {
        /// A role (or `@everyone`).
        Role = 1,
        /// A user.
        User = 2,
        /// A channel (or all channels).
        Channel = 3,
    }
}