mini-interactions 0.0.0-stage → 0.15.0

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 (152) hide show
  1. package/LICENSE +21 -0
  2. package/MIGRATION.md +126 -0
  3. package/README.md +253 -2
  4. package/dist/bot.d.ts +58 -0
  5. package/dist/bot.js +217 -0
  6. package/dist/builders/ActionRowBuilder.d.ts +22 -0
  7. package/dist/builders/ActionRowBuilder.js +33 -0
  8. package/dist/builders/AutomodRuleBuilder.d.ts +45 -0
  9. package/dist/builders/AutomodRuleBuilder.js +151 -0
  10. package/dist/builders/ButtonBuilder.d.ts +53 -0
  11. package/dist/builders/ButtonBuilder.js +124 -0
  12. package/dist/builders/ChannelSelectMenuBuilder.d.ts +53 -0
  13. package/dist/builders/ChannelSelectMenuBuilder.js +105 -0
  14. package/dist/builders/CheckboxBuilder.d.ts +20 -0
  15. package/dist/builders/CheckboxBuilder.js +20 -0
  16. package/dist/builders/CheckboxGroupBuilder.d.ts +25 -0
  17. package/dist/builders/CheckboxGroupBuilder.js +48 -0
  18. package/dist/builders/EmbedBuilder.d.ts +33 -0
  19. package/dist/builders/EmbedBuilder.js +103 -0
  20. package/dist/builders/FileUploadBuilder.d.ts +17 -0
  21. package/dist/builders/FileUploadBuilder.js +22 -0
  22. package/dist/builders/LabelBuilder.d.ts +16 -0
  23. package/dist/builders/LabelBuilder.js +21 -0
  24. package/dist/builders/MiniContainerBuilder.d.ts +131 -0
  25. package/dist/builders/MiniContainerBuilder.js +347 -0
  26. package/dist/builders/ModalBuilder.d.ts +16 -0
  27. package/dist/builders/ModalBuilder.js +36 -0
  28. package/dist/builders/ModalChannelSelectMenuBuilder.d.ts +29 -0
  29. package/dist/builders/ModalChannelSelectMenuBuilder.js +25 -0
  30. package/dist/builders/ModalMentionableSelectMenuBuilder.d.ts +53 -0
  31. package/dist/builders/ModalMentionableSelectMenuBuilder.js +87 -0
  32. package/dist/builders/ModalRoleSelectMenuBuilder.d.ts +27 -0
  33. package/dist/builders/ModalRoleSelectMenuBuilder.js +24 -0
  34. package/dist/builders/ModalStringSelectMenuBuilder.d.ts +62 -0
  35. package/dist/builders/ModalStringSelectMenuBuilder.js +120 -0
  36. package/dist/builders/ModalUserSelectMenuBuilder.d.ts +53 -0
  37. package/dist/builders/ModalUserSelectMenuBuilder.js +96 -0
  38. package/dist/builders/RadioBuilder.d.ts +22 -0
  39. package/dist/builders/RadioBuilder.js +36 -0
  40. package/dist/builders/RoleSelectMenuBuilder.d.ts +47 -0
  41. package/dist/builders/RoleSelectMenuBuilder.js +92 -0
  42. package/dist/builders/StringSelectMenuBuilder.d.ts +52 -0
  43. package/dist/builders/StringSelectMenuBuilder.js +104 -0
  44. package/dist/builders/StringSelectMenuOptionBuilder.d.ts +46 -0
  45. package/dist/builders/StringSelectMenuOptionBuilder.js +106 -0
  46. package/dist/builders/TextInputBuilder.d.ts +23 -0
  47. package/dist/builders/TextInputBuilder.js +26 -0
  48. package/dist/builders/index.d.ts +44 -0
  49. package/dist/builders/index.js +22 -0
  50. package/dist/builders/shared.d.ts +8 -0
  51. package/dist/builders/shared.js +11 -0
  52. package/dist/commands/CommandBuilder.d.ts +278 -0
  53. package/dist/commands/CommandBuilder.js +687 -0
  54. package/dist/commands/ContextMenuCommandBuilder.d.ts +94 -0
  55. package/dist/commands/ContextMenuCommandBuilder.js +145 -0
  56. package/dist/core/http/DiscordRestClient.d.ts +400 -0
  57. package/dist/core/http/DiscordRestClient.js +988 -0
  58. package/dist/core/interactions/InteractionContext.d.ts +33 -0
  59. package/dist/core/interactions/InteractionContext.js +61 -0
  60. package/dist/core/interactions/InteractionVerifier.d.ts +8 -0
  61. package/dist/core/interactions/InteractionVerifier.js +9 -0
  62. package/dist/core/messages/DiscordSentMessage.d.ts +32 -0
  63. package/dist/core/messages/DiscordSentMessage.js +64 -0
  64. package/dist/core/messages/message-payloads.d.ts +94 -0
  65. package/dist/core/messages/message-payloads.js +99 -0
  66. package/dist/core/webhooks/DiscordWebhook.d.ts +14 -0
  67. package/dist/core/webhooks/DiscordWebhook.js +69 -0
  68. package/dist/database/MiniDataBuilder.d.ts +61 -0
  69. package/dist/database/MiniDataBuilder.js +98 -0
  70. package/dist/database/MiniDatabase.d.ts +67 -0
  71. package/dist/database/MiniDatabase.js +222 -0
  72. package/dist/database/MiniDatabaseBuilder.d.ts +58 -0
  73. package/dist/database/MiniDatabaseBuilder.js +84 -0
  74. package/dist/database/index.d.ts +5 -0
  75. package/dist/database/index.js +3 -0
  76. package/dist/identity/ApplicationIdentityProfile.d.ts +188 -0
  77. package/dist/identity/ApplicationIdentityProfile.js +207 -0
  78. package/dist/index.d.ts +54 -0
  79. package/dist/index.js +34 -0
  80. package/dist/lobby/Lobby.d.ts +150 -0
  81. package/dist/lobby/Lobby.js +90 -0
  82. package/dist/node/MiniInteraction.d.ts +199 -0
  83. package/dist/node/MiniInteraction.js +861 -0
  84. package/dist/node/index.d.ts +2 -0
  85. package/dist/node/index.js +1 -0
  86. package/dist/oauth2/DiscordOAuth.d.ts +49 -0
  87. package/dist/oauth2/DiscordOAuth.js +113 -0
  88. package/dist/oauth2/OAuth2Builder.d.ts +296 -0
  89. package/dist/oauth2/OAuth2Builder.js +435 -0
  90. package/dist/oauth2/OAuth2Scopes.d.ts +285 -0
  91. package/dist/oauth2/OAuth2Scopes.js +438 -0
  92. package/dist/oauth2/OAuthTokenStorage.d.ts +37 -0
  93. package/dist/oauth2/OAuthTokenStorage.js +109 -0
  94. package/dist/oauth2/index.d.ts +8 -0
  95. package/dist/oauth2/index.js +4 -0
  96. package/dist/router/AutocompleteContext.d.ts +36 -0
  97. package/dist/router/AutocompleteContext.js +82 -0
  98. package/dist/router/InteractionRouter.d.ts +82 -0
  99. package/dist/router/InteractionRouter.js +225 -0
  100. package/dist/types/ButtonStyle.d.ts +16 -0
  101. package/dist/types/ButtonStyle.js +17 -0
  102. package/dist/types/ChannelType.d.ts +2 -0
  103. package/dist/types/ChannelType.js +2 -0
  104. package/dist/types/Commands.d.ts +35 -0
  105. package/dist/types/Commands.js +1 -0
  106. package/dist/types/ComponentTypes.d.ts +19 -0
  107. package/dist/types/ComponentTypes.js +1 -0
  108. package/dist/types/InteractionFlags.d.ts +5 -0
  109. package/dist/types/InteractionFlags.js +6 -0
  110. package/dist/types/PermissionFlags.d.ts +56 -0
  111. package/dist/types/PermissionFlags.js +5 -0
  112. package/dist/types/RoleConnectionMetadata.d.ts +14 -0
  113. package/dist/types/RoleConnectionMetadata.js +1 -0
  114. package/dist/types/RoleConnectionMetadataTypes.d.ts +11 -0
  115. package/dist/types/RoleConnectionMetadataTypes.js +12 -0
  116. package/dist/types/SeparatorSpacingSize.d.ts +2 -0
  117. package/dist/types/SeparatorSpacingSize.js +2 -0
  118. package/dist/types/checkbox.d.ts +16 -0
  119. package/dist/types/checkbox.js +12 -0
  120. package/dist/types/discord.d.ts +2 -0
  121. package/dist/types/discord.js +1 -0
  122. package/dist/types/radio.d.ts +12 -0
  123. package/dist/types/radio.js +10 -0
  124. package/dist/types/validation.d.ts +14 -0
  125. package/dist/types/validation.js +40 -0
  126. package/dist/utils/CommandInteractionOptions.d.ts +66 -0
  127. package/dist/utils/CommandInteractionOptions.js +364 -0
  128. package/dist/utils/ContextMenuInteraction.d.ts +76 -0
  129. package/dist/utils/ContextMenuInteraction.js +152 -0
  130. package/dist/utils/MessageComponentInteraction.d.ts +148 -0
  131. package/dist/utils/MessageComponentInteraction.js +259 -0
  132. package/dist/utils/ModalSubmitInteraction.d.ts +86 -0
  133. package/dist/utils/ModalSubmitInteraction.js +267 -0
  134. package/dist/utils/cdn.d.ts +30 -0
  135. package/dist/utils/cdn.js +60 -0
  136. package/dist/utils/formatting.d.ts +76 -0
  137. package/dist/utils/formatting.js +132 -0
  138. package/dist/utils/interactionMessageHelpers.d.ts +40 -0
  139. package/dist/utils/interactionMessageHelpers.js +118 -0
  140. package/dist/utils/localization.d.ts +25 -0
  141. package/dist/utils/localization.js +38 -0
  142. package/dist/utils/snowflake.d.ts +19 -0
  143. package/dist/utils/snowflake.js +32 -0
  144. package/dist/webhooks/WebhookEvent.d.ts +229 -0
  145. package/dist/webhooks/WebhookEvent.js +59 -0
  146. package/dist/webhooks/WebhookEventRouter.d.ts +123 -0
  147. package/dist/webhooks/WebhookEventRouter.js +160 -0
  148. package/dist/webhooks/WebhookEventVerifier.d.ts +33 -0
  149. package/dist/webhooks/WebhookEventVerifier.js +37 -0
  150. package/dist/webhooks/index.d.ts +6 -0
  151. package/dist/webhooks/index.js +3 -0
  152. package/package.json +90 -4
@@ -0,0 +1,67 @@
1
+ import type { MiniDataBuilder } from "./MiniDataBuilder.js";
2
+ import type { DatabaseConfig } from "./MiniDatabaseBuilder.js";
3
+ /**
4
+ * MiniDatabase provides async data storage backed by MongoDB.
5
+ * Designed to work seamlessly with Vercel and other serverless environments.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const db = new MiniDatabase(config, schema);
10
+ *
11
+ * // Get data
12
+ * const user = await db.get("user123");
13
+ *
14
+ * // Set data
15
+ * await db.set("user123", { username: "john", coins: 100 });
16
+ *
17
+ * // Update data
18
+ * await db.update("user123", { coins: 150 });
19
+ * ```
20
+ */
21
+ export declare class MiniDatabase {
22
+ private config;
23
+ private schema?;
24
+ private mongoClient?;
25
+ private mongoDb?;
26
+ private mongoCollection?;
27
+ private initPromise?;
28
+ /**
29
+ * Creates a MiniDatabase instance using an environment variable for the MongoDB URI.
30
+ * Defaults to the `MONGODB_URI` variable expected by Vercel and many hosting providers.
31
+ */
32
+ static fromEnv(schema?: MiniDataBuilder, options?: {
33
+ variable?: string;
34
+ dbName?: string;
35
+ collectionName?: string;
36
+ }): MiniDatabase;
37
+ constructor(config: DatabaseConfig, schema?: MiniDataBuilder);
38
+ private sanitiseStoredData;
39
+ /**
40
+ * Initializes the database connection.
41
+ */
42
+ private initialize;
43
+ /**
44
+ * Initializes MongoDB connection.
45
+ */
46
+ private initializeMongoDB;
47
+ /**
48
+ * Gets data by key.
49
+ */
50
+ get(key: string): Promise<Record<string, unknown> | null>;
51
+ /**
52
+ * Sets data by key (overwrites existing data).
53
+ */
54
+ set(key: string, data: Record<string, unknown>): Promise<boolean>;
55
+ /**
56
+ * Updates specific fields in data (merges with existing data).
57
+ */
58
+ update(key: string, updates: Record<string, unknown>): Promise<boolean>;
59
+ /**
60
+ * Deletes data by key.
61
+ */
62
+ delete(key: string): Promise<boolean>;
63
+ /**
64
+ * Closes the database connection (for MongoDB).
65
+ */
66
+ close(): Promise<void>;
67
+ }
@@ -0,0 +1,222 @@
1
+ import { MiniDatabaseBuilder } from "./MiniDatabaseBuilder.js";
2
+ /**
3
+ * MiniDatabase provides async data storage backed by MongoDB.
4
+ * Designed to work seamlessly with Vercel and other serverless environments.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * const db = new MiniDatabase(config, schema);
9
+ *
10
+ * // Get data
11
+ * const user = await db.get("user123");
12
+ *
13
+ * // Set data
14
+ * await db.set("user123", { username: "john", coins: 100 });
15
+ *
16
+ * // Update data
17
+ * await db.update("user123", { coins: 150 });
18
+ * ```
19
+ */
20
+ export class MiniDatabase {
21
+ config;
22
+ schema;
23
+ mongoClient;
24
+ mongoDb;
25
+ mongoCollection;
26
+ initPromise;
27
+ /**
28
+ * Creates a MiniDatabase instance using an environment variable for the MongoDB URI.
29
+ * Defaults to the `MONGODB_URI` variable expected by Vercel and many hosting providers.
30
+ */
31
+ static fromEnv(schema, options) {
32
+ const variable = options?.variable ?? "MONGODB_URI";
33
+ const uri = process.env[variable];
34
+ if (!uri) {
35
+ throw new Error(`[MiniDatabase] Environment variable "${variable}" is not set`);
36
+ }
37
+ const builder = new MiniDatabaseBuilder()
38
+ .setMongoUri(uri)
39
+ .setDbName(options?.dbName ?? "minidb")
40
+ .setCollectionName(options?.collectionName ?? "data");
41
+ return new MiniDatabase(builder.build(), schema);
42
+ }
43
+ constructor(config, schema) {
44
+ this.config = config;
45
+ this.schema = schema;
46
+ }
47
+ sanitiseStoredData(data) {
48
+ const { _id, createdAt, updatedAt, ...rest } = data;
49
+ return rest;
50
+ }
51
+ /**
52
+ * Initializes the database connection.
53
+ */
54
+ async initialize() {
55
+ if (this.initPromise) {
56
+ return this.initPromise;
57
+ }
58
+ this.initPromise = this.initializeMongoDB().catch((error) => {
59
+ this.initPromise = undefined;
60
+ throw error;
61
+ });
62
+ return this.initPromise;
63
+ }
64
+ /**
65
+ * Initializes MongoDB connection.
66
+ */
67
+ async initializeMongoDB() {
68
+ try {
69
+ let MongoClient;
70
+ try {
71
+ // @ts-ignore - MongoDB is optional
72
+ const mongoModule = await import("mongodb");
73
+ MongoClient = mongoModule.MongoClient;
74
+ }
75
+ catch {
76
+ throw new Error("MongoDB driver not installed. Install it with: npm install mongodb");
77
+ }
78
+ if (!this.config.mongoUri) {
79
+ throw new Error("MongoDB URI is required");
80
+ }
81
+ this.mongoClient = new MongoClient(this.config.mongoUri, {
82
+ maxPoolSize: 5,
83
+ });
84
+ await this.mongoClient.connect();
85
+ this.mongoDb = this.mongoClient.db(this.config.dbName || "minidb");
86
+ this.mongoCollection = this.mongoDb.collection(this.config.collectionName || "data");
87
+ }
88
+ catch (err) {
89
+ console.error("❌ [MiniDatabase] Failed to connect to MongoDB:", err);
90
+ throw err;
91
+ }
92
+ }
93
+ /**
94
+ * Gets data by key.
95
+ */
96
+ async get(key) {
97
+ await this.initialize();
98
+ try {
99
+ const collection = this.mongoCollection;
100
+ if (!collection) {
101
+ throw new Error("MongoDB collection is not initialized");
102
+ }
103
+ const doc = await collection.findOne({ _id: key });
104
+ if (!doc) {
105
+ return null;
106
+ }
107
+ const { _id, ...rest } = doc;
108
+ return rest;
109
+ }
110
+ catch (err) {
111
+ console.error(`❌ [MiniDatabase] Failed to get data for key "${key}":`, err);
112
+ return null;
113
+ }
114
+ }
115
+ /**
116
+ * Sets data by key (overwrites existing data).
117
+ */
118
+ async set(key, data) {
119
+ await this.initialize();
120
+ try {
121
+ const collection = this.mongoCollection;
122
+ if (!collection) {
123
+ throw new Error("MongoDB collection is not initialized");
124
+ }
125
+ // Validate against schema if provided
126
+ if (this.schema) {
127
+ const validation = this.schema.validate(data);
128
+ if (!validation.valid) {
129
+ throw new Error(`Validation failed: ${validation.errors.join(", ")}`);
130
+ }
131
+ }
132
+ const dataWithDefaults = this.schema
133
+ ? this.schema.applyDefaults(data)
134
+ : data;
135
+ const sanitizedData = this.sanitiseStoredData(dataWithDefaults);
136
+ await collection.updateOne({ _id: key }, {
137
+ $set: {
138
+ ...sanitizedData,
139
+ _id: key,
140
+ updatedAt: new Date(),
141
+ },
142
+ $setOnInsert: {
143
+ createdAt: new Date(),
144
+ },
145
+ }, { upsert: true });
146
+ return true;
147
+ }
148
+ catch (err) {
149
+ console.error(`❌ [MiniDatabase] Failed to set data for key "${key}":`, err);
150
+ return false;
151
+ }
152
+ }
153
+ /**
154
+ * Updates specific fields in data (merges with existing data).
155
+ */
156
+ async update(key, updates) {
157
+ await this.initialize();
158
+ try {
159
+ const collection = this.mongoCollection;
160
+ if (!collection) {
161
+ throw new Error("MongoDB collection is not initialized");
162
+ }
163
+ const existing = await this.get(key);
164
+ const merged = { ...(existing ?? {}), ...updates };
165
+ // Validate merged data against schema if provided
166
+ if (this.schema) {
167
+ const validation = this.schema.validate(merged);
168
+ if (!validation.valid) {
169
+ throw new Error(`Validation failed: ${validation.errors.join(", ")}`);
170
+ }
171
+ }
172
+ const dataWithDefaults = this.schema
173
+ ? this.schema.applyDefaults(merged)
174
+ : merged;
175
+ const sanitizedData = this.sanitiseStoredData(dataWithDefaults);
176
+ await collection.updateOne({ _id: key }, {
177
+ $set: {
178
+ ...sanitizedData,
179
+ updatedAt: new Date(),
180
+ },
181
+ $setOnInsert: {
182
+ createdAt: new Date(),
183
+ },
184
+ }, { upsert: true });
185
+ return true;
186
+ }
187
+ catch (err) {
188
+ console.error(`❌ [MiniDatabase] Failed to update data for key "${key}":`, err);
189
+ return false;
190
+ }
191
+ }
192
+ /**
193
+ * Deletes data by key.
194
+ */
195
+ async delete(key) {
196
+ await this.initialize();
197
+ try {
198
+ const collection = this.mongoCollection;
199
+ if (!collection) {
200
+ throw new Error("MongoDB collection is not initialized");
201
+ }
202
+ await collection.deleteOne({ _id: key });
203
+ return true;
204
+ }
205
+ catch (err) {
206
+ console.error(`❌ [MiniDatabase] Failed to delete data for key "${key}":`, err);
207
+ return false;
208
+ }
209
+ }
210
+ /**
211
+ * Closes the database connection (for MongoDB).
212
+ */
213
+ async close() {
214
+ if (this.mongoClient) {
215
+ await this.mongoClient.close();
216
+ }
217
+ this.mongoClient = undefined;
218
+ this.mongoDb = undefined;
219
+ this.mongoCollection = undefined;
220
+ this.initPromise = undefined;
221
+ }
222
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Configuration for MiniDatabase backend.
3
+ */
4
+ export interface DatabaseConfig {
5
+ mongoUri: string;
6
+ dbName: string;
7
+ collectionName: string;
8
+ }
9
+ /**
10
+ * Builder for configuring MiniDatabase.
11
+ * Provides a fluent API for easy database setup.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const db = new MiniDatabaseBuilder()
16
+ * .useMongoUriFromEnv()
17
+ * .setDbName("myapp")
18
+ * .setCollectionName("users")
19
+ * .build();
20
+ * ```
21
+ */
22
+ export declare class MiniDatabaseBuilder {
23
+ private config;
24
+ /**
25
+ * Sets the MongoDB connection URI.
26
+ */
27
+ setMongoUri(uri: string): this;
28
+ /**
29
+ * Reads the MongoDB connection URI from an environment variable.
30
+ * Defaults to `MONGODB_URI`.
31
+ */
32
+ useMongoUriFromEnv(variable?: string): this;
33
+ /**
34
+ * Sets the MongoDB database name.
35
+ * Default: "minidb"
36
+ */
37
+ setDbName(name: string): this;
38
+ /**
39
+ * Sets the MongoDB collection name.
40
+ * Default: "data"
41
+ */
42
+ setCollectionName(name: string): this;
43
+ /**
44
+ * Gets the current configuration.
45
+ */
46
+ getConfig(): DatabaseConfig;
47
+ /**
48
+ * Validates the configuration.
49
+ */
50
+ validate(): {
51
+ valid: boolean;
52
+ errors: string[];
53
+ };
54
+ /**
55
+ * Builds and returns the configuration.
56
+ */
57
+ build(): DatabaseConfig;
58
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Builder for configuring MiniDatabase.
3
+ * Provides a fluent API for easy database setup.
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * const db = new MiniDatabaseBuilder()
8
+ * .useMongoUriFromEnv()
9
+ * .setDbName("myapp")
10
+ * .setCollectionName("users")
11
+ * .build();
12
+ * ```
13
+ */
14
+ export class MiniDatabaseBuilder {
15
+ config = {
16
+ mongoUri: process.env.MONGODB_URI ?? "",
17
+ dbName: "minidb",
18
+ collectionName: "data",
19
+ };
20
+ /**
21
+ * Sets the MongoDB connection URI.
22
+ */
23
+ setMongoUri(uri) {
24
+ this.config.mongoUri = uri;
25
+ return this;
26
+ }
27
+ /**
28
+ * Reads the MongoDB connection URI from an environment variable.
29
+ * Defaults to `MONGODB_URI`.
30
+ */
31
+ useMongoUriFromEnv(variable = "MONGODB_URI") {
32
+ const value = process.env[variable];
33
+ if (!value) {
34
+ throw new Error(`[MiniDatabaseBuilder] Environment variable "${variable}" is not set`);
35
+ }
36
+ this.config.mongoUri = value;
37
+ return this;
38
+ }
39
+ /**
40
+ * Sets the MongoDB database name.
41
+ * Default: "minidb"
42
+ */
43
+ setDbName(name) {
44
+ this.config.dbName = name;
45
+ return this;
46
+ }
47
+ /**
48
+ * Sets the MongoDB collection name.
49
+ * Default: "data"
50
+ */
51
+ setCollectionName(name) {
52
+ this.config.collectionName = name;
53
+ return this;
54
+ }
55
+ /**
56
+ * Gets the current configuration.
57
+ */
58
+ getConfig() {
59
+ return { ...this.config };
60
+ }
61
+ /**
62
+ * Validates the configuration.
63
+ */
64
+ validate() {
65
+ const errors = [];
66
+ if (!this.config.mongoUri) {
67
+ errors.push("MongoDB URI is required");
68
+ }
69
+ return {
70
+ valid: errors.length === 0,
71
+ errors,
72
+ };
73
+ }
74
+ /**
75
+ * Builds and returns the configuration.
76
+ */
77
+ build() {
78
+ const validation = this.validate();
79
+ if (!validation.valid) {
80
+ throw new Error(`Invalid database configuration: ${validation.errors.join(", ")}`);
81
+ }
82
+ return this.getConfig();
83
+ }
84
+ }
@@ -0,0 +1,5 @@
1
+ export { MiniDataBuilder } from "./MiniDataBuilder.js";
2
+ export type { DataField } from "./MiniDataBuilder.js";
3
+ export { MiniDatabaseBuilder } from "./MiniDatabaseBuilder.js";
4
+ export type { DatabaseConfig } from "./MiniDatabaseBuilder.js";
5
+ export { MiniDatabase } from "./MiniDatabase.js";
@@ -0,0 +1,3 @@
1
+ export { MiniDataBuilder } from "./MiniDataBuilder.js";
2
+ export { MiniDatabaseBuilder } from "./MiniDatabaseBuilder.js";
3
+ export { MiniDatabase } from "./MiniDatabase.js";
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Application Identity profiles power **Game Stats Widgets** — the rank,
3
+ * playtime and win panel a *claimed* game can render on a Discord user profile.
4
+ *
5
+ * Everything here is plain HTTP authenticated with the application's **bot
6
+ * token**, so it works in stateless/serverless deployments with no gateway.
7
+ *
8
+ * Prerequisites (configured outside this library):
9
+ * - The game must be **claimed on Discord** and a widget configured under
10
+ * Developer Portal → Games → Widget.
11
+ * - The player must have linked their Discord account via OAuth2 with the
12
+ * `application_identities.write` scope.
13
+ * - Media URLs must be reachable from the public internet: Discord's unfurler
14
+ * fetches them server-side, so `localhost`/LAN URLs never resolve.
15
+ *
16
+ * @see {@link https://docs.discord.com/developers/resources/application-identity-profile}
17
+ * @see {@link https://docs.discord.com/developers/social-layer/game-stats-widgets/overview}
18
+ */
19
+ /**
20
+ * Discriminator for a dynamic (custom) profile field.
21
+ *
22
+ * - `String` (1) — a text value
23
+ * - `Number` (2) — a numeric value
24
+ * - `Media` (3) — a media object (public image URL)
25
+ */
26
+ export declare const DynamicFieldType: {
27
+ readonly String: 1;
28
+ readonly Number: 2;
29
+ readonly Media: 3;
30
+ };
31
+ export type DynamicFieldType = (typeof DynamicFieldType)[keyof typeof DynamicFieldType];
32
+ /** Provider type of an {@link APIApplicationIdentity}. */
33
+ export type ApplicationIdentityProviderType = "NONE" | (string & {});
34
+ /** A media value: a publicly reachable URL Discord's unfurler can fetch. */
35
+ export type ProfileMedia = {
36
+ url: string;
37
+ };
38
+ /**
39
+ * A custom stat. The `name` is the data key referenced from the widget editor
40
+ * (its `User Data` value type) — it is never shown to players.
41
+ */
42
+ export type DynamicProfileField = {
43
+ type: typeof DynamicFieldType.String;
44
+ name: string;
45
+ value: string;
46
+ } | {
47
+ type: typeof DynamicFieldType.Number;
48
+ name: string;
49
+ value: number;
50
+ } | {
51
+ type: typeof DynamicFieldType.Media;
52
+ name: string;
53
+ value: ProfileMedia;
54
+ };
55
+ /**
56
+ * Pre-configured stat keys defined by Discord. All fields are optional —
57
+ * populate the ones that fit your game. Every value is fully replaced on write.
58
+ */
59
+ export type PrimaryProfileData = {
60
+ /** Current season name, e.g. `"Season 3"`. */
61
+ season?: string;
62
+ /** Current rank name, e.g. `"Silver"`. */
63
+ rank_name?: string;
64
+ /** Image representing the current rank. */
65
+ rank_image?: ProfileMedia;
66
+ /** Highest rank ever achieved. */
67
+ highest_rank?: string;
68
+ /** Image representing the highest rank achieved. */
69
+ highest_rank_image?: ProfileMedia;
70
+ /** Name of the featured played character. */
71
+ featured_played_character?: string;
72
+ /** Image of the featured played character. */
73
+ featured_played_character_image?: ProfileMedia;
74
+ /** Total playtime in hours; decimals allowed (e.g. `69.41`). */
75
+ playtime_hours?: number;
76
+ total_wins?: number;
77
+ current_period_wins?: number;
78
+ total_games?: number;
79
+ current_period_games?: number;
80
+ total_kills?: number;
81
+ current_period_kills?: number;
82
+ total_assists?: number;
83
+ current_period_assists?: number;
84
+ total_deaths?: number;
85
+ current_period_deaths?: number;
86
+ };
87
+ /** The `data` payload of a profile: pre-configured primary stats + custom dynamic stats. */
88
+ export type ApplicationIdentityProfileData = {
89
+ primary?: PrimaryProfileData;
90
+ /** Custom stats. Maximum {@link APPLICATION_IDENTITY_LIMITS.MaxDynamicFields} entries. */
91
+ dynamic?: DynamicProfileField[];
92
+ };
93
+ /** An Application Identity record returned by the list endpoints. */
94
+ export type APIApplicationIdentity = {
95
+ user_id: string;
96
+ provider_type: ApplicationIdentityProviderType;
97
+ /** Omitted when absent or empty. */
98
+ provider_id?: string;
99
+ /** The user's ID *in your system* — not a Discord snowflake. */
100
+ provider_issued_user_id: string;
101
+ };
102
+ /** A player's stored profile, as returned by the get/update endpoints. */
103
+ export type ApplicationIdentityProfile = {
104
+ /** The user's username in *your* system. */
105
+ username?: string;
106
+ /** Arbitrary app-owned data; Discord stores it but never consumes it. */
107
+ metadata?: Record<string, unknown> | null;
108
+ data?: ApplicationIdentityProfileData;
109
+ };
110
+ /**
111
+ * Body of {@link UpdateIdentityProfileBody}.
112
+ *
113
+ * **`data` is fully replaced whenever it is present.** Any field you omit is
114
+ * deleted. Omit `data` entirely to leave the stored stats untouched.
115
+ */
116
+ export type UpdateIdentityProfileBody = {
117
+ /** Max {@link APPLICATION_IDENTITY_LIMITS.MaxUsernameLength} characters. */
118
+ username?: string;
119
+ data?: ApplicationIdentityProfileData;
120
+ };
121
+ /** Hard limits enforced by Discord; validated client-side so failures are obvious. */
122
+ export declare const APPLICATION_IDENTITY_LIMITS: {
123
+ /** Serialized `data` object must stay under 10 KB. */
124
+ readonly MaxSerializedDataBytes: number;
125
+ /** Maximum number of `dynamic` fields. */
126
+ readonly MaxDynamicFields: 30;
127
+ /** Maximum length of any string stat value (e.g. `rank_name`). */
128
+ readonly MaxStringValueLength: 100;
129
+ /** Maximum length of a dynamic field `name` (its data key). */
130
+ readonly MaxDynamicFieldNameLength: 100;
131
+ /** Maximum length of `username`. */
132
+ readonly MaxUsernameLength: 1024;
133
+ };
134
+ /** Machine-readable reasons a Game Stats payload was rejected before hitting the API. */
135
+ export type ApplicationIdentityProfileErrorCode = "payload_too_large" | "too_many_dynamic_fields" | "string_value_too_long" | "dynamic_field_name_too_long" | "username_too_long" | "media_url_not_public";
136
+ /**
137
+ * Thrown when a Game Stats payload would be rejected by Discord, so callers can
138
+ * branch on {@link code} instead of string-matching an API error.
139
+ */
140
+ export declare class ApplicationIdentityProfileError extends Error {
141
+ readonly code: ApplicationIdentityProfileErrorCode;
142
+ constructor(code: ApplicationIdentityProfileErrorCode, message: string);
143
+ }
144
+ /** Error strings the Application Identity Profile API returns that are worth branching on. */
145
+ export declare const APPLICATION_IDENTITY_PROFILE_ERRORS: {
146
+ readonly PayloadTooLarge: "Profile data is too large, must be less than 10KB";
147
+ readonly IdentityAlreadyExists: "Application identity for this external account already exists for another user";
148
+ readonly ProviderUserMismatch: "does not match existing identity record";
149
+ };
150
+ /**
151
+ * Whether a media URL is reachable from Discord's servers.
152
+ *
153
+ * The unfurler fetches media server-side, so `localhost`, loopback, link-local
154
+ * and private-range hosts render as nothing in the widget. Expose local assets
155
+ * through a tunnel (Cloudflare Tunnel, ngrok) during development.
156
+ */
157
+ export declare function isPublicMediaUrl(url: string): boolean;
158
+ /** Serializes `data` exactly as Discord measures it, for the 10 KB ceiling. */
159
+ export declare function serializeProfileData(data: ApplicationIdentityProfileData): string;
160
+ /**
161
+ * Validates a `data` payload against Discord's documented limits.
162
+ *
163
+ * @throws {@link ApplicationIdentityProfileError} with a specific `code`.
164
+ */
165
+ export declare function assertProfileDataWithinLimits(data: ApplicationIdentityProfileData, options?: {
166
+ allowPrivateMediaUrls?: boolean;
167
+ }): void;
168
+ /** Validates a `username` against Discord's length limit. */
169
+ export declare function assertUsernameLength(username: string): void;
170
+ /**
171
+ * Builds a `data` object from optional parts, dropping undefined keys so the
172
+ * resulting payload never contains empty `primary`/`dynamic` values.
173
+ */
174
+ export declare function buildProfileData(parts: {
175
+ primary?: PrimaryProfileData;
176
+ dynamic?: DynamicProfileField[];
177
+ }): ApplicationIdentityProfileData | undefined;
178
+ /**
179
+ * Merges incoming stats into existing stats.
180
+ *
181
+ * `primary` is shallow-merged; `dynamic` fields are matched by `name`, so
182
+ * updating one custom stat leaves the others intact. This is the read-then-write
183
+ * counterpart to Discord's replace-on-PATCH behaviour.
184
+ */
185
+ export declare function mergeProfileData(existing: ApplicationIdentityProfileData | undefined, incoming: {
186
+ primary?: PrimaryProfileData;
187
+ dynamic?: DynamicProfileField[];
188
+ }): ApplicationIdentityProfileData | undefined;