spearkit 0.1.0 → 0.3.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.
- package/README.md +20 -0
- package/dist/index.cjs +2572 -71
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1656 -247
- package/dist/index.d.ts +1656 -247
- package/dist/index.js +2509 -75
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,523 @@
|
|
|
1
|
-
import { GatewayIntentBits, MessageFlags,
|
|
1
|
+
import { ButtonStyle, GatewayIntentBits, EmbedBuilder, MessageFlags, ApplicationCommandType, ComponentType, ActionRowBuilder, ButtonBuilder, ApplicationCommandOptionType, REST, Routes, StringSelectMenuBuilder, UserSelectMenuBuilder, RoleSelectMenuBuilder, ChannelSelectMenuBuilder, MentionableSelectMenuBuilder, ModalBuilder, Client, PermissionsBitField, InteractionContextType, TextInputStyle, TextInputBuilder } from 'discord.js';
|
|
2
2
|
export * from 'discord.js';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { readFile, readFileSync } from 'fs';
|
|
4
|
+
import { promisify } from 'util';
|
|
5
|
+
import { mkdir, appendFile, readFile as readFile$1, readdir } from 'fs/promises';
|
|
6
|
+
import { dirname, join, extname } from 'path';
|
|
5
7
|
import { pathToFileURL } from 'url';
|
|
6
8
|
|
|
7
9
|
// src/index.ts
|
|
10
|
+
var DEFAULT_EMBED_COLORS = {
|
|
11
|
+
error: 15747655,
|
|
12
|
+
success: 4437378,
|
|
13
|
+
info: 3447003,
|
|
14
|
+
warn: 16361509
|
|
15
|
+
};
|
|
16
|
+
var DEFAULT_EMBED_ICONS = {
|
|
17
|
+
error: "\u26D4",
|
|
18
|
+
success: "\u2705",
|
|
19
|
+
info: "\u2139\uFE0F",
|
|
20
|
+
warn: "\u26A0\uFE0F"
|
|
21
|
+
};
|
|
22
|
+
var Embeds = class {
|
|
23
|
+
/** The resolved colors for every preset. */
|
|
24
|
+
colors;
|
|
25
|
+
/** The resolved icons for every preset. */
|
|
26
|
+
icons;
|
|
27
|
+
constructor(options = {}) {
|
|
28
|
+
this.colors = { ...DEFAULT_EMBED_COLORS, ...options.colors };
|
|
29
|
+
this.icons = { ...DEFAULT_EMBED_ICONS, ...options.icons };
|
|
30
|
+
}
|
|
31
|
+
/** Red preset — something went wrong. */
|
|
32
|
+
error(input) {
|
|
33
|
+
return this.build("error", input);
|
|
34
|
+
}
|
|
35
|
+
/** Green preset — something succeeded. */
|
|
36
|
+
success(input) {
|
|
37
|
+
return this.build("success", input);
|
|
38
|
+
}
|
|
39
|
+
/** Blue preset — neutral information. */
|
|
40
|
+
info(input) {
|
|
41
|
+
return this.build("info", input);
|
|
42
|
+
}
|
|
43
|
+
/** Yellow preset — caution. */
|
|
44
|
+
warn(input) {
|
|
45
|
+
return this.build("warn", input);
|
|
46
|
+
}
|
|
47
|
+
/** Build an embed at a chosen level. */
|
|
48
|
+
build(level, input) {
|
|
49
|
+
const builder = new EmbedBuilder().setColor(this.colors[level]);
|
|
50
|
+
const icon = this.icons[level];
|
|
51
|
+
const prefix = icon.length > 0 ? `${icon} ` : "";
|
|
52
|
+
if (typeof input === "string") {
|
|
53
|
+
builder.setDescription(`${prefix}${input}`);
|
|
54
|
+
return builder;
|
|
55
|
+
}
|
|
56
|
+
if (input.title !== void 0) builder.setTitle(input.title);
|
|
57
|
+
if (input.description !== void 0) {
|
|
58
|
+
builder.setDescription(`${prefix}${input.description}`);
|
|
59
|
+
}
|
|
60
|
+
if (input.fields !== void 0) builder.addFields(...input.fields);
|
|
61
|
+
if (input.footer !== void 0) builder.setFooter(input.footer);
|
|
62
|
+
if (input.author !== void 0) builder.setAuthor(input.author);
|
|
63
|
+
if (input.url !== void 0) builder.setURL(input.url);
|
|
64
|
+
if (input.timestamp !== void 0) {
|
|
65
|
+
builder.setTimestamp(
|
|
66
|
+
input.timestamp instanceof Date ? input.timestamp : new Date(input.timestamp)
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
if (input.thumbnail !== void 0) builder.setThumbnail(input.thumbnail.url);
|
|
70
|
+
if (input.image !== void 0) builder.setImage(input.image.url);
|
|
71
|
+
return builder;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
var defaultEmbeds = new Embeds();
|
|
75
|
+
|
|
76
|
+
// src/lock.ts
|
|
77
|
+
var KeyedLock = class {
|
|
78
|
+
entries = /* @__PURE__ */ new Map();
|
|
79
|
+
defaultTtl;
|
|
80
|
+
sweepTimer;
|
|
81
|
+
constructor(options = {}) {
|
|
82
|
+
this.defaultTtl = options.ttl ?? 6e4;
|
|
83
|
+
const sweep = options.sweep ?? 15e3;
|
|
84
|
+
if (sweep > 0) {
|
|
85
|
+
this.sweepTimer = setInterval(() => this.sweep(), sweep);
|
|
86
|
+
if (typeof this.sweepTimer.unref === "function") this.sweepTimer.unref();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** Try to acquire `key`. Returns a release function, or `null` if already held. */
|
|
90
|
+
tryAcquire(key, ttl = this.defaultTtl) {
|
|
91
|
+
const existing = this.entries.get(key);
|
|
92
|
+
if (existing !== void 0 && Date.now() - existing.createdAt < existing.ttl) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
this.entries.set(key, { createdAt: Date.now(), ttl });
|
|
96
|
+
let released = false;
|
|
97
|
+
return () => {
|
|
98
|
+
if (released) return;
|
|
99
|
+
released = true;
|
|
100
|
+
this.entries.delete(key);
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/** Whether `key` is currently held and not expired. */
|
|
104
|
+
isHeld(key) {
|
|
105
|
+
const entry = this.entries.get(key);
|
|
106
|
+
return entry !== void 0 && Date.now() - entry.createdAt < entry.ttl;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Run `fn` while holding `key`. If the key is already held, calls `onBusy`
|
|
110
|
+
* (or returns `undefined`) without ever calling `fn`. Always releases on
|
|
111
|
+
* return or throw.
|
|
112
|
+
*/
|
|
113
|
+
async run(key, fn, options = {}) {
|
|
114
|
+
const release = this.tryAcquire(key, options.ttl ?? this.defaultTtl);
|
|
115
|
+
if (release === null) {
|
|
116
|
+
return options.onBusy !== void 0 ? await options.onBusy() : void 0;
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
return await fn();
|
|
120
|
+
} finally {
|
|
121
|
+
release();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** Number of currently-tracked leases (including expired-but-unswept). */
|
|
125
|
+
get size() {
|
|
126
|
+
return this.entries.size;
|
|
127
|
+
}
|
|
128
|
+
/** Drop all known leases and stop the sweep timer. */
|
|
129
|
+
dispose() {
|
|
130
|
+
this.entries.clear();
|
|
131
|
+
if (this.sweepTimer !== void 0) clearInterval(this.sweepTimer);
|
|
132
|
+
}
|
|
133
|
+
/** Manually remove a single key without running anything. */
|
|
134
|
+
forget(key) {
|
|
135
|
+
return this.entries.delete(key);
|
|
136
|
+
}
|
|
137
|
+
sweep() {
|
|
138
|
+
const now = Date.now();
|
|
139
|
+
for (const [key, entry] of this.entries.entries()) {
|
|
140
|
+
if (now - entry.createdAt > entry.ttl) this.entries.delete(key);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
// src/safe-fetch.ts
|
|
146
|
+
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
147
|
+
async function withTimeout(promise, ms) {
|
|
148
|
+
let timer;
|
|
149
|
+
try {
|
|
150
|
+
const timeout = new Promise((resolve) => {
|
|
151
|
+
timer = setTimeout(() => resolve(null), ms);
|
|
152
|
+
});
|
|
153
|
+
return await Promise.race([promise.catch(() => null), timeout]);
|
|
154
|
+
} finally {
|
|
155
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async function fetchMember(guild, userId, options = {}) {
|
|
159
|
+
if (guild == null || userId == null || userId.length === 0) return null;
|
|
160
|
+
if (options.cache !== false && options.force !== true) {
|
|
161
|
+
const cached = guild.members.cache.get(userId);
|
|
162
|
+
if (cached !== void 0) return cached;
|
|
163
|
+
}
|
|
164
|
+
return withTimeout(
|
|
165
|
+
guild.members.fetch({ user: userId, force: options.force ?? false }),
|
|
166
|
+
options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
async function fetchChannel(client, channelId, options = {}) {
|
|
170
|
+
if (client == null || channelId == null || channelId.length === 0) return null;
|
|
171
|
+
if (options.cache !== false && options.force !== true) {
|
|
172
|
+
const cached = client.channels.cache.get(channelId);
|
|
173
|
+
if (cached !== void 0) return cached;
|
|
174
|
+
}
|
|
175
|
+
return withTimeout(
|
|
176
|
+
client.channels.fetch(channelId, { force: options.force ?? false }),
|
|
177
|
+
options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
async function fetchMessage(messages, messageId, options = {}) {
|
|
181
|
+
if (messages == null || messageId == null || messageId.length === 0) return null;
|
|
182
|
+
if (options.cache !== false && options.force !== true) {
|
|
183
|
+
const cached = messages.cache.get(messageId);
|
|
184
|
+
if (cached !== void 0) return cached;
|
|
185
|
+
}
|
|
186
|
+
return withTimeout(
|
|
187
|
+
messages.fetch({ message: messageId, force: options.force ?? false }),
|
|
188
|
+
options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
async function fetchUser(client, userId, options = {}) {
|
|
192
|
+
if (client == null || userId == null || userId.length === 0) return null;
|
|
193
|
+
if (options.cache !== false && options.force !== true) {
|
|
194
|
+
const cached = client.users.cache.get(userId);
|
|
195
|
+
if (cached !== void 0) return cached;
|
|
196
|
+
}
|
|
197
|
+
return withTimeout(
|
|
198
|
+
client.users.fetch(userId, { force: options.force ?? false }),
|
|
199
|
+
options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
async function fetchGuild(client, guildId, options = {}) {
|
|
203
|
+
if (client == null || guildId == null || guildId.length === 0) return null;
|
|
204
|
+
if (options.cache !== false && options.force !== true) {
|
|
205
|
+
const cached = client.guilds.cache.get(guildId);
|
|
206
|
+
if (cached !== void 0) return cached;
|
|
207
|
+
}
|
|
208
|
+
return withTimeout(
|
|
209
|
+
client.guilds.fetch({ guild: guildId, force: options.force ?? false }),
|
|
210
|
+
options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
async function fetchRole(guild, roleId, options = {}) {
|
|
214
|
+
if (guild == null || roleId == null || roleId.length === 0) return null;
|
|
215
|
+
if (options.cache !== false && options.force !== true) {
|
|
216
|
+
const cached = guild.roles.cache.get(roleId);
|
|
217
|
+
if (cached !== void 0) return cached;
|
|
218
|
+
}
|
|
219
|
+
return withTimeout(
|
|
220
|
+
guild.roles.fetch(roleId, { force: options.force ?? false }),
|
|
221
|
+
options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
async function safeTry(op) {
|
|
225
|
+
try {
|
|
226
|
+
return await op();
|
|
227
|
+
} catch {
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
async function withSafeTimeout(promise, timeoutMs) {
|
|
232
|
+
return withTimeout(promise, timeoutMs);
|
|
233
|
+
}
|
|
234
|
+
var safeFetch = {
|
|
235
|
+
member: fetchMember,
|
|
236
|
+
channel: fetchChannel,
|
|
237
|
+
message: fetchMessage,
|
|
238
|
+
user: fetchUser,
|
|
239
|
+
guild: fetchGuild,
|
|
240
|
+
role: fetchRole,
|
|
241
|
+
try: safeTry
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
// src/format.ts
|
|
245
|
+
var EN = {
|
|
246
|
+
week: ["week", "weeks"],
|
|
247
|
+
day: ["day", "days"],
|
|
248
|
+
hour: ["hour", "hours"],
|
|
249
|
+
minute: ["minute", "minutes"],
|
|
250
|
+
second: ["second", "seconds"],
|
|
251
|
+
separator: " ",
|
|
252
|
+
zero: "0 seconds"
|
|
253
|
+
};
|
|
254
|
+
var TR = {
|
|
255
|
+
week: ["hafta", "hafta"],
|
|
256
|
+
day: ["g\xFCn", "g\xFCn"],
|
|
257
|
+
hour: ["saat", "saat"],
|
|
258
|
+
minute: ["dakika", "dakika"],
|
|
259
|
+
second: ["saniye", "saniye"],
|
|
260
|
+
separator: " ",
|
|
261
|
+
zero: "0 saniye"
|
|
262
|
+
};
|
|
263
|
+
var LABELS = {
|
|
264
|
+
en: EN,
|
|
265
|
+
"en-US": EN,
|
|
266
|
+
"en-GB": EN,
|
|
267
|
+
tr: TR,
|
|
268
|
+
"tr-TR": TR
|
|
269
|
+
};
|
|
270
|
+
var UNIT_MS = {
|
|
271
|
+
week: 7 * 864e5,
|
|
272
|
+
day: 864e5,
|
|
273
|
+
hour: 36e5,
|
|
274
|
+
minute: 6e4,
|
|
275
|
+
second: 1e3
|
|
276
|
+
};
|
|
277
|
+
var UNIT_ORDER = ["week", "day", "hour", "minute", "second"];
|
|
278
|
+
function resolveLabels(locale) {
|
|
279
|
+
if (typeof locale === "object" && locale !== null) return locale;
|
|
280
|
+
if (locale === void 0) return EN;
|
|
281
|
+
return LABELS[locale] ?? LABELS[locale.split("-")[0] ?? ""] ?? EN;
|
|
282
|
+
}
|
|
283
|
+
function formatDuration(ms, options = {}) {
|
|
284
|
+
const labels = resolveLabels(options.locale);
|
|
285
|
+
if (!Number.isFinite(ms) || ms <= 0) return labels.zero;
|
|
286
|
+
const limit = options.largest ?? 2;
|
|
287
|
+
const units = options.units ?? UNIT_ORDER;
|
|
288
|
+
const parts = [];
|
|
289
|
+
let remaining = Math.floor(ms);
|
|
290
|
+
for (const unit of units) {
|
|
291
|
+
if (parts.length >= limit) break;
|
|
292
|
+
const size = UNIT_MS[unit];
|
|
293
|
+
if (remaining < size) continue;
|
|
294
|
+
const value = Math.floor(remaining / size);
|
|
295
|
+
remaining -= value * size;
|
|
296
|
+
const word = value === 1 ? labels[unit][0] : labels[unit][1];
|
|
297
|
+
parts.push(`${value} ${word}`);
|
|
298
|
+
}
|
|
299
|
+
return parts.length > 0 ? parts.join(labels.separator) : labels.zero;
|
|
300
|
+
}
|
|
301
|
+
var DURATION_PATTERN = /(\d+(?:\.\d+)?)\s*(milliseconds|millisecond|seconds|minutes|saniye|dakika|minute|second|weeks|hours|hafta|saat|week|hour|days|day|gün|gun|min|sec|ms|wk|hr|dk|m|s|h|d|w)/gi;
|
|
302
|
+
var SHORT_TO_MS = {
|
|
303
|
+
ms: 1,
|
|
304
|
+
millisecond: 1,
|
|
305
|
+
milliseconds: 1,
|
|
306
|
+
s: 1e3,
|
|
307
|
+
sec: 1e3,
|
|
308
|
+
second: 1e3,
|
|
309
|
+
seconds: 1e3,
|
|
310
|
+
saniye: 1e3,
|
|
311
|
+
m: 6e4,
|
|
312
|
+
min: 6e4,
|
|
313
|
+
minute: 6e4,
|
|
314
|
+
minutes: 6e4,
|
|
315
|
+
dakika: 6e4,
|
|
316
|
+
dk: 6e4,
|
|
317
|
+
h: 36e5,
|
|
318
|
+
hr: 36e5,
|
|
319
|
+
hour: 36e5,
|
|
320
|
+
hours: 36e5,
|
|
321
|
+
saat: 36e5,
|
|
322
|
+
d: 864e5,
|
|
323
|
+
day: 864e5,
|
|
324
|
+
days: 864e5,
|
|
325
|
+
g\u00FCn: 864e5,
|
|
326
|
+
gun: 864e5,
|
|
327
|
+
w: 6048e5,
|
|
328
|
+
wk: 6048e5,
|
|
329
|
+
week: 6048e5,
|
|
330
|
+
weeks: 6048e5,
|
|
331
|
+
hafta: 6048e5
|
|
332
|
+
};
|
|
333
|
+
function parseDuration(input) {
|
|
334
|
+
const trimmed = input.trim().toLowerCase();
|
|
335
|
+
if (trimmed.length === 0) return null;
|
|
336
|
+
DURATION_PATTERN.lastIndex = 0;
|
|
337
|
+
let total = 0;
|
|
338
|
+
let matched = false;
|
|
339
|
+
for (; ; ) {
|
|
340
|
+
const match = DURATION_PATTERN.exec(trimmed);
|
|
341
|
+
if (match === null) break;
|
|
342
|
+
matched = true;
|
|
343
|
+
const value = Number(match[1]);
|
|
344
|
+
const unit = match[2] ?? "";
|
|
345
|
+
const ms = SHORT_TO_MS[unit];
|
|
346
|
+
if (ms !== void 0 && Number.isFinite(value)) total += value * ms;
|
|
347
|
+
}
|
|
348
|
+
return matched ? total : null;
|
|
349
|
+
}
|
|
350
|
+
function toEpochSeconds(date) {
|
|
351
|
+
return Math.floor((date instanceof Date ? date.getTime() : date) / 1e3);
|
|
352
|
+
}
|
|
353
|
+
function discordTimestamp(date, style = "f") {
|
|
354
|
+
return `<t:${toEpochSeconds(date)}:${style}>`;
|
|
355
|
+
}
|
|
356
|
+
function relativeTimestamp(date) {
|
|
357
|
+
return discordTimestamp(date, "R");
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// src/cache.ts
|
|
361
|
+
var MemoryCache = class {
|
|
362
|
+
store = /* @__PURE__ */ new Map();
|
|
363
|
+
/** Total number of stored (possibly expired) entries — primarily for tests. */
|
|
364
|
+
get size() {
|
|
365
|
+
return this.store.size;
|
|
366
|
+
}
|
|
367
|
+
async get(key) {
|
|
368
|
+
const entry = this.store.get(key);
|
|
369
|
+
if (entry === void 0) return void 0;
|
|
370
|
+
if (entry.expiresAt !== void 0 && entry.expiresAt <= Date.now()) {
|
|
371
|
+
this.store.delete(key);
|
|
372
|
+
return void 0;
|
|
373
|
+
}
|
|
374
|
+
return entry.value;
|
|
375
|
+
}
|
|
376
|
+
async set(key, value, options) {
|
|
377
|
+
const ttl = options?.ttl;
|
|
378
|
+
this.store.set(key, {
|
|
379
|
+
value,
|
|
380
|
+
expiresAt: ttl !== void 0 && ttl > 0 ? Date.now() + ttl : void 0
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
async delete(key) {
|
|
384
|
+
return this.store.delete(key);
|
|
385
|
+
}
|
|
386
|
+
async has(key) {
|
|
387
|
+
return await this.get(key) !== void 0;
|
|
388
|
+
}
|
|
389
|
+
async increment(key, delta = 1, options) {
|
|
390
|
+
const current = await this.get(key) ?? 0;
|
|
391
|
+
const next = current + delta;
|
|
392
|
+
const existing = this.store.get(key);
|
|
393
|
+
const ttl = options?.ttl;
|
|
394
|
+
if (ttl !== void 0 && ttl > 0) {
|
|
395
|
+
await this.set(key, next, { ttl });
|
|
396
|
+
} else if (existing?.expiresAt !== void 0) {
|
|
397
|
+
this.store.set(key, { value: next, expiresAt: existing.expiresAt });
|
|
398
|
+
} else {
|
|
399
|
+
await this.set(key, next);
|
|
400
|
+
}
|
|
401
|
+
return next;
|
|
402
|
+
}
|
|
403
|
+
async rateLimit(key, options) {
|
|
404
|
+
const now = Date.now();
|
|
405
|
+
const bucketKey = `__rl__:${key}`;
|
|
406
|
+
const entry = this.store.get(bucketKey);
|
|
407
|
+
const expired = entry === void 0 || entry.expiresAt === void 0 || entry.expiresAt <= now;
|
|
408
|
+
if (expired) {
|
|
409
|
+
const resetAt2 = now + options.windowMs;
|
|
410
|
+
this.store.set(bucketKey, { value: 1, expiresAt: resetAt2 });
|
|
411
|
+
return { allowed: true, remaining: Math.max(0, options.limit - 1), resetAt: resetAt2 };
|
|
412
|
+
}
|
|
413
|
+
const count = entry.value;
|
|
414
|
+
const resetAt = entry.expiresAt ?? now;
|
|
415
|
+
if (count >= options.limit) {
|
|
416
|
+
return { allowed: false, remaining: 0, resetAt };
|
|
417
|
+
}
|
|
418
|
+
this.store.set(bucketKey, { value: count + 1, expiresAt: resetAt });
|
|
419
|
+
return { allowed: true, remaining: Math.max(0, options.limit - count - 1), resetAt };
|
|
420
|
+
}
|
|
421
|
+
async clear() {
|
|
422
|
+
this.store.clear();
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
function createCache() {
|
|
426
|
+
return new MemoryCache();
|
|
427
|
+
}
|
|
428
|
+
var readFileAsync = promisify(readFile);
|
|
429
|
+
function loadConfig(options) {
|
|
430
|
+
const text = readFileSync(options.file, options.encoding ?? "utf8");
|
|
431
|
+
const parser = options.parser ?? JSON.parse;
|
|
432
|
+
const parsed = parser(text);
|
|
433
|
+
return options.schema !== void 0 ? options.schema(parsed) : parsed;
|
|
434
|
+
}
|
|
435
|
+
async function loadConfigAsync(options) {
|
|
436
|
+
const text = await readFileAsync(options.file, options.encoding ?? "utf8");
|
|
437
|
+
const parser = options.parser ?? JSON.parse;
|
|
438
|
+
const parsed = parser(text);
|
|
439
|
+
return options.schema !== void 0 ? options.schema(parsed) : parsed;
|
|
440
|
+
}
|
|
441
|
+
function lookup(table, resourceName = "key") {
|
|
442
|
+
return (key) => {
|
|
443
|
+
const value = table[key];
|
|
444
|
+
if (value === void 0) {
|
|
445
|
+
throw new Error(`spearkit: ${resourceName} "${String(key)}" not found in config`);
|
|
446
|
+
}
|
|
447
|
+
return value;
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
function lookupOptional(table) {
|
|
451
|
+
return (key) => table[key];
|
|
452
|
+
}
|
|
453
|
+
function denied(reason) {
|
|
454
|
+
return { allowed: false, reason };
|
|
455
|
+
}
|
|
456
|
+
async function runGuards(ctx, guards) {
|
|
457
|
+
if (guards === void 0 || guards.length === 0) return { allowed: true };
|
|
458
|
+
for (const guard2 of guards) {
|
|
459
|
+
const result = await guard2(ctx);
|
|
460
|
+
if (result === true) continue;
|
|
461
|
+
if (result === false) return { allowed: false, reason: void 0 };
|
|
462
|
+
if (result.allowed === false) return { allowed: false, reason: result.reason };
|
|
463
|
+
}
|
|
464
|
+
return { allowed: true };
|
|
465
|
+
}
|
|
466
|
+
function guildOnly(reason = "This can only be used in a server.") {
|
|
467
|
+
return (ctx) => ctx.guildId !== null ? true : denied(reason);
|
|
468
|
+
}
|
|
469
|
+
function dmOnly(reason = "This can only be used in DMs.") {
|
|
470
|
+
return (ctx) => ctx.guildId === null ? true : denied(reason);
|
|
471
|
+
}
|
|
472
|
+
function memberRoleIds(member) {
|
|
473
|
+
if (member === null) return [];
|
|
474
|
+
const roles = member.roles;
|
|
475
|
+
if (Array.isArray(roles)) return roles;
|
|
476
|
+
return [...roles.cache.keys()];
|
|
477
|
+
}
|
|
478
|
+
function memberPermissionsBitField(member) {
|
|
479
|
+
if (member === null) return null;
|
|
480
|
+
const perms = member.permissions;
|
|
481
|
+
if (perms instanceof PermissionsBitField) return perms;
|
|
482
|
+
if (typeof perms === "string") return new PermissionsBitField(BigInt(perms));
|
|
483
|
+
return null;
|
|
484
|
+
}
|
|
485
|
+
function requireAnyRole(roleIds, reason = "You don't have permission to use this.") {
|
|
486
|
+
const set = new Set(roleIds);
|
|
487
|
+
return (ctx) => {
|
|
488
|
+
const ids = memberRoleIds(ctx.member);
|
|
489
|
+
return ids.some((id) => set.has(id)) ? true : denied(reason);
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
function requireAllRoles(roleIds, reason = "You're missing one of the required roles.") {
|
|
493
|
+
return (ctx) => {
|
|
494
|
+
const ids = new Set(memberRoleIds(ctx.member));
|
|
495
|
+
return roleIds.every((id) => ids.has(id)) ? true : denied(reason);
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
function requireOwner(ownerIds, reason = "This is owner-only.") {
|
|
499
|
+
const set = new Set(ownerIds);
|
|
500
|
+
return (ctx) => set.has(ctx.user.id) ? true : denied(reason);
|
|
501
|
+
}
|
|
502
|
+
function requireUserPermissions(permission, reason = "You don't have permission to use this.") {
|
|
503
|
+
return (ctx) => {
|
|
504
|
+
const bits = memberPermissionsBitField(ctx.member);
|
|
505
|
+
if (bits === null) return denied(reason);
|
|
506
|
+
return bits.has(permission) ? true : denied(reason);
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
function requireBotPermissions(permission, reason = "I don't have permission to do that here.") {
|
|
510
|
+
return async (ctx) => {
|
|
511
|
+
const guild = ctx.guild;
|
|
512
|
+
if (guild === null) return denied(reason);
|
|
513
|
+
const me = guild.members.me ?? await guild.members.fetchMe().catch(() => null);
|
|
514
|
+
if (me === null) return denied(reason);
|
|
515
|
+
return me.permissions.has(permission) ? true : denied(reason);
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
function guard(predicate) {
|
|
519
|
+
return predicate;
|
|
520
|
+
}
|
|
8
521
|
function withEphemeralFlag(flags) {
|
|
9
522
|
if (flags == null) return MessageFlags.Ephemeral;
|
|
10
523
|
if (typeof flags === "number" || typeof flags === "bigint") {
|
|
@@ -24,86 +537,1647 @@ function normalizeEdit(input) {
|
|
|
24
537
|
const { ephemeral: _ephemeral, flags: _flags, ...rest } = input;
|
|
25
538
|
return rest;
|
|
26
539
|
}
|
|
27
|
-
function asEphemeral(input) {
|
|
28
|
-
if (typeof input === "string") return { content: input, ephemeral: true };
|
|
29
|
-
return { ...input, ephemeral: true };
|
|
540
|
+
function asEphemeral(input) {
|
|
541
|
+
if (typeof input === "string") return { content: input, ephemeral: true };
|
|
542
|
+
return { ...input, ephemeral: true };
|
|
543
|
+
}
|
|
544
|
+
var BaseContext = class {
|
|
545
|
+
constructor(interaction) {
|
|
546
|
+
this.interaction = interaction;
|
|
547
|
+
}
|
|
548
|
+
interaction;
|
|
549
|
+
get client() {
|
|
550
|
+
return this.interaction.client;
|
|
551
|
+
}
|
|
552
|
+
get user() {
|
|
553
|
+
return this.interaction.user;
|
|
554
|
+
}
|
|
555
|
+
get member() {
|
|
556
|
+
return this.interaction.member;
|
|
557
|
+
}
|
|
558
|
+
get guild() {
|
|
559
|
+
return this.interaction.guild;
|
|
560
|
+
}
|
|
561
|
+
get guildId() {
|
|
562
|
+
return this.interaction.guildId;
|
|
563
|
+
}
|
|
564
|
+
get channel() {
|
|
565
|
+
return this.interaction.channel;
|
|
566
|
+
}
|
|
567
|
+
get channelId() {
|
|
568
|
+
return this.interaction.channelId;
|
|
569
|
+
}
|
|
570
|
+
get locale() {
|
|
571
|
+
return this.interaction.locale;
|
|
572
|
+
}
|
|
573
|
+
/** Whether the interaction is already deferred. */
|
|
574
|
+
get deferred() {
|
|
575
|
+
return this.interaction.deferred;
|
|
576
|
+
}
|
|
577
|
+
/** Whether the interaction already received an initial response. */
|
|
578
|
+
get replied() {
|
|
579
|
+
return this.interaction.replied;
|
|
580
|
+
}
|
|
581
|
+
/** Send the initial response to the interaction. */
|
|
582
|
+
reply(input) {
|
|
583
|
+
return this.interaction.reply(normalizeReply(input));
|
|
584
|
+
}
|
|
585
|
+
/** Reply, but always hidden to everyone except the invoking user. */
|
|
586
|
+
replyEphemeral(input) {
|
|
587
|
+
return this.reply(asEphemeral(input));
|
|
588
|
+
}
|
|
589
|
+
/** Acknowledge now and respond later via {@link editReply}. */
|
|
590
|
+
defer(options = {}) {
|
|
591
|
+
return this.interaction.deferReply(
|
|
592
|
+
options.ephemeral ? { flags: MessageFlags.Ephemeral } : {}
|
|
593
|
+
);
|
|
594
|
+
}
|
|
595
|
+
/** Edit the original (or deferred) response. */
|
|
596
|
+
editReply(input) {
|
|
597
|
+
return this.interaction.editReply(normalizeEdit(input));
|
|
598
|
+
}
|
|
599
|
+
/** Add an additional message after the initial response. */
|
|
600
|
+
followUp(input) {
|
|
601
|
+
return this.interaction.followUp(normalizeReply(input));
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* State-aware send: replies, edits a deferred response, or follows up —
|
|
605
|
+
* whichever is valid given the current interaction state. The single method
|
|
606
|
+
* most handlers ever need.
|
|
607
|
+
*/
|
|
608
|
+
async send(input) {
|
|
609
|
+
if (this.interaction.deferred) {
|
|
610
|
+
await this.editReply(input);
|
|
611
|
+
} else if (this.interaction.replied) {
|
|
612
|
+
await this.followUp(input);
|
|
613
|
+
} else {
|
|
614
|
+
await this.reply(input);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
/** Get the configured {@link Embeds} factory — `client.embeds` or the default. */
|
|
618
|
+
getEmbeds() {
|
|
619
|
+
return this.interaction.client.embeds ?? defaultEmbeds;
|
|
620
|
+
}
|
|
621
|
+
/** State-aware send of a red error embed. Defaults to ephemeral. */
|
|
622
|
+
error(input, options = {}) {
|
|
623
|
+
return this.sendPreset("error", input, { ephemeral: options.ephemeral ?? true });
|
|
624
|
+
}
|
|
625
|
+
/** State-aware send of a green success embed. */
|
|
626
|
+
success(input, options = {}) {
|
|
627
|
+
return this.sendPreset("success", input, options);
|
|
628
|
+
}
|
|
629
|
+
/** State-aware send of a blue info embed. */
|
|
630
|
+
info(input, options = {}) {
|
|
631
|
+
return this.sendPreset("info", input, options);
|
|
632
|
+
}
|
|
633
|
+
/** State-aware send of a yellow warn embed. */
|
|
634
|
+
warn(input, options = {}) {
|
|
635
|
+
return this.sendPreset("warn", input, options);
|
|
636
|
+
}
|
|
637
|
+
/** Initial-reply variant of {@link error} (always `reply`, never `editReply`/`followUp`). */
|
|
638
|
+
replyError(input, options = {}) {
|
|
639
|
+
return this.replyPreset("error", input, { ephemeral: options.ephemeral ?? true });
|
|
640
|
+
}
|
|
641
|
+
/** Initial-reply variant of {@link success}. */
|
|
642
|
+
replySuccess(input, options = {}) {
|
|
643
|
+
return this.replyPreset("success", input, options);
|
|
644
|
+
}
|
|
645
|
+
/** Initial-reply variant of {@link info}. */
|
|
646
|
+
replyInfo(input, options = {}) {
|
|
647
|
+
return this.replyPreset("info", input, options);
|
|
648
|
+
}
|
|
649
|
+
/** Initial-reply variant of {@link warn}. */
|
|
650
|
+
replyWarn(input, options = {}) {
|
|
651
|
+
return this.replyPreset("warn", input, options);
|
|
652
|
+
}
|
|
653
|
+
sendPreset(level, input, options) {
|
|
654
|
+
const embed = this.getEmbeds().build(level, input);
|
|
655
|
+
return this.send({ embeds: [embed], ephemeral: options.ephemeral });
|
|
656
|
+
}
|
|
657
|
+
replyPreset(level, input, options) {
|
|
658
|
+
const embed = this.getEmbeds().build(level, input);
|
|
659
|
+
return this.reply({ embeds: [embed], ephemeral: options.ephemeral });
|
|
660
|
+
}
|
|
661
|
+
};
|
|
662
|
+
|
|
663
|
+
// src/cooldown.ts
|
|
664
|
+
function normalizeCooldown(input) {
|
|
665
|
+
return typeof input === "number" ? { duration: input } : input;
|
|
666
|
+
}
|
|
667
|
+
function scopeKey(scope, actor) {
|
|
668
|
+
switch (scope) {
|
|
669
|
+
case "guild":
|
|
670
|
+
return `g:${actor.guildId ?? "dm"}`;
|
|
671
|
+
case "channel":
|
|
672
|
+
return `c:${actor.channelId ?? "dm"}`;
|
|
673
|
+
case "global":
|
|
674
|
+
return "global";
|
|
675
|
+
case "user":
|
|
676
|
+
return `u:${actor.userId}`;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
function effectiveDuration(config, actor) {
|
|
680
|
+
if (config.exempt?.users?.includes(actor.userId) === true) return null;
|
|
681
|
+
if (config.exempt?.roles?.some((roleId) => actor.roleIds.includes(roleId)) === true) return null;
|
|
682
|
+
const userOverride = config.overrides?.users?.[actor.userId];
|
|
683
|
+
if (userOverride !== void 0) return userOverride;
|
|
684
|
+
const roleOverrides = config.overrides?.roles;
|
|
685
|
+
if (roleOverrides !== void 0) {
|
|
686
|
+
let best;
|
|
687
|
+
for (const roleId of actor.roleIds) {
|
|
688
|
+
const candidate = roleOverrides[roleId];
|
|
689
|
+
if (candidate !== void 0) best = best === void 0 ? candidate : Math.min(best, candidate);
|
|
690
|
+
}
|
|
691
|
+
if (best !== void 0) return best;
|
|
692
|
+
}
|
|
693
|
+
return config.duration;
|
|
694
|
+
}
|
|
695
|
+
function keyFor(bucket, config, actor) {
|
|
696
|
+
return `${bucket}|${scopeKey(config.scope ?? "user", actor)}`;
|
|
697
|
+
}
|
|
698
|
+
var CooldownManager = class {
|
|
699
|
+
hits = /* @__PURE__ */ new Map();
|
|
700
|
+
/** Number of tracked buckets. */
|
|
701
|
+
get size() {
|
|
702
|
+
return this.hits.size;
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* Check whether `actor` may use `bucket`, recording the use when allowed.
|
|
706
|
+
* Exempt actors and non-positive durations are always allowed (no record).
|
|
707
|
+
*/
|
|
708
|
+
consume(bucket, input, actor, now = Date.now()) {
|
|
709
|
+
const config = normalizeCooldown(input);
|
|
710
|
+
const duration = effectiveDuration(config, actor);
|
|
711
|
+
if (duration === null || duration <= 0) return { allowed: true };
|
|
712
|
+
const key = keyFor(bucket, config, actor);
|
|
713
|
+
const last = this.hits.get(key);
|
|
714
|
+
if (last !== void 0 && now - last < duration) {
|
|
715
|
+
return { allowed: false, remaining: duration - (now - last) };
|
|
716
|
+
}
|
|
717
|
+
this.hits.set(key, now);
|
|
718
|
+
return { allowed: true };
|
|
719
|
+
}
|
|
720
|
+
/** Like {@link consume} but never records — a read-only check. */
|
|
721
|
+
peek(bucket, input, actor, now = Date.now()) {
|
|
722
|
+
const config = normalizeCooldown(input);
|
|
723
|
+
const duration = effectiveDuration(config, actor);
|
|
724
|
+
if (duration === null || duration <= 0) return { allowed: true };
|
|
725
|
+
const last = this.hits.get(keyFor(bucket, config, actor));
|
|
726
|
+
if (last !== void 0 && now - last < duration) {
|
|
727
|
+
return { allowed: false, remaining: duration - (now - last) };
|
|
728
|
+
}
|
|
729
|
+
return { allowed: true };
|
|
730
|
+
}
|
|
731
|
+
/** Clear a single actor's cooldown for a bucket. Returns whether one existed. */
|
|
732
|
+
reset(bucket, actor, scope = "user") {
|
|
733
|
+
return this.hits.delete(`${bucket}|${scopeKey(scope, actor)}`);
|
|
734
|
+
}
|
|
735
|
+
/** Drop every tracked cooldown. */
|
|
736
|
+
clear() {
|
|
737
|
+
this.hits.clear();
|
|
738
|
+
}
|
|
739
|
+
};
|
|
740
|
+
function formatCooldownMessage(config, remainingMs) {
|
|
741
|
+
if (typeof config.message === "function") return config.message(remainingMs);
|
|
742
|
+
if (typeof config.message === "string") return config.message;
|
|
743
|
+
const seconds = Math.max(1, Math.ceil(remainingMs / 1e3));
|
|
744
|
+
return `You're on cooldown \u2014 try again in ${seconds}s.`;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// src/context-menus.ts
|
|
748
|
+
var UserContextMenuContext = class extends BaseContext {
|
|
749
|
+
/** The user the menu was invoked on. */
|
|
750
|
+
get targetUser() {
|
|
751
|
+
return this.interaction.targetUser;
|
|
752
|
+
}
|
|
753
|
+
/** The member version of the target, if available. */
|
|
754
|
+
get targetMember() {
|
|
755
|
+
return this.interaction.targetMember;
|
|
756
|
+
}
|
|
757
|
+
};
|
|
758
|
+
var MessageContextMenuContext = class extends BaseContext {
|
|
759
|
+
/** The message the menu was invoked on. */
|
|
760
|
+
get targetMessage() {
|
|
761
|
+
return this.interaction.targetMessage;
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
function baseJSON(meta, type) {
|
|
765
|
+
return {
|
|
766
|
+
type,
|
|
767
|
+
name: meta.name,
|
|
768
|
+
name_localizations: meta.nameLocalizations,
|
|
769
|
+
nsfw: meta.nsfw,
|
|
770
|
+
default_member_permissions: meta.defaultMemberPermissions == null ? meta.defaultMemberPermissions : new PermissionsBitField(meta.defaultMemberPermissions).bitfield.toString(),
|
|
771
|
+
contexts: meta.guildOnly ? [InteractionContextType.Guild] : void 0
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
function userCommand(config) {
|
|
775
|
+
const cooldown = config.cooldown !== void 0 ? normalizeCooldown(config.cooldown) : void 0;
|
|
776
|
+
return {
|
|
777
|
+
kind: "userMenu",
|
|
778
|
+
name: config.name,
|
|
779
|
+
cooldown,
|
|
780
|
+
guards: config.guards,
|
|
781
|
+
toJSON: () => baseJSON(config, ApplicationCommandType.User),
|
|
782
|
+
execute: async (interaction) => {
|
|
783
|
+
await config.run(new UserContextMenuContext(interaction));
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
function messageCommand(config) {
|
|
788
|
+
const cooldown = config.cooldown !== void 0 ? normalizeCooldown(config.cooldown) : void 0;
|
|
789
|
+
return {
|
|
790
|
+
kind: "messageMenu",
|
|
791
|
+
name: config.name,
|
|
792
|
+
cooldown,
|
|
793
|
+
guards: config.guards,
|
|
794
|
+
toJSON: () => baseJSON(config, ApplicationCommandType.Message),
|
|
795
|
+
execute: async (interaction) => {
|
|
796
|
+
await config.run(new MessageContextMenuContext(interaction));
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
var ContextMenuRegistry = class {
|
|
801
|
+
users = /* @__PURE__ */ new Map();
|
|
802
|
+
messages = /* @__PURE__ */ new Map();
|
|
803
|
+
logger;
|
|
804
|
+
cooldowns;
|
|
805
|
+
defaultCooldown;
|
|
806
|
+
defaultGuards = [];
|
|
807
|
+
onUsage;
|
|
808
|
+
/** Register one or more context-menu commands. */
|
|
809
|
+
add(...commands) {
|
|
810
|
+
for (const command2 of commands) {
|
|
811
|
+
if (command2.kind === "userMenu") this.users.set(command2.name, command2);
|
|
812
|
+
else this.messages.set(command2.name, command2);
|
|
813
|
+
}
|
|
814
|
+
return this;
|
|
815
|
+
}
|
|
816
|
+
/** Total number of registered context-menu commands. */
|
|
817
|
+
get size() {
|
|
818
|
+
return this.users.size + this.messages.size;
|
|
819
|
+
}
|
|
820
|
+
/** Every registered command, both kinds. */
|
|
821
|
+
all() {
|
|
822
|
+
return [...this.users.values(), ...this.messages.values()];
|
|
823
|
+
}
|
|
824
|
+
/** Serialise every command for the REST `applicationCommands` PUT body. */
|
|
825
|
+
toJSON() {
|
|
826
|
+
return this.all().map((c) => c.toJSON());
|
|
827
|
+
}
|
|
828
|
+
setLogger(logger) {
|
|
829
|
+
this.logger = logger;
|
|
830
|
+
return this;
|
|
831
|
+
}
|
|
832
|
+
setCooldowns(manager, defaultCooldown) {
|
|
833
|
+
this.cooldowns = manager;
|
|
834
|
+
this.defaultCooldown = defaultCooldown;
|
|
835
|
+
return this;
|
|
836
|
+
}
|
|
837
|
+
setDefaultGuards(guards) {
|
|
838
|
+
this.defaultGuards = guards;
|
|
839
|
+
return this;
|
|
840
|
+
}
|
|
841
|
+
setUsageHook(hook) {
|
|
842
|
+
this.onUsage = hook;
|
|
843
|
+
return this;
|
|
844
|
+
}
|
|
845
|
+
/** Dispatch a user-target interaction. */
|
|
846
|
+
async handleUser(interaction) {
|
|
847
|
+
const command2 = this.users.get(interaction.commandName);
|
|
848
|
+
if (command2 === void 0) return;
|
|
849
|
+
await this.dispatch(command2, interaction);
|
|
850
|
+
}
|
|
851
|
+
/** Dispatch a message-target interaction. */
|
|
852
|
+
async handleMessage(interaction) {
|
|
853
|
+
const command2 = this.messages.get(interaction.commandName);
|
|
854
|
+
if (command2 === void 0) return;
|
|
855
|
+
await this.dispatch(command2, interaction);
|
|
856
|
+
}
|
|
857
|
+
async dispatch(command2, interaction) {
|
|
858
|
+
this.logger?.debug("contextMenu", {
|
|
859
|
+
data: { kind: command2.kind, name: command2.name, user: interaction.user.id }
|
|
860
|
+
});
|
|
861
|
+
const cooldown = command2.cooldown ?? this.defaultCooldown;
|
|
862
|
+
if (cooldown !== void 0 && this.cooldowns !== void 0) {
|
|
863
|
+
const result = this.cooldowns.consume(
|
|
864
|
+
`${command2.kind}:${command2.name}`,
|
|
865
|
+
cooldown,
|
|
866
|
+
actorOf(interaction)
|
|
867
|
+
);
|
|
868
|
+
if (!result.allowed) {
|
|
869
|
+
await replyCooldown(interaction, cooldown, result.remaining);
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
const guards = combineGuards(this.defaultGuards, command2.guards);
|
|
874
|
+
if (guards.length > 0) {
|
|
875
|
+
const guardResult = await runGuards(interaction, guards);
|
|
876
|
+
if (!guardResult.allowed) {
|
|
877
|
+
this.logger?.debug("contextMenu denied", {
|
|
878
|
+
data: { name: command2.name, user: interaction.user.id, reason: guardResult.reason ?? "" }
|
|
879
|
+
});
|
|
880
|
+
await replyDenied(interaction, guardResult.reason);
|
|
881
|
+
return;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
const start = Date.now();
|
|
885
|
+
try {
|
|
886
|
+
if (command2.kind === "userMenu") {
|
|
887
|
+
await command2.execute(interaction);
|
|
888
|
+
} else {
|
|
889
|
+
await command2.execute(interaction);
|
|
890
|
+
}
|
|
891
|
+
this.onUsage?.({
|
|
892
|
+
type: "command",
|
|
893
|
+
name: command2.name,
|
|
894
|
+
detail: command2.kind,
|
|
895
|
+
outcome: "success",
|
|
896
|
+
durationMs: Date.now() - start,
|
|
897
|
+
userId: interaction.user.id,
|
|
898
|
+
userTag: interaction.user.tag,
|
|
899
|
+
guildId: interaction.guildId,
|
|
900
|
+
channelId: interaction.channelId,
|
|
901
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
902
|
+
});
|
|
903
|
+
} catch (error) {
|
|
904
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
905
|
+
this.onUsage?.({
|
|
906
|
+
type: "command",
|
|
907
|
+
name: command2.name,
|
|
908
|
+
detail: command2.kind,
|
|
909
|
+
outcome: "error",
|
|
910
|
+
errorMessage: err.message,
|
|
911
|
+
durationMs: Date.now() - start,
|
|
912
|
+
userId: interaction.user.id,
|
|
913
|
+
userTag: interaction.user.tag,
|
|
914
|
+
guildId: interaction.guildId,
|
|
915
|
+
channelId: interaction.channelId,
|
|
916
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
917
|
+
});
|
|
918
|
+
interaction.client.emit("error", err);
|
|
919
|
+
try {
|
|
920
|
+
if (!interaction.replied && !interaction.deferred) {
|
|
921
|
+
await interaction.reply({
|
|
922
|
+
content: "Something went wrong.",
|
|
923
|
+
flags: MessageFlags.Ephemeral
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
} catch {
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
function combineGuards(defaults, own) {
|
|
932
|
+
if (own === void 0 || own.length === 0) return defaults;
|
|
933
|
+
if (defaults.length === 0) return own;
|
|
934
|
+
return [...defaults, ...own];
|
|
935
|
+
}
|
|
936
|
+
function actorOf(interaction) {
|
|
937
|
+
const member = interaction.member;
|
|
938
|
+
let roleIds = [];
|
|
939
|
+
if (member !== null) {
|
|
940
|
+
const roles = member.roles;
|
|
941
|
+
roleIds = Array.isArray(roles) ? roles : [...roles.cache.keys()];
|
|
942
|
+
}
|
|
943
|
+
return {
|
|
944
|
+
userId: interaction.user.id,
|
|
945
|
+
roleIds,
|
|
946
|
+
guildId: interaction.guildId,
|
|
947
|
+
channelId: interaction.channelId
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
function clientEmbeds(client) {
|
|
951
|
+
return client.embeds ?? defaultEmbeds;
|
|
952
|
+
}
|
|
953
|
+
async function replyCooldown(interaction, config, remaining) {
|
|
954
|
+
const content = formatCooldownMessage(config, remaining);
|
|
955
|
+
try {
|
|
956
|
+
if (interaction.deferred) await interaction.editReply({ content });
|
|
957
|
+
else if (interaction.replied) await interaction.followUp({ content, flags: MessageFlags.Ephemeral });
|
|
958
|
+
else await interaction.reply({ content, flags: MessageFlags.Ephemeral });
|
|
959
|
+
} catch {
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
async function replyDenied(interaction, reason) {
|
|
963
|
+
const embeds = clientEmbeds(interaction.client);
|
|
964
|
+
const text = reason ?? "You don't have permission to use this.";
|
|
965
|
+
try {
|
|
966
|
+
const payload = { embeds: [embeds.error(text)], flags: MessageFlags.Ephemeral };
|
|
967
|
+
if (interaction.deferred) await interaction.editReply({ embeds: payload.embeds });
|
|
968
|
+
else if (interaction.replied) await interaction.followUp(payload);
|
|
969
|
+
else await interaction.reply(payload);
|
|
970
|
+
} catch {
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
// src/prefix-args.ts
|
|
975
|
+
var SNOWFLAKE_RE = /^\d{15,21}$/;
|
|
976
|
+
var USER_MENTION_RE = /^<@!?(\d{15,21})>$/;
|
|
977
|
+
var CHANNEL_MENTION_RE = /^<#(\d{15,21})>$/;
|
|
978
|
+
var ROLE_MENTION_RE = /^<@&(\d{15,21})>$/;
|
|
979
|
+
function extractSnowflake(input) {
|
|
980
|
+
if (SNOWFLAKE_RE.test(input)) return input;
|
|
981
|
+
const m = USER_MENTION_RE.exec(input) ?? CHANNEL_MENTION_RE.exec(input) ?? ROLE_MENTION_RE.exec(input);
|
|
982
|
+
return m === null ? null : m[1] ?? null;
|
|
983
|
+
}
|
|
984
|
+
var PrefixArgsBuilder = class _PrefixArgsBuilder {
|
|
985
|
+
specs;
|
|
986
|
+
/** @internal */
|
|
987
|
+
constructor(specs = []) {
|
|
988
|
+
this.specs = specs;
|
|
989
|
+
}
|
|
990
|
+
/** A raw string token. */
|
|
991
|
+
string(name, options) {
|
|
992
|
+
return this.push({ name, kind: "string", required: options?.required ?? false, defaultValue: options?.default });
|
|
993
|
+
}
|
|
994
|
+
/** A whole integer. */
|
|
995
|
+
integer(name, options) {
|
|
996
|
+
return this.push({ name, kind: "integer", required: options?.required ?? false, defaultValue: options?.default });
|
|
997
|
+
}
|
|
998
|
+
/** A floating-point number. */
|
|
999
|
+
number(name, options) {
|
|
1000
|
+
return this.push({ name, kind: "number", required: options?.required ?? false, defaultValue: options?.default });
|
|
1001
|
+
}
|
|
1002
|
+
/** A boolean (`true`/`yes`/`1`/`on` vs `false`/`no`/`0`/`off`). */
|
|
1003
|
+
boolean(name, options) {
|
|
1004
|
+
return this.push({ name, kind: "boolean", required: options?.required ?? false, defaultValue: options?.default });
|
|
1005
|
+
}
|
|
1006
|
+
/** A Discord snowflake id — accepts raw ids and `<@u>` / `<#c>` / `<@&r>` mentions. */
|
|
1007
|
+
snowflake(name, options) {
|
|
1008
|
+
return this.push({ name, kind: "snowflake", required: options?.required ?? false, defaultValue: options?.default });
|
|
1009
|
+
}
|
|
1010
|
+
/** A duration like `"1h30m"` or `"1 saat"` parsed to milliseconds. */
|
|
1011
|
+
duration(name, options) {
|
|
1012
|
+
return this.push({ name, kind: "duration", required: options?.required ?? false, defaultValue: options?.default });
|
|
1013
|
+
}
|
|
1014
|
+
/** The remainder of the message (everything after previous args). */
|
|
1015
|
+
rest(name, options) {
|
|
1016
|
+
return this.push({ name, kind: "rest", required: options?.required ?? false, defaultValue: options?.default });
|
|
1017
|
+
}
|
|
1018
|
+
push(spec) {
|
|
1019
|
+
return new _PrefixArgsBuilder([...this.specs, spec]);
|
|
1020
|
+
}
|
|
1021
|
+
/** Compile this builder into a parser. */
|
|
1022
|
+
compile() {
|
|
1023
|
+
const specs = this.specs;
|
|
1024
|
+
return {
|
|
1025
|
+
specs,
|
|
1026
|
+
parse(tokens, rest) {
|
|
1027
|
+
const out = {};
|
|
1028
|
+
let idx = 0;
|
|
1029
|
+
for (let i = 0; i < specs.length; i++) {
|
|
1030
|
+
const spec = specs[i];
|
|
1031
|
+
if (spec.kind === "rest") {
|
|
1032
|
+
const tail = idx === 0 ? rest : tokens.slice(idx).join(" ");
|
|
1033
|
+
if (tail.length === 0) {
|
|
1034
|
+
if (spec.required) return { ok: false, arg: spec.name, reason: `missing required argument "${spec.name}"` };
|
|
1035
|
+
out[spec.name] = spec.defaultValue;
|
|
1036
|
+
} else {
|
|
1037
|
+
out[spec.name] = tail;
|
|
1038
|
+
}
|
|
1039
|
+
idx = tokens.length;
|
|
1040
|
+
continue;
|
|
1041
|
+
}
|
|
1042
|
+
const token = tokens[idx];
|
|
1043
|
+
if (token === void 0) {
|
|
1044
|
+
if (spec.required) {
|
|
1045
|
+
return { ok: false, arg: spec.name, reason: `missing required argument "${spec.name}"` };
|
|
1046
|
+
}
|
|
1047
|
+
out[spec.name] = spec.defaultValue;
|
|
1048
|
+
continue;
|
|
1049
|
+
}
|
|
1050
|
+
const parsed = coerce(spec, token);
|
|
1051
|
+
if (parsed.ok === false) return { ok: false, arg: spec.name, reason: parsed.reason };
|
|
1052
|
+
out[spec.name] = parsed.value;
|
|
1053
|
+
idx += 1;
|
|
1054
|
+
}
|
|
1055
|
+
return { ok: true, values: out };
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
function coerce(spec, token) {
|
|
1061
|
+
switch (spec.kind) {
|
|
1062
|
+
case "string":
|
|
1063
|
+
return { ok: true, value: token };
|
|
1064
|
+
case "integer": {
|
|
1065
|
+
const n = Number(token);
|
|
1066
|
+
if (!Number.isInteger(n)) return { ok: false, reason: `"${token}" is not an integer` };
|
|
1067
|
+
return { ok: true, value: n };
|
|
1068
|
+
}
|
|
1069
|
+
case "number": {
|
|
1070
|
+
const n = Number(token);
|
|
1071
|
+
if (!Number.isFinite(n)) return { ok: false, reason: `"${token}" is not a number` };
|
|
1072
|
+
return { ok: true, value: n };
|
|
1073
|
+
}
|
|
1074
|
+
case "boolean": {
|
|
1075
|
+
const low = token.toLowerCase();
|
|
1076
|
+
if (["true", "1", "yes", "on"].includes(low)) return { ok: true, value: true };
|
|
1077
|
+
if (["false", "0", "no", "off"].includes(low)) return { ok: true, value: false };
|
|
1078
|
+
return { ok: false, reason: `"${token}" is not a boolean` };
|
|
1079
|
+
}
|
|
1080
|
+
case "snowflake": {
|
|
1081
|
+
const id = extractSnowflake(token);
|
|
1082
|
+
if (id === null) return { ok: false, reason: `"${token}" is not a snowflake or mention` };
|
|
1083
|
+
return { ok: true, value: id };
|
|
1084
|
+
}
|
|
1085
|
+
case "duration": {
|
|
1086
|
+
const ms = parseDuration(token);
|
|
1087
|
+
if (ms === null) return { ok: false, reason: `"${token}" is not a duration` };
|
|
1088
|
+
return { ok: true, value: ms };
|
|
1089
|
+
}
|
|
1090
|
+
default:
|
|
1091
|
+
return { ok: false, reason: `unknown arg kind for "${spec.name}"` };
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
function prefixArgs() {
|
|
1095
|
+
return new PrefixArgsBuilder();
|
|
1096
|
+
}
|
|
1097
|
+
function normalisePayload(render) {
|
|
1098
|
+
if (typeof render.setColor === "function" && typeof render.toJSON === "function") {
|
|
1099
|
+
return { embeds: [render] };
|
|
1100
|
+
}
|
|
1101
|
+
if (Array.isArray(render)) {
|
|
1102
|
+
return { embeds: render };
|
|
1103
|
+
}
|
|
1104
|
+
return render;
|
|
1105
|
+
}
|
|
1106
|
+
function controlsRow(page, pages, ns, controls, labels) {
|
|
1107
|
+
const buttons = [];
|
|
1108
|
+
if (controls === "first-prev-next-last") {
|
|
1109
|
+
buttons.push(
|
|
1110
|
+
new ButtonBuilder().setCustomId(`${ns}:first`).setStyle(ButtonStyle.Secondary).setLabel(labels.first).setDisabled(page === 0)
|
|
1111
|
+
);
|
|
1112
|
+
}
|
|
1113
|
+
buttons.push(
|
|
1114
|
+
new ButtonBuilder().setCustomId(`${ns}:prev`).setStyle(ButtonStyle.Primary).setLabel(labels.prev).setDisabled(page === 0),
|
|
1115
|
+
new ButtonBuilder().setCustomId(`${ns}:next`).setStyle(ButtonStyle.Primary).setLabel(labels.next).setDisabled(page >= pages - 1)
|
|
1116
|
+
);
|
|
1117
|
+
if (controls === "first-prev-next-last") {
|
|
1118
|
+
buttons.push(
|
|
1119
|
+
new ButtonBuilder().setCustomId(`${ns}:last`).setStyle(ButtonStyle.Secondary).setLabel(labels.last).setDisabled(page >= pages - 1)
|
|
1120
|
+
);
|
|
1121
|
+
}
|
|
1122
|
+
return new ActionRowBuilder().addComponents(...buttons);
|
|
1123
|
+
}
|
|
1124
|
+
function resolveLabels2(input) {
|
|
1125
|
+
return {
|
|
1126
|
+
first: input?.first ?? "\xAB",
|
|
1127
|
+
prev: input?.prev ?? "\u2039",
|
|
1128
|
+
next: input?.next ?? "\u203A",
|
|
1129
|
+
last: input?.last ?? "\xBB"
|
|
1130
|
+
};
|
|
1131
|
+
}
|
|
1132
|
+
async function buildPaginatorPage(items, page, options) {
|
|
1133
|
+
const pageSize = options.pageSize ?? 10;
|
|
1134
|
+
const pages = Math.max(1, Math.ceil(items.length / pageSize));
|
|
1135
|
+
const ns = options.namespace ?? "spk-page";
|
|
1136
|
+
const controls = options.controls ?? "prev-next";
|
|
1137
|
+
const labels = resolveLabels2(options.labels);
|
|
1138
|
+
const slice = items.slice(page * pageSize, page * pageSize + pageSize);
|
|
1139
|
+
const body = await options.render(slice, { page, pages });
|
|
1140
|
+
const payload = normalisePayload(body);
|
|
1141
|
+
const components = pages > 1 ? [controlsRow(page, pages, ns, controls, labels)] : [];
|
|
1142
|
+
return { payload: { ...payload, components }, pages };
|
|
1143
|
+
}
|
|
1144
|
+
async function paginate(interaction, items, options) {
|
|
1145
|
+
const pageSize = options.pageSize ?? 10;
|
|
1146
|
+
const ns = options.namespace ?? "spk-page";
|
|
1147
|
+
const controls = options.controls ?? "prev-next";
|
|
1148
|
+
const labels = resolveLabels2(options.labels);
|
|
1149
|
+
const allowedUser = options.user ?? interaction.user.id;
|
|
1150
|
+
let page = 0;
|
|
1151
|
+
const buildPage = async () => {
|
|
1152
|
+
return buildPaginatorPage(items, page, { ...options, pageSize, namespace: ns, controls, labels });
|
|
1153
|
+
};
|
|
1154
|
+
const { payload: initial, pages } = await buildPage();
|
|
1155
|
+
const sent = interaction.deferred ? await interaction.editReply(initial) : (await interaction.reply({
|
|
1156
|
+
...initial,
|
|
1157
|
+
flags: options.ephemeral === true ? 64 : void 0
|
|
1158
|
+
}), await interaction.fetchReply());
|
|
1159
|
+
if (pages <= 1) return;
|
|
1160
|
+
const collector = sent.createMessageComponentCollector({
|
|
1161
|
+
componentType: ComponentType.Button,
|
|
1162
|
+
time: options.timeoutMs ?? 5 * 6e4,
|
|
1163
|
+
filter: (i) => i.user.id === allowedUser && i.customId.startsWith(`${ns}:`)
|
|
1164
|
+
});
|
|
1165
|
+
collector.on("collect", async (button2) => {
|
|
1166
|
+
const action = button2.customId.slice(ns.length + 1);
|
|
1167
|
+
if (action === "first") page = 0;
|
|
1168
|
+
else if (action === "prev") page = Math.max(0, page - 1);
|
|
1169
|
+
else if (action === "next") page = Math.min(pages - 1, page + 1);
|
|
1170
|
+
else if (action === "last") page = pages - 1;
|
|
1171
|
+
const next = await buildPage();
|
|
1172
|
+
await button2.update(next.payload).catch(() => void 0);
|
|
1173
|
+
});
|
|
1174
|
+
collector.on("end", async () => {
|
|
1175
|
+
const disabledRow = controlsRow(page, pages, ns, controls, labels);
|
|
1176
|
+
for (const c of disabledRow.components) c.setDisabled(true);
|
|
1177
|
+
const { payload: final } = await buildPage();
|
|
1178
|
+
await interaction.editReply({ ...final, components: [disabledRow] }).catch(() => void 0);
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
var STYLE_MAP = {
|
|
1182
|
+
Primary: ButtonStyle.Primary,
|
|
1183
|
+
Secondary: ButtonStyle.Secondary,
|
|
1184
|
+
Success: ButtonStyle.Success,
|
|
1185
|
+
Danger: ButtonStyle.Danger
|
|
1186
|
+
};
|
|
1187
|
+
function clientEmbeds2(client) {
|
|
1188
|
+
return client.embeds ?? defaultEmbeds;
|
|
1189
|
+
}
|
|
1190
|
+
async function confirm(interaction, options) {
|
|
1191
|
+
const ns = options.namespace ?? "spk-confirm";
|
|
1192
|
+
const confirmLabel = options.confirm?.label ?? "Confirm";
|
|
1193
|
+
const cancelLabel = options.cancel?.label ?? "Cancel";
|
|
1194
|
+
const confirmStyle = STYLE_MAP[options.confirm?.style ?? "Success"];
|
|
1195
|
+
const cancelStyle = STYLE_MAP[options.cancel?.style ?? "Secondary"];
|
|
1196
|
+
const user = options.user ?? interaction.user.id;
|
|
1197
|
+
const ephemeral = options.ephemeral !== false;
|
|
1198
|
+
const embeds = clientEmbeds2(interaction.client);
|
|
1199
|
+
const promptEmbed = embeds.info(
|
|
1200
|
+
options.title !== void 0 ? { title: options.title, description: options.body } : options.body
|
|
1201
|
+
);
|
|
1202
|
+
const row2 = new ActionRowBuilder().addComponents(
|
|
1203
|
+
new ButtonBuilder().setCustomId(`${ns}:yes`).setLabel(confirmLabel).setStyle(confirmStyle),
|
|
1204
|
+
new ButtonBuilder().setCustomId(`${ns}:no`).setLabel(cancelLabel).setStyle(cancelStyle)
|
|
1205
|
+
);
|
|
1206
|
+
const payload = { embeds: [promptEmbed], components: [row2] };
|
|
1207
|
+
const sent = interaction.deferred ? await interaction.editReply(payload) : (await interaction.reply({
|
|
1208
|
+
...payload,
|
|
1209
|
+
flags: ephemeral ? 64 : void 0
|
|
1210
|
+
}), await interaction.fetchReply());
|
|
1211
|
+
return new Promise((resolve) => {
|
|
1212
|
+
const collector = sent.createMessageComponentCollector({
|
|
1213
|
+
componentType: ComponentType.Button,
|
|
1214
|
+
time: options.timeoutMs ?? 3e4,
|
|
1215
|
+
max: 1,
|
|
1216
|
+
filter: (i) => i.user.id === user && i.customId.startsWith(`${ns}:`)
|
|
1217
|
+
});
|
|
1218
|
+
let outcome = null;
|
|
1219
|
+
collector.on("collect", async (button2) => {
|
|
1220
|
+
const action = button2.customId.slice(ns.length + 1);
|
|
1221
|
+
outcome = {
|
|
1222
|
+
confirmed: action === "yes",
|
|
1223
|
+
reason: action === "yes" ? "confirm" : "cancel",
|
|
1224
|
+
interaction: button2
|
|
1225
|
+
};
|
|
1226
|
+
await button2.deferUpdate().catch(() => void 0);
|
|
1227
|
+
});
|
|
1228
|
+
collector.on("end", async () => {
|
|
1229
|
+
for (const c of row2.components) c.setDisabled(true);
|
|
1230
|
+
await interaction.editReply({ embeds: [promptEmbed], components: [row2] }).catch(() => void 0);
|
|
1231
|
+
resolve(outcome ?? { confirmed: false, reason: "timeout" });
|
|
1232
|
+
});
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
var RANK = {
|
|
1236
|
+
debug: 10,
|
|
1237
|
+
info: 20,
|
|
1238
|
+
warn: 30,
|
|
1239
|
+
error: 40,
|
|
1240
|
+
silent: Number.POSITIVE_INFINITY
|
|
1241
|
+
};
|
|
1242
|
+
function formatValue(value) {
|
|
1243
|
+
return typeof value === "string" ? value : String(value);
|
|
1244
|
+
}
|
|
1245
|
+
function consoleSink(entry) {
|
|
1246
|
+
const scope = entry.scope !== void 0 ? ` [${entry.scope}]` : "";
|
|
1247
|
+
let suffix = "";
|
|
1248
|
+
if (entry.data !== void 0) {
|
|
1249
|
+
const parts = Object.entries(entry.data).map(([k, v]) => `${k}=${formatValue(v)}`);
|
|
1250
|
+
if (parts.length > 0) suffix = ` ${parts.join(" ")}`;
|
|
1251
|
+
}
|
|
1252
|
+
const line = `${entry.timestamp.toISOString()} ${entry.level.toUpperCase()}${scope} ${entry.message}${suffix}`;
|
|
1253
|
+
const write = entry.level === "warn" || entry.level === "error" ? console.error : console.log;
|
|
1254
|
+
write(line);
|
|
1255
|
+
if (entry.error !== void 0) write(entry.error.stack ?? String(entry.error));
|
|
1256
|
+
}
|
|
1257
|
+
function jsonlSink(path, options = {}) {
|
|
1258
|
+
const min = options.minLevel ?? "debug";
|
|
1259
|
+
let dirReady = false;
|
|
1260
|
+
let chain = Promise.resolve();
|
|
1261
|
+
return (entry) => {
|
|
1262
|
+
if (RANK[entry.level] < RANK[min]) return;
|
|
1263
|
+
const record = {
|
|
1264
|
+
...entry,
|
|
1265
|
+
timestamp: entry.timestamp.toISOString(),
|
|
1266
|
+
error: entry.error ? { name: entry.error.name, message: entry.error.message, stack: entry.error.stack } : void 0
|
|
1267
|
+
};
|
|
1268
|
+
const line = `${JSON.stringify(record)}
|
|
1269
|
+
`;
|
|
1270
|
+
chain = chain.then(async () => {
|
|
1271
|
+
try {
|
|
1272
|
+
if (!dirReady) {
|
|
1273
|
+
await mkdir(dirname(path), { recursive: true });
|
|
1274
|
+
dirReady = true;
|
|
1275
|
+
}
|
|
1276
|
+
await appendFile(path, line, "utf8");
|
|
1277
|
+
} catch {
|
|
1278
|
+
}
|
|
1279
|
+
});
|
|
1280
|
+
};
|
|
1281
|
+
}
|
|
1282
|
+
function webhookSink(options) {
|
|
1283
|
+
const min = options.minLevel ?? "warn";
|
|
1284
|
+
return (entry) => {
|
|
1285
|
+
if (RANK[entry.level] < RANK[min]) return;
|
|
1286
|
+
const color = entry.level === "error" ? 15747655 : entry.level === "warn" ? 16361509 : 3447003;
|
|
1287
|
+
const fields = [];
|
|
1288
|
+
if (entry.scope !== void 0) fields.push({ name: "Scope", value: entry.scope, inline: true });
|
|
1289
|
+
if (entry.data !== void 0) {
|
|
1290
|
+
for (const [k, v] of Object.entries(entry.data)) {
|
|
1291
|
+
fields.push({ name: k, value: formatValue(v).slice(0, 1e3), inline: true });
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
const desc = entry.error?.stack !== void 0 ? `${entry.message}
|
|
1295
|
+
\`\`\`
|
|
1296
|
+
${entry.error.stack.slice(0, 1800)}
|
|
1297
|
+
\`\`\`` : entry.message;
|
|
1298
|
+
const body = {
|
|
1299
|
+
username: options.username ?? "spearkit",
|
|
1300
|
+
embeds: [
|
|
1301
|
+
{
|
|
1302
|
+
title: `[${entry.level.toUpperCase()}] ${entry.message.slice(0, 240)}`,
|
|
1303
|
+
description: desc.slice(0, 4e3),
|
|
1304
|
+
color,
|
|
1305
|
+
timestamp: entry.timestamp.toISOString(),
|
|
1306
|
+
fields: fields.slice(0, 25)
|
|
1307
|
+
}
|
|
1308
|
+
]
|
|
1309
|
+
};
|
|
1310
|
+
void fetch(options.url, {
|
|
1311
|
+
method: "POST",
|
|
1312
|
+
headers: { "content-type": "application/json" },
|
|
1313
|
+
body: JSON.stringify(body)
|
|
1314
|
+
}).catch(() => void 0);
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
function resolveTransports(options) {
|
|
1318
|
+
if (options.transports !== void 0 && options.transports.length > 0) return options.transports;
|
|
1319
|
+
if (options.sink !== void 0) return [options.sink];
|
|
1320
|
+
return [consoleSink];
|
|
1321
|
+
}
|
|
1322
|
+
var Logger = class _Logger {
|
|
1323
|
+
state;
|
|
1324
|
+
/** The scope prefix applied to every entry, if any. */
|
|
1325
|
+
scope;
|
|
1326
|
+
constructor(options = {}) {
|
|
1327
|
+
this.state = {
|
|
1328
|
+
threshold: options.level ?? "info",
|
|
1329
|
+
transports: resolveTransports(options)
|
|
1330
|
+
};
|
|
1331
|
+
this.scope = options.scope;
|
|
1332
|
+
}
|
|
1333
|
+
/** The current minimum threshold. */
|
|
1334
|
+
get level() {
|
|
1335
|
+
return this.state.threshold;
|
|
1336
|
+
}
|
|
1337
|
+
/** Change the threshold for this logger and every child sharing its state. */
|
|
1338
|
+
setLevel(level) {
|
|
1339
|
+
this.state.threshold = level;
|
|
1340
|
+
return this;
|
|
1341
|
+
}
|
|
1342
|
+
/** Replace the transport list for this logger and every child sharing its state. */
|
|
1343
|
+
setTransports(transports) {
|
|
1344
|
+
this.state.transports = transports;
|
|
1345
|
+
return this;
|
|
1346
|
+
}
|
|
1347
|
+
/** Append a transport to the existing list. */
|
|
1348
|
+
addTransport(sink) {
|
|
1349
|
+
this.state.transports = [...this.state.transports, sink];
|
|
1350
|
+
return this;
|
|
1351
|
+
}
|
|
1352
|
+
/** Whether an entry of `level` would currently be emitted. */
|
|
1353
|
+
enabled(level) {
|
|
1354
|
+
return RANK[level] >= RANK[this.state.threshold];
|
|
1355
|
+
}
|
|
1356
|
+
/** A child logger with an extra scope segment, sharing this logger's state. */
|
|
1357
|
+
child(scope) {
|
|
1358
|
+
const combined = this.scope !== void 0 ? `${this.scope}:${scope}` : scope;
|
|
1359
|
+
const child = new _Logger({ scope: combined });
|
|
1360
|
+
child.state = this.state;
|
|
1361
|
+
return child;
|
|
1362
|
+
}
|
|
1363
|
+
/** Emit an entry at an explicit level. */
|
|
1364
|
+
log(level, message, options) {
|
|
1365
|
+
if (!this.enabled(level)) return;
|
|
1366
|
+
const entry = {
|
|
1367
|
+
level,
|
|
1368
|
+
message,
|
|
1369
|
+
scope: this.scope,
|
|
1370
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
1371
|
+
error: options?.error,
|
|
1372
|
+
data: options?.data
|
|
1373
|
+
};
|
|
1374
|
+
for (const sink of this.state.transports) {
|
|
1375
|
+
try {
|
|
1376
|
+
sink(entry);
|
|
1377
|
+
} catch {
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
/** Verbose diagnostics, off by default. */
|
|
1382
|
+
debug(message, options) {
|
|
1383
|
+
this.log("debug", message, options);
|
|
1384
|
+
}
|
|
1385
|
+
/** Normal operational messages. */
|
|
1386
|
+
info(message, options) {
|
|
1387
|
+
this.log("info", message, options);
|
|
1388
|
+
}
|
|
1389
|
+
/** Recoverable problems worth attention. */
|
|
1390
|
+
warn(message, options) {
|
|
1391
|
+
this.log("warn", message, options);
|
|
1392
|
+
}
|
|
1393
|
+
/** Failures. Attach the cause via `{ error }`. */
|
|
1394
|
+
error(message, options) {
|
|
1395
|
+
this.log("error", message, options);
|
|
1396
|
+
}
|
|
1397
|
+
};
|
|
1398
|
+
function toError(value) {
|
|
1399
|
+
return value instanceof Error ? value : new Error(String(value));
|
|
1400
|
+
}
|
|
1401
|
+
function stripInlineComment(value) {
|
|
1402
|
+
const match = /\s#/.exec(value);
|
|
1403
|
+
return match !== null ? value.slice(0, match.index).trimEnd() : value;
|
|
1404
|
+
}
|
|
1405
|
+
function unquote(raw) {
|
|
1406
|
+
if (raw.length >= 2) {
|
|
1407
|
+
const quote = raw[0];
|
|
1408
|
+
if ((quote === '"' || quote === "'") && raw.endsWith(quote)) {
|
|
1409
|
+
const inner = raw.slice(1, -1);
|
|
1410
|
+
return quote === '"' ? inner.replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, " ") : inner;
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
return stripInlineComment(raw);
|
|
1414
|
+
}
|
|
1415
|
+
function parseEnv(content) {
|
|
1416
|
+
const out = {};
|
|
1417
|
+
for (const rawLine of content.split(/\r?\n/)) {
|
|
1418
|
+
const line = rawLine.trim();
|
|
1419
|
+
if (line.length === 0 || line.startsWith("#")) continue;
|
|
1420
|
+
const body = line.startsWith("export ") ? line.slice(7).trimStart() : line;
|
|
1421
|
+
const eq = body.indexOf("=");
|
|
1422
|
+
if (eq <= 0) continue;
|
|
1423
|
+
const key = body.slice(0, eq).trim();
|
|
1424
|
+
if (key.length === 0) continue;
|
|
1425
|
+
out[key] = unquote(body.slice(eq + 1).trim());
|
|
1426
|
+
}
|
|
1427
|
+
return out;
|
|
1428
|
+
}
|
|
1429
|
+
function loadEnv(options = {}) {
|
|
1430
|
+
const path = options.path ?? join(process.cwd(), ".env");
|
|
1431
|
+
let content;
|
|
1432
|
+
try {
|
|
1433
|
+
content = readFileSync(path, "utf8");
|
|
1434
|
+
} catch {
|
|
1435
|
+
return {};
|
|
1436
|
+
}
|
|
1437
|
+
const parsed = parseEnv(content);
|
|
1438
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
1439
|
+
if (options.override === true || process.env[key] === void 0) {
|
|
1440
|
+
process.env[key] = value;
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
return parsed;
|
|
1444
|
+
}
|
|
1445
|
+
var TRUTHY = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
|
|
1446
|
+
var FALSY = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
|
|
1447
|
+
function read(key) {
|
|
1448
|
+
const value = process.env[key];
|
|
1449
|
+
return value !== void 0 && value !== "" ? value : void 0;
|
|
1450
|
+
}
|
|
1451
|
+
function envString(key, fallback) {
|
|
1452
|
+
return read(key) ?? fallback;
|
|
1453
|
+
}
|
|
1454
|
+
function envNumber(key, fallback) {
|
|
1455
|
+
const value = read(key);
|
|
1456
|
+
if (value === void 0) return fallback;
|
|
1457
|
+
const parsed = Number(value);
|
|
1458
|
+
return Number.isNaN(parsed) ? fallback : parsed;
|
|
1459
|
+
}
|
|
1460
|
+
function envBoolean(key, fallback) {
|
|
1461
|
+
const value = read(key)?.toLowerCase();
|
|
1462
|
+
if (value === void 0) return fallback;
|
|
1463
|
+
if (TRUTHY.has(value)) return true;
|
|
1464
|
+
if (FALSY.has(value)) return false;
|
|
1465
|
+
return fallback;
|
|
1466
|
+
}
|
|
1467
|
+
function envRequire(key) {
|
|
1468
|
+
const value = read(key);
|
|
1469
|
+
if (value === void 0) {
|
|
1470
|
+
throw new Error(`spearkit: required environment variable "${key}" is missing or empty`);
|
|
1471
|
+
}
|
|
1472
|
+
return value;
|
|
1473
|
+
}
|
|
1474
|
+
var env = {
|
|
1475
|
+
string: envString,
|
|
1476
|
+
number: envNumber,
|
|
1477
|
+
boolean: envBoolean,
|
|
1478
|
+
require: envRequire
|
|
1479
|
+
};
|
|
1480
|
+
|
|
1481
|
+
// src/scheduler.ts
|
|
1482
|
+
var ALIASES = {
|
|
1483
|
+
"@yearly": "0 0 1 1 *",
|
|
1484
|
+
"@annually": "0 0 1 1 *",
|
|
1485
|
+
"@monthly": "0 0 1 * *",
|
|
1486
|
+
"@weekly": "0 0 * * 0",
|
|
1487
|
+
"@daily": "0 0 * * *",
|
|
1488
|
+
"@midnight": "0 0 * * *",
|
|
1489
|
+
"@hourly": "0 * * * *"
|
|
1490
|
+
};
|
|
1491
|
+
function parseField(spec, min, max, label) {
|
|
1492
|
+
const set = /* @__PURE__ */ new Set();
|
|
1493
|
+
for (const part of spec.split(",")) {
|
|
1494
|
+
let range = part;
|
|
1495
|
+
let step = 1;
|
|
1496
|
+
const slash = part.indexOf("/");
|
|
1497
|
+
if (slash >= 0) {
|
|
1498
|
+
step = Number(part.slice(slash + 1));
|
|
1499
|
+
range = part.slice(0, slash);
|
|
1500
|
+
if (!Number.isInteger(step) || step <= 0) {
|
|
1501
|
+
throw new Error(`spearkit: invalid step in cron ${label} field "${part}"`);
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
let lo;
|
|
1505
|
+
let hi;
|
|
1506
|
+
if (range === "*") {
|
|
1507
|
+
lo = min;
|
|
1508
|
+
hi = max;
|
|
1509
|
+
} else if (range.includes("-")) {
|
|
1510
|
+
const dash = range.indexOf("-");
|
|
1511
|
+
lo = Number(range.slice(0, dash));
|
|
1512
|
+
hi = Number(range.slice(dash + 1));
|
|
1513
|
+
} else {
|
|
1514
|
+
lo = Number(range);
|
|
1515
|
+
hi = lo;
|
|
1516
|
+
}
|
|
1517
|
+
if (!Number.isInteger(lo) || !Number.isInteger(hi) || lo < min || hi > max || lo > hi) {
|
|
1518
|
+
throw new Error(`spearkit: cron ${label} field out of range ${min}-${max}: "${part}"`);
|
|
1519
|
+
}
|
|
1520
|
+
for (let value = lo; value <= hi; value += step) set.add(value);
|
|
1521
|
+
}
|
|
1522
|
+
return set;
|
|
1523
|
+
}
|
|
1524
|
+
var CronExpression = class {
|
|
1525
|
+
/** The original expression string. */
|
|
1526
|
+
source;
|
|
1527
|
+
minutes;
|
|
1528
|
+
hours;
|
|
1529
|
+
daysOfMonth;
|
|
1530
|
+
months;
|
|
1531
|
+
daysOfWeek;
|
|
1532
|
+
domRestricted;
|
|
1533
|
+
dowRestricted;
|
|
1534
|
+
constructor(expression) {
|
|
1535
|
+
const trimmed = expression.trim();
|
|
1536
|
+
const normalized = ALIASES[trimmed] ?? trimmed;
|
|
1537
|
+
const parts = normalized.split(/\s+/);
|
|
1538
|
+
if (parts.length !== 5) {
|
|
1539
|
+
throw new Error(`spearkit: cron expression must have 5 fields, got "${expression}"`);
|
|
1540
|
+
}
|
|
1541
|
+
const [minute, hour, dom, month, dow] = parts;
|
|
1542
|
+
if (minute === void 0 || hour === void 0 || dom === void 0 || month === void 0 || dow === void 0) {
|
|
1543
|
+
throw new Error(`spearkit: invalid cron expression "${expression}"`);
|
|
1544
|
+
}
|
|
1545
|
+
this.source = expression;
|
|
1546
|
+
this.minutes = parseField(minute, 0, 59, "minute");
|
|
1547
|
+
this.hours = parseField(hour, 0, 23, "hour");
|
|
1548
|
+
this.daysOfMonth = parseField(dom, 1, 31, "day-of-month");
|
|
1549
|
+
this.months = parseField(month, 1, 12, "month");
|
|
1550
|
+
const weekdays = parseField(dow, 0, 7, "day-of-week");
|
|
1551
|
+
if (weekdays.has(7)) {
|
|
1552
|
+
weekdays.delete(7);
|
|
1553
|
+
weekdays.add(0);
|
|
1554
|
+
}
|
|
1555
|
+
this.daysOfWeek = weekdays;
|
|
1556
|
+
this.domRestricted = dom !== "*";
|
|
1557
|
+
this.dowRestricted = dow !== "*";
|
|
1558
|
+
}
|
|
1559
|
+
dayMatches(date) {
|
|
1560
|
+
const dom = this.daysOfMonth.has(date.getDate());
|
|
1561
|
+
const dow = this.daysOfWeek.has(date.getDay());
|
|
1562
|
+
if (this.domRestricted && this.dowRestricted) return dom || dow;
|
|
1563
|
+
if (this.domRestricted) return dom;
|
|
1564
|
+
if (this.dowRestricted) return dow;
|
|
1565
|
+
return true;
|
|
1566
|
+
}
|
|
1567
|
+
/** The next time strictly after `from` (default now) that matches. */
|
|
1568
|
+
next(from = /* @__PURE__ */ new Date()) {
|
|
1569
|
+
const date = new Date(from.getTime());
|
|
1570
|
+
date.setSeconds(0, 0);
|
|
1571
|
+
date.setMinutes(date.getMinutes() + 1);
|
|
1572
|
+
for (let guard2 = 0; guard2 < 1e5; guard2++) {
|
|
1573
|
+
if (!this.months.has(date.getMonth() + 1)) {
|
|
1574
|
+
date.setMonth(date.getMonth() + 1, 1);
|
|
1575
|
+
date.setHours(0, 0, 0, 0);
|
|
1576
|
+
continue;
|
|
1577
|
+
}
|
|
1578
|
+
if (!this.dayMatches(date)) {
|
|
1579
|
+
date.setDate(date.getDate() + 1);
|
|
1580
|
+
date.setHours(0, 0, 0, 0);
|
|
1581
|
+
continue;
|
|
1582
|
+
}
|
|
1583
|
+
if (!this.hours.has(date.getHours())) {
|
|
1584
|
+
date.setHours(date.getHours() + 1, 0, 0, 0);
|
|
1585
|
+
continue;
|
|
1586
|
+
}
|
|
1587
|
+
if (!this.minutes.has(date.getMinutes())) {
|
|
1588
|
+
date.setMinutes(date.getMinutes() + 1, 0, 0);
|
|
1589
|
+
continue;
|
|
1590
|
+
}
|
|
1591
|
+
return new Date(date.getTime());
|
|
1592
|
+
}
|
|
1593
|
+
throw new Error(`spearkit: cron expression "${this.source}" has no upcoming match`);
|
|
1594
|
+
}
|
|
1595
|
+
};
|
|
1596
|
+
function cron(expression) {
|
|
1597
|
+
return new CronExpression(expression);
|
|
1598
|
+
}
|
|
1599
|
+
function task(config) {
|
|
1600
|
+
if (config.cron === void 0 && config.interval === void 0) {
|
|
1601
|
+
throw new Error(`spearkit: task "${config.name}" needs a cron expression or an interval`);
|
|
1602
|
+
}
|
|
1603
|
+
if (config.interval !== void 0 && config.interval <= 0) {
|
|
1604
|
+
throw new Error(`spearkit: task "${config.name}" interval must be positive`);
|
|
1605
|
+
}
|
|
1606
|
+
return {
|
|
1607
|
+
kind: "task",
|
|
1608
|
+
name: config.name,
|
|
1609
|
+
interval: config.interval,
|
|
1610
|
+
cron: config.cron !== void 0 ? new CronExpression(config.cron) : void 0,
|
|
1611
|
+
runOnStart: config.runOnStart ?? false,
|
|
1612
|
+
run: config.run
|
|
1613
|
+
};
|
|
1614
|
+
}
|
|
1615
|
+
var MAX_TIMEOUT = 2147483647;
|
|
1616
|
+
var TaskScheduler = class {
|
|
1617
|
+
tasks = /* @__PURE__ */ new Map();
|
|
1618
|
+
timers = /* @__PURE__ */ new Map();
|
|
1619
|
+
running = false;
|
|
1620
|
+
client;
|
|
1621
|
+
logger;
|
|
1622
|
+
reconcilers = [];
|
|
1623
|
+
/** Number of registered tasks. */
|
|
1624
|
+
get size() {
|
|
1625
|
+
return this.tasks.size;
|
|
1626
|
+
}
|
|
1627
|
+
/** Whether the scheduler is currently running. */
|
|
1628
|
+
get active() {
|
|
1629
|
+
return this.running;
|
|
1630
|
+
}
|
|
1631
|
+
/** Every registered task. */
|
|
1632
|
+
list() {
|
|
1633
|
+
return [...this.tasks.values()];
|
|
1634
|
+
}
|
|
1635
|
+
/** Attach a logger for task error reporting. */
|
|
1636
|
+
setLogger(logger) {
|
|
1637
|
+
this.logger = logger;
|
|
1638
|
+
return this;
|
|
1639
|
+
}
|
|
1640
|
+
/** Register one or more tasks. If already running, they are scheduled now. */
|
|
1641
|
+
add(...tasks) {
|
|
1642
|
+
for (const task2 of tasks) {
|
|
1643
|
+
this.tasks.set(task2.name, task2);
|
|
1644
|
+
if (this.running) this.begin(task2);
|
|
1645
|
+
}
|
|
1646
|
+
return this;
|
|
1647
|
+
}
|
|
1648
|
+
/** Remove a task and cancel its timer. */
|
|
1649
|
+
remove(name) {
|
|
1650
|
+
this.cancel(name);
|
|
1651
|
+
return this.tasks.delete(name);
|
|
1652
|
+
}
|
|
1653
|
+
/**
|
|
1654
|
+
* Schedule a one-shot job: run `fn` once after `ms` milliseconds, then forget.
|
|
1655
|
+
* Returns a cancel handle. Replaces hand-rolled `setTimeout` calls for things
|
|
1656
|
+
* like "remind the moderator in 10 minutes if no claim happened".
|
|
1657
|
+
*/
|
|
1658
|
+
delay(name, ms, fn) {
|
|
1659
|
+
const key = `delay:${name}`;
|
|
1660
|
+
this.cancel(key);
|
|
1661
|
+
const timer = setTimeout(async () => {
|
|
1662
|
+
this.timers.delete(key);
|
|
1663
|
+
try {
|
|
1664
|
+
await fn();
|
|
1665
|
+
} catch (error) {
|
|
1666
|
+
this.logger?.error(`delay "${name}" failed`, { error: toError(error) });
|
|
1667
|
+
}
|
|
1668
|
+
}, Math.max(0, ms));
|
|
1669
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
1670
|
+
this.timers.set(key, timer);
|
|
1671
|
+
return {
|
|
1672
|
+
cancel: () => {
|
|
1673
|
+
const had = this.timers.has(key);
|
|
1674
|
+
this.cancel(key);
|
|
1675
|
+
return had;
|
|
1676
|
+
}
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
/**
|
|
1680
|
+
* Schedule a series of follow-up fires from a single start point. Each
|
|
1681
|
+
* delay is measured from "now"; the callback receives the index of the
|
|
1682
|
+
* fire. Generalises the 10s/30s/60s retry pattern in real bots.
|
|
1683
|
+
*/
|
|
1684
|
+
followUp(name, delays, fn) {
|
|
1685
|
+
const keys = delays.map((_, i) => `followUp:${name}:${i}`);
|
|
1686
|
+
for (const key of keys) this.cancel(key);
|
|
1687
|
+
delays.forEach((delay, i) => {
|
|
1688
|
+
const key = keys[i];
|
|
1689
|
+
const timer = setTimeout(async () => {
|
|
1690
|
+
this.timers.delete(key);
|
|
1691
|
+
try {
|
|
1692
|
+
await fn(i);
|
|
1693
|
+
} catch (error) {
|
|
1694
|
+
this.logger?.error(`followUp "${name}" fire ${i} failed`, { error: toError(error) });
|
|
1695
|
+
}
|
|
1696
|
+
}, Math.max(0, delay));
|
|
1697
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
1698
|
+
this.timers.set(key, timer);
|
|
1699
|
+
});
|
|
1700
|
+
return {
|
|
1701
|
+
cancel: () => {
|
|
1702
|
+
let any = false;
|
|
1703
|
+
for (const key of keys) {
|
|
1704
|
+
if (this.timers.has(key)) any = true;
|
|
1705
|
+
this.cancel(key);
|
|
1706
|
+
}
|
|
1707
|
+
return any;
|
|
1708
|
+
}
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
/**
|
|
1712
|
+
* Register a once-on-ready reconciler — runs the first time the scheduler
|
|
1713
|
+
* starts (typically when the client becomes ready) and never again. Use
|
|
1714
|
+
* for restart-recovery work like closing orphaned voice sessions or
|
|
1715
|
+
* reapplying cached channel state.
|
|
1716
|
+
*/
|
|
1717
|
+
reconcile(name, fn) {
|
|
1718
|
+
if (this.running && this.client !== void 0) {
|
|
1719
|
+
void this.runReconciler(name, fn, this.client);
|
|
1720
|
+
} else {
|
|
1721
|
+
this.reconcilers.push({ name, run: fn });
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
async runReconciler(name, run, client) {
|
|
1725
|
+
this.logger?.debug("reconcile", { data: { name } });
|
|
1726
|
+
try {
|
|
1727
|
+
await run(client);
|
|
1728
|
+
} catch (error) {
|
|
1729
|
+
this.logger?.error(`reconciler "${name}" failed`, { error: toError(error) });
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
/** Start every task. Safe to call once; later calls are ignored. */
|
|
1733
|
+
start(client) {
|
|
1734
|
+
if (this.running) return;
|
|
1735
|
+
this.client = client;
|
|
1736
|
+
this.running = true;
|
|
1737
|
+
for (const task2 of this.tasks.values()) this.begin(task2);
|
|
1738
|
+
const pending = this.reconcilers.splice(0);
|
|
1739
|
+
for (const { name, run } of pending) void this.runReconciler(name, run, client);
|
|
1740
|
+
}
|
|
1741
|
+
/** Stop the scheduler and cancel every pending timer. */
|
|
1742
|
+
stop() {
|
|
1743
|
+
this.running = false;
|
|
1744
|
+
for (const name of [...this.timers.keys()]) this.cancel(name);
|
|
1745
|
+
}
|
|
1746
|
+
cancel(name) {
|
|
1747
|
+
const timer = this.timers.get(name);
|
|
1748
|
+
if (timer !== void 0) {
|
|
1749
|
+
clearTimeout(timer);
|
|
1750
|
+
this.timers.delete(name);
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
begin(task2) {
|
|
1754
|
+
if (task2.runOnStart) void this.runTask(task2);
|
|
1755
|
+
this.scheduleNext(task2);
|
|
1756
|
+
}
|
|
1757
|
+
delayFor(task2) {
|
|
1758
|
+
if (task2.interval !== void 0) return task2.interval;
|
|
1759
|
+
if (task2.cron !== void 0) return Math.max(0, task2.cron.next().getTime() - Date.now());
|
|
1760
|
+
return MAX_TIMEOUT;
|
|
1761
|
+
}
|
|
1762
|
+
scheduleNext(task2) {
|
|
1763
|
+
if (!this.running) return;
|
|
1764
|
+
this.arm(task2.name, this.delayFor(task2), () => {
|
|
1765
|
+
void this.runTask(task2);
|
|
1766
|
+
this.scheduleNext(task2);
|
|
1767
|
+
});
|
|
1768
|
+
}
|
|
1769
|
+
arm(name, delay, fire) {
|
|
1770
|
+
if (delay > MAX_TIMEOUT) {
|
|
1771
|
+
const timer2 = setTimeout(() => this.arm(name, delay - MAX_TIMEOUT, fire), MAX_TIMEOUT);
|
|
1772
|
+
if (typeof timer2.unref === "function") timer2.unref();
|
|
1773
|
+
this.timers.set(name, timer2);
|
|
1774
|
+
return;
|
|
1775
|
+
}
|
|
1776
|
+
const timer = setTimeout(fire, Math.max(0, delay));
|
|
1777
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
1778
|
+
this.timers.set(name, timer);
|
|
1779
|
+
}
|
|
1780
|
+
async runTask(task2) {
|
|
1781
|
+
if (this.client === void 0) return;
|
|
1782
|
+
this.logger?.debug("task", { data: { task: task2.name } });
|
|
1783
|
+
try {
|
|
1784
|
+
await task2.run(this.client);
|
|
1785
|
+
} catch (error) {
|
|
1786
|
+
this.logger?.error(`task "${task2.name}" failed`, { error: toError(error) });
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
};
|
|
1790
|
+
|
|
1791
|
+
// src/prefix.ts
|
|
1792
|
+
function prefixCommand(config) {
|
|
1793
|
+
const parser = config.args !== void 0 ? config.args(prefixArgs()).compile() : void 0;
|
|
1794
|
+
return {
|
|
1795
|
+
kind: "prefixCommand",
|
|
1796
|
+
name: config.name,
|
|
1797
|
+
aliases: config.aliases ?? [],
|
|
1798
|
+
description: config.description,
|
|
1799
|
+
cooldown: config.cooldown !== void 0 ? normalizeCooldown(config.cooldown) : void 0,
|
|
1800
|
+
guards: config.guards,
|
|
1801
|
+
parser,
|
|
1802
|
+
run: async (ctx) => {
|
|
1803
|
+
await config.run(ctx);
|
|
1804
|
+
}
|
|
1805
|
+
};
|
|
30
1806
|
}
|
|
31
|
-
var
|
|
32
|
-
constructor(
|
|
33
|
-
this.
|
|
1807
|
+
var PrefixContext = class {
|
|
1808
|
+
constructor(message, commandName, args, rest, options = {}) {
|
|
1809
|
+
this.message = message;
|
|
1810
|
+
this.commandName = commandName;
|
|
1811
|
+
this.args = args;
|
|
1812
|
+
this.rest = rest;
|
|
1813
|
+
this.options = options;
|
|
34
1814
|
}
|
|
35
|
-
|
|
1815
|
+
message;
|
|
1816
|
+
commandName;
|
|
1817
|
+
args;
|
|
1818
|
+
rest;
|
|
1819
|
+
options;
|
|
36
1820
|
get client() {
|
|
37
|
-
return this.
|
|
1821
|
+
return this.message.client;
|
|
38
1822
|
}
|
|
39
|
-
get
|
|
40
|
-
return this.
|
|
1823
|
+
get author() {
|
|
1824
|
+
return this.message.author;
|
|
41
1825
|
}
|
|
42
1826
|
get member() {
|
|
43
|
-
return this.
|
|
1827
|
+
return this.message.member;
|
|
44
1828
|
}
|
|
45
1829
|
get guild() {
|
|
46
|
-
return this.
|
|
1830
|
+
return this.message.guild;
|
|
47
1831
|
}
|
|
48
1832
|
get guildId() {
|
|
49
|
-
return this.
|
|
1833
|
+
return this.message.guildId;
|
|
50
1834
|
}
|
|
51
1835
|
get channel() {
|
|
52
|
-
return this.
|
|
1836
|
+
return this.message.channel;
|
|
53
1837
|
}
|
|
54
1838
|
get channelId() {
|
|
55
|
-
return this.
|
|
1839
|
+
return this.message.channelId;
|
|
56
1840
|
}
|
|
57
|
-
|
|
58
|
-
|
|
1841
|
+
/** Reply to the triggering message. */
|
|
1842
|
+
reply(content) {
|
|
1843
|
+
return this.message.reply(content);
|
|
59
1844
|
}
|
|
60
|
-
/**
|
|
61
|
-
|
|
62
|
-
|
|
1845
|
+
/** Send a message to the same channel (no reply reference). */
|
|
1846
|
+
async send(content) {
|
|
1847
|
+
const channel = this.message.channel;
|
|
1848
|
+
if ("send" in channel) return channel.send(content);
|
|
1849
|
+
return void 0;
|
|
63
1850
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
1851
|
+
};
|
|
1852
|
+
function resolveOptions(input) {
|
|
1853
|
+
if (typeof input === "string") return { prefixes: [input], mention: true, ignoreBots: true, caseInsensitive: true };
|
|
1854
|
+
if (Array.isArray(input)) {
|
|
1855
|
+
return { prefixes: [...input], mention: true, ignoreBots: true, caseInsensitive: true };
|
|
67
1856
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
1857
|
+
const options = input;
|
|
1858
|
+
const prefix = options.prefix ?? [];
|
|
1859
|
+
return {
|
|
1860
|
+
prefixes: typeof prefix === "string" ? [prefix] : [...prefix],
|
|
1861
|
+
mention: options.mention ?? true,
|
|
1862
|
+
ignoreBots: options.ignoreBots ?? true,
|
|
1863
|
+
caseInsensitive: options.caseInsensitive ?? true
|
|
1864
|
+
};
|
|
1865
|
+
}
|
|
1866
|
+
function actorFromMessage(message) {
|
|
1867
|
+
const member = message.member;
|
|
1868
|
+
const roleIds = member !== null ? [...member.roles.cache.keys()] : [];
|
|
1869
|
+
return {
|
|
1870
|
+
userId: message.author.id,
|
|
1871
|
+
roleIds,
|
|
1872
|
+
guildId: message.guildId,
|
|
1873
|
+
channelId: message.channelId
|
|
1874
|
+
};
|
|
1875
|
+
}
|
|
1876
|
+
var PrefixRegistry = class {
|
|
1877
|
+
commands = /* @__PURE__ */ new Map();
|
|
1878
|
+
lookup = /* @__PURE__ */ new Map();
|
|
1879
|
+
options = {
|
|
1880
|
+
prefixes: [],
|
|
1881
|
+
mention: true,
|
|
1882
|
+
ignoreBots: true,
|
|
1883
|
+
caseInsensitive: true
|
|
1884
|
+
};
|
|
1885
|
+
logger;
|
|
1886
|
+
cooldowns;
|
|
1887
|
+
defaultCooldown;
|
|
1888
|
+
errorHandler;
|
|
1889
|
+
defaultGuards = [];
|
|
1890
|
+
onUsage;
|
|
1891
|
+
/** Configure prefixes and matching behaviour. */
|
|
1892
|
+
setOptions(input) {
|
|
1893
|
+
this.options = resolveOptions(input);
|
|
1894
|
+
return this;
|
|
71
1895
|
}
|
|
72
|
-
/**
|
|
73
|
-
|
|
74
|
-
|
|
1896
|
+
/** Attach a logger for dispatch tracing and error reporting. */
|
|
1897
|
+
setLogger(logger) {
|
|
1898
|
+
this.logger = logger;
|
|
1899
|
+
return this;
|
|
75
1900
|
}
|
|
76
|
-
/**
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
);
|
|
1901
|
+
/** Attach a hook called after each successful prefix command run. */
|
|
1902
|
+
setUsageHook(hook) {
|
|
1903
|
+
this.onUsage = hook;
|
|
1904
|
+
return this;
|
|
81
1905
|
}
|
|
82
|
-
/**
|
|
83
|
-
|
|
84
|
-
|
|
1906
|
+
/** Share a cooldown manager and an optional default cooldown. */
|
|
1907
|
+
setCooldowns(manager, defaultCooldown) {
|
|
1908
|
+
this.cooldowns = manager;
|
|
1909
|
+
this.defaultCooldown = defaultCooldown;
|
|
1910
|
+
return this;
|
|
85
1911
|
}
|
|
86
|
-
/**
|
|
87
|
-
|
|
88
|
-
|
|
1912
|
+
/** Guards that run before every prefix command's own guards. */
|
|
1913
|
+
setDefaultGuards(guards) {
|
|
1914
|
+
this.defaultGuards = guards;
|
|
1915
|
+
return this;
|
|
1916
|
+
}
|
|
1917
|
+
/** Set the handler used when a prefix command throws. */
|
|
1918
|
+
onError(handler) {
|
|
1919
|
+
this.errorHandler = handler;
|
|
1920
|
+
return this;
|
|
1921
|
+
}
|
|
1922
|
+
/** Register one or more prefix commands (and their aliases). */
|
|
1923
|
+
add(...commands) {
|
|
1924
|
+
for (const command2 of commands) {
|
|
1925
|
+
this.commands.set(command2.name, command2);
|
|
1926
|
+
this.index(command2.name, command2);
|
|
1927
|
+
for (const alias of command2.aliases) this.index(alias, command2);
|
|
1928
|
+
}
|
|
1929
|
+
return this;
|
|
1930
|
+
}
|
|
1931
|
+
index(key, command2) {
|
|
1932
|
+
this.lookup.set(this.options.caseInsensitive ? key.toLowerCase() : key, command2);
|
|
1933
|
+
}
|
|
1934
|
+
/** Look up a command by name or alias. */
|
|
1935
|
+
get(nameOrAlias) {
|
|
1936
|
+
return this.lookup.get(this.options.caseInsensitive ? nameOrAlias.toLowerCase() : nameOrAlias);
|
|
1937
|
+
}
|
|
1938
|
+
/** Number of registered commands (excluding aliases). */
|
|
1939
|
+
get size() {
|
|
1940
|
+
return this.commands.size;
|
|
1941
|
+
}
|
|
1942
|
+
/** Every registered command. */
|
|
1943
|
+
list() {
|
|
1944
|
+
return [...this.commands.values()];
|
|
1945
|
+
}
|
|
1946
|
+
/** Strip a matching prefix (or bot mention) from `content`, or return `null`. */
|
|
1947
|
+
stripPrefix(content, botId) {
|
|
1948
|
+
for (const prefix of this.options.prefixes) {
|
|
1949
|
+
if (prefix.length > 0 && content.startsWith(prefix)) return content.slice(prefix.length);
|
|
1950
|
+
}
|
|
1951
|
+
if (this.options.mention && botId !== void 0) {
|
|
1952
|
+
const match = /^<@!?(\d+)>\s*/.exec(content);
|
|
1953
|
+
if (match !== null && match[1] === botId) return content.slice(match[0].length);
|
|
1954
|
+
}
|
|
1955
|
+
return null;
|
|
89
1956
|
}
|
|
90
1957
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
* most handlers ever need.
|
|
1958
|
+
* Parse and dispatch a message. Returns `true` when a command ran (or was
|
|
1959
|
+
* blocked by a cooldown), `false` when the message was not a prefix command.
|
|
94
1960
|
*/
|
|
95
|
-
async
|
|
96
|
-
if (this.
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
1961
|
+
async handle(message) {
|
|
1962
|
+
if (this.options.prefixes.length === 0 && !this.options.mention) return false;
|
|
1963
|
+
if (this.options.ignoreBots && message.author.bot) return false;
|
|
1964
|
+
const stripped = this.stripPrefix(message.content, message.client.user?.id);
|
|
1965
|
+
if (stripped === null) return false;
|
|
1966
|
+
const trimmed = stripped.trimStart();
|
|
1967
|
+
const match = /^(\S+)\s*([\s\S]*)$/.exec(trimmed);
|
|
1968
|
+
if (match === null) return false;
|
|
1969
|
+
const name = match[1] ?? "";
|
|
1970
|
+
const rest = match[2] ?? "";
|
|
1971
|
+
const command2 = this.get(name);
|
|
1972
|
+
if (command2 === void 0) return false;
|
|
1973
|
+
this.logger?.debug("prefix", { data: { command: command2.name, user: message.author.id } });
|
|
1974
|
+
const cooldown = command2.cooldown ?? this.defaultCooldown;
|
|
1975
|
+
if (cooldown !== void 0 && this.cooldowns !== void 0) {
|
|
1976
|
+
const result = this.cooldowns.consume(`prefix:${command2.name}`, cooldown, actorFromMessage(message));
|
|
1977
|
+
if (!result.allowed) {
|
|
1978
|
+
await message.reply(formatCooldownMessage(cooldown, result.remaining)).catch(() => void 0);
|
|
1979
|
+
return true;
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
const guards = combineGuards2(this.defaultGuards, command2.guards);
|
|
1983
|
+
if (guards.length > 0) {
|
|
1984
|
+
const guardCtx = guardContextFromMessage(message);
|
|
1985
|
+
const guardResult = await runGuards(guardCtx, guards);
|
|
1986
|
+
if (!guardResult.allowed) {
|
|
1987
|
+
this.logger?.debug("prefix denied", {
|
|
1988
|
+
data: {
|
|
1989
|
+
command: command2.name,
|
|
1990
|
+
user: message.author.id,
|
|
1991
|
+
reason: guardResult.reason ?? ""
|
|
1992
|
+
}
|
|
1993
|
+
});
|
|
1994
|
+
await replyDeniedMessage(message, guardResult.reason);
|
|
1995
|
+
return true;
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
const args = rest.length > 0 ? rest.split(/\s+/) : [];
|
|
1999
|
+
let options = {};
|
|
2000
|
+
if (command2.parser !== void 0) {
|
|
2001
|
+
const parsed = command2.parser.parse(args, rest);
|
|
2002
|
+
if (!parsed.ok) {
|
|
2003
|
+
this.logger?.debug("prefix arg error", {
|
|
2004
|
+
data: { command: command2.name, user: message.author.id, arg: parsed.arg, reason: parsed.reason }
|
|
2005
|
+
});
|
|
2006
|
+
const embeds = clientEmbeds3(message.client);
|
|
2007
|
+
await message.reply({ embeds: [embeds.error(`Argument \`${parsed.arg}\`: ${parsed.reason}`)] }).catch(() => void 0);
|
|
2008
|
+
return true;
|
|
2009
|
+
}
|
|
2010
|
+
options = parsed.values;
|
|
2011
|
+
}
|
|
2012
|
+
const start = Date.now();
|
|
2013
|
+
try {
|
|
2014
|
+
await command2.run(new PrefixContext(message, name, args, rest, options));
|
|
2015
|
+
this.onUsage?.({
|
|
2016
|
+
type: "prefix",
|
|
2017
|
+
name: command2.name,
|
|
2018
|
+
outcome: "success",
|
|
2019
|
+
durationMs: Date.now() - start,
|
|
2020
|
+
userId: message.author.id,
|
|
2021
|
+
userTag: message.author.tag,
|
|
2022
|
+
guildId: message.guildId,
|
|
2023
|
+
channelId: message.channelId,
|
|
2024
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
2025
|
+
});
|
|
2026
|
+
} catch (error) {
|
|
2027
|
+
const err = toError(error);
|
|
2028
|
+
this.logger?.error(`prefix command "${command2.name}" failed`, { error: err });
|
|
2029
|
+
this.onUsage?.({
|
|
2030
|
+
type: "prefix",
|
|
2031
|
+
name: command2.name,
|
|
2032
|
+
outcome: "error",
|
|
2033
|
+
errorMessage: err.message,
|
|
2034
|
+
durationMs: Date.now() - start,
|
|
2035
|
+
userId: message.author.id,
|
|
2036
|
+
userTag: message.author.tag,
|
|
2037
|
+
guildId: message.guildId,
|
|
2038
|
+
channelId: message.channelId,
|
|
2039
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
2040
|
+
});
|
|
2041
|
+
if (this.errorHandler !== void 0) await this.errorHandler(err, message);
|
|
2042
|
+
}
|
|
2043
|
+
return true;
|
|
2044
|
+
}
|
|
2045
|
+
};
|
|
2046
|
+
function combineGuards2(defaults, own) {
|
|
2047
|
+
if (own === void 0 || own.length === 0) return defaults;
|
|
2048
|
+
if (defaults.length === 0) return own;
|
|
2049
|
+
return [...defaults, ...own];
|
|
2050
|
+
}
|
|
2051
|
+
function guardContextFromMessage(message) {
|
|
2052
|
+
return {
|
|
2053
|
+
client: message.client,
|
|
2054
|
+
user: message.author,
|
|
2055
|
+
member: message.member,
|
|
2056
|
+
guild: message.guild,
|
|
2057
|
+
guildId: message.guildId,
|
|
2058
|
+
channelId: message.channelId
|
|
2059
|
+
};
|
|
2060
|
+
}
|
|
2061
|
+
function clientEmbeds3(client) {
|
|
2062
|
+
return client.embeds ?? defaultEmbeds;
|
|
2063
|
+
}
|
|
2064
|
+
async function replyDeniedMessage(message, reason) {
|
|
2065
|
+
const embeds = clientEmbeds3(message.client);
|
|
2066
|
+
const text = reason ?? "You don't have permission to use this.";
|
|
2067
|
+
await message.reply({ embeds: [embeds.error(text)] }).catch(() => void 0);
|
|
2068
|
+
}
|
|
2069
|
+
var MemoryUsageStore = class {
|
|
2070
|
+
constructor(limit = Number.POSITIVE_INFINITY) {
|
|
2071
|
+
this.limit = limit;
|
|
2072
|
+
}
|
|
2073
|
+
limit;
|
|
2074
|
+
events = [];
|
|
2075
|
+
record(event2) {
|
|
2076
|
+
this.events.push(event2);
|
|
2077
|
+
if (this.events.length > this.limit) this.events.splice(0, this.events.length - this.limit);
|
|
2078
|
+
}
|
|
2079
|
+
all() {
|
|
2080
|
+
return this.events;
|
|
2081
|
+
}
|
|
2082
|
+
/** Total recorded events. */
|
|
2083
|
+
get size() {
|
|
2084
|
+
return this.events.length;
|
|
2085
|
+
}
|
|
2086
|
+
/** Events recorded for a given user id. */
|
|
2087
|
+
byUser(userId) {
|
|
2088
|
+
return this.events.filter((event2) => event2.userId === userId);
|
|
2089
|
+
}
|
|
2090
|
+
/** Forget everything. */
|
|
2091
|
+
clear() {
|
|
2092
|
+
this.events.length = 0;
|
|
2093
|
+
}
|
|
2094
|
+
};
|
|
2095
|
+
var JsonFileUsageStore = class {
|
|
2096
|
+
constructor(path) {
|
|
2097
|
+
this.path = path;
|
|
2098
|
+
}
|
|
2099
|
+
path;
|
|
2100
|
+
async record(event2) {
|
|
2101
|
+
const line = `${JSON.stringify({ ...event2, timestamp: event2.timestamp.toISOString() })}
|
|
2102
|
+
`;
|
|
2103
|
+
await mkdir(dirname(this.path), { recursive: true });
|
|
2104
|
+
await appendFile(this.path, line, "utf8");
|
|
2105
|
+
}
|
|
2106
|
+
async all() {
|
|
2107
|
+
let content;
|
|
2108
|
+
try {
|
|
2109
|
+
content = await readFile$1(this.path, "utf8");
|
|
2110
|
+
} catch {
|
|
2111
|
+
return [];
|
|
102
2112
|
}
|
|
2113
|
+
const events = [];
|
|
2114
|
+
for (const line of content.split("\n")) {
|
|
2115
|
+
if (line.trim().length === 0) continue;
|
|
2116
|
+
const parsed = JSON.parse(line);
|
|
2117
|
+
events.push({ ...parsed, timestamp: new Date(parsed.timestamp) });
|
|
2118
|
+
}
|
|
2119
|
+
return events;
|
|
2120
|
+
}
|
|
2121
|
+
};
|
|
2122
|
+
function formatUsage(event2) {
|
|
2123
|
+
const who = event2.userTag ?? (event2.userId !== void 0 ? `<@${event2.userId}>` : "unknown");
|
|
2124
|
+
const where = event2.channelId !== void 0 && event2.channelId !== null ? ` in <#${event2.channelId}>` : "";
|
|
2125
|
+
const detail = event2.detail !== void 0 ? ` \u2014 ${event2.detail}` : "";
|
|
2126
|
+
return `\`${event2.type}\` **${event2.name}** by ${who}${where}${detail}`;
|
|
2127
|
+
}
|
|
2128
|
+
var UsageTracker = class {
|
|
2129
|
+
/** The configured store, if any. Directly queryable. */
|
|
2130
|
+
store;
|
|
2131
|
+
reporter;
|
|
2132
|
+
client;
|
|
2133
|
+
logger;
|
|
2134
|
+
/** Whether anything will happen on {@link track}. */
|
|
2135
|
+
get enabled() {
|
|
2136
|
+
return this.store !== void 0 || this.reporter !== void 0;
|
|
2137
|
+
}
|
|
2138
|
+
/** @internal Used by the client to resolve report channels. */
|
|
2139
|
+
setClient(client) {
|
|
2140
|
+
this.client = client;
|
|
2141
|
+
return this;
|
|
2142
|
+
}
|
|
2143
|
+
setLogger(logger) {
|
|
2144
|
+
this.logger = logger;
|
|
2145
|
+
return this;
|
|
2146
|
+
}
|
|
2147
|
+
/** Persist events to a store (a database). */
|
|
2148
|
+
setStore(store) {
|
|
2149
|
+
this.store = store;
|
|
2150
|
+
return this;
|
|
2151
|
+
}
|
|
2152
|
+
/** Mirror events into a Discord channel. */
|
|
2153
|
+
reportTo(channelId, format = formatUsage) {
|
|
2154
|
+
this.reporter = { channelId, format };
|
|
2155
|
+
return this;
|
|
103
2156
|
}
|
|
104
|
-
/**
|
|
105
|
-
|
|
106
|
-
|
|
2157
|
+
/** Record a use. Returns immediately; storing/reporting happen in the background. */
|
|
2158
|
+
track(event2) {
|
|
2159
|
+
if (!this.enabled) return;
|
|
2160
|
+
void this.run(event2);
|
|
2161
|
+
}
|
|
2162
|
+
async run(event2) {
|
|
2163
|
+
if (this.store !== void 0) {
|
|
2164
|
+
try {
|
|
2165
|
+
await this.store.record(event2);
|
|
2166
|
+
} catch (error) {
|
|
2167
|
+
this.logger?.error("usage store failed", { error: toError(error) });
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
if (this.reporter !== void 0 && this.client !== void 0) {
|
|
2171
|
+
try {
|
|
2172
|
+
const cache = this.client.channels.cache.get(this.reporter.channelId);
|
|
2173
|
+
const channel = cache ?? await this.client.channels.fetch(this.reporter.channelId);
|
|
2174
|
+
if (channel !== null && "send" in channel) {
|
|
2175
|
+
await channel.send(this.reporter.format(event2));
|
|
2176
|
+
}
|
|
2177
|
+
} catch (error) {
|
|
2178
|
+
this.logger?.error("usage report failed", { error: toError(error) });
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
107
2181
|
}
|
|
108
2182
|
};
|
|
109
2183
|
function makeOption(type, config) {
|
|
@@ -285,6 +2359,10 @@ var SlashCommand = class {
|
|
|
285
2359
|
json;
|
|
286
2360
|
executor;
|
|
287
2361
|
autocompleter;
|
|
2362
|
+
/** Resolved cooldown configuration for this command, if any. */
|
|
2363
|
+
cooldown;
|
|
2364
|
+
/** Resolved guard list for this command, if any. */
|
|
2365
|
+
guards;
|
|
288
2366
|
/** @internal */
|
|
289
2367
|
constructor(spec) {
|
|
290
2368
|
this.name = spec.name;
|
|
@@ -292,6 +2370,8 @@ var SlashCommand = class {
|
|
|
292
2370
|
this.json = spec.json;
|
|
293
2371
|
this.executor = spec.executor;
|
|
294
2372
|
this.autocompleter = spec.autocompleter;
|
|
2373
|
+
this.cooldown = spec.cooldown;
|
|
2374
|
+
this.guards = spec.guards;
|
|
295
2375
|
}
|
|
296
2376
|
/** Serialise to the discord REST chat-input command payload. */
|
|
297
2377
|
toJSON() {
|
|
@@ -306,7 +2386,7 @@ var SlashCommand = class {
|
|
|
306
2386
|
return this.autocompleter(interaction);
|
|
307
2387
|
}
|
|
308
2388
|
};
|
|
309
|
-
function
|
|
2389
|
+
function resolveOptions2(interaction, options) {
|
|
310
2390
|
const resolved = {};
|
|
311
2391
|
for (const [name, def] of Object.entries(options)) {
|
|
312
2392
|
resolved[name] = readOption(interaction.options, name, def);
|
|
@@ -326,7 +2406,7 @@ function makeAutocompleter(options) {
|
|
|
326
2406
|
if (!interaction.responded) await ctx.respond(choices);
|
|
327
2407
|
};
|
|
328
2408
|
}
|
|
329
|
-
function
|
|
2409
|
+
function baseJSON2(meta, options) {
|
|
330
2410
|
return {
|
|
331
2411
|
type: ApplicationCommandType.ChatInput,
|
|
332
2412
|
name: meta.name,
|
|
@@ -361,22 +2441,24 @@ function command(config) {
|
|
|
361
2441
|
const options = config.options ?? {};
|
|
362
2442
|
const { run } = config;
|
|
363
2443
|
const executor = async (interaction) => {
|
|
364
|
-
const resolved =
|
|
2444
|
+
const resolved = resolveOptions2(interaction, options);
|
|
365
2445
|
await run(new CommandContext(interaction, resolved));
|
|
366
2446
|
};
|
|
367
2447
|
return new SlashCommand({
|
|
368
2448
|
name: config.name,
|
|
369
|
-
json:
|
|
2449
|
+
json: baseJSON2(config, leafOptionsJSON(options)),
|
|
370
2450
|
hasAutocomplete: optionsHaveAutocomplete(options),
|
|
371
2451
|
executor,
|
|
372
|
-
autocompleter: makeAutocompleter(options)
|
|
2452
|
+
autocompleter: makeAutocompleter(options),
|
|
2453
|
+
cooldown: config.cooldown !== void 0 ? normalizeCooldown(config.cooldown) : void 0,
|
|
2454
|
+
guards: config.guards
|
|
373
2455
|
});
|
|
374
2456
|
}
|
|
375
2457
|
function subcommand(config) {
|
|
376
2458
|
const options = config.options ?? {};
|
|
377
2459
|
const { run } = config;
|
|
378
2460
|
const execute = async (interaction) => {
|
|
379
|
-
const resolved =
|
|
2461
|
+
const resolved = resolveOptions2(interaction, options);
|
|
380
2462
|
await run(new CommandContext(interaction, resolved));
|
|
381
2463
|
};
|
|
382
2464
|
return {
|
|
@@ -437,15 +2519,22 @@ function commandGroup(config) {
|
|
|
437
2519
|
};
|
|
438
2520
|
return new SlashCommand({
|
|
439
2521
|
name: config.name,
|
|
440
|
-
json:
|
|
2522
|
+
json: baseJSON2(config, options),
|
|
441
2523
|
hasAutocomplete,
|
|
442
2524
|
executor,
|
|
443
|
-
autocompleter
|
|
2525
|
+
autocompleter,
|
|
2526
|
+
cooldown: config.cooldown !== void 0 ? normalizeCooldown(config.cooldown) : void 0,
|
|
2527
|
+
guards: config.guards
|
|
444
2528
|
});
|
|
445
2529
|
}
|
|
446
2530
|
var CommandRegistry = class {
|
|
447
2531
|
commands = /* @__PURE__ */ new Map();
|
|
448
2532
|
errorHandler;
|
|
2533
|
+
logger;
|
|
2534
|
+
cooldowns;
|
|
2535
|
+
defaultCooldown;
|
|
2536
|
+
defaultGuards = [];
|
|
2537
|
+
onUsage;
|
|
449
2538
|
/** Register one or more commands. Later registrations override by name. */
|
|
450
2539
|
add(...commands) {
|
|
451
2540
|
for (const command2 of commands) this.commands.set(command2.name, command2);
|
|
@@ -476,6 +2565,27 @@ var CommandRegistry = class {
|
|
|
476
2565
|
this.errorHandler = handler;
|
|
477
2566
|
return this;
|
|
478
2567
|
}
|
|
2568
|
+
/** Attach a logger used for dispatch tracing (debug level). */
|
|
2569
|
+
setLogger(logger) {
|
|
2570
|
+
this.logger = logger;
|
|
2571
|
+
return this;
|
|
2572
|
+
}
|
|
2573
|
+
/** Wire a shared cooldown manager and an optional default cooldown for every command. */
|
|
2574
|
+
setCooldowns(manager, defaultCooldown) {
|
|
2575
|
+
this.cooldowns = manager;
|
|
2576
|
+
this.defaultCooldown = defaultCooldown;
|
|
2577
|
+
return this;
|
|
2578
|
+
}
|
|
2579
|
+
/** Guards that run before every command's own guards. */
|
|
2580
|
+
setDefaultGuards(guards) {
|
|
2581
|
+
this.defaultGuards = guards;
|
|
2582
|
+
return this;
|
|
2583
|
+
}
|
|
2584
|
+
/** Attach a hook called after each successful command execution. */
|
|
2585
|
+
setUsageHook(hook) {
|
|
2586
|
+
this.onUsage = hook;
|
|
2587
|
+
return this;
|
|
2588
|
+
}
|
|
479
2589
|
/** Serialise every command to discord REST payloads. */
|
|
480
2590
|
toJSON() {
|
|
481
2591
|
return this.all().map((c) => c.toJSON());
|
|
@@ -484,10 +2594,60 @@ var CommandRegistry = class {
|
|
|
484
2594
|
async handle(interaction) {
|
|
485
2595
|
const command2 = this.commands.get(interaction.commandName);
|
|
486
2596
|
if (command2 === void 0) return;
|
|
2597
|
+
this.logger?.debug("command", {
|
|
2598
|
+
data: { command: interaction.commandName, user: interaction.user.id }
|
|
2599
|
+
});
|
|
2600
|
+
const cooldown = command2.cooldown ?? this.defaultCooldown;
|
|
2601
|
+
if (cooldown !== void 0 && this.cooldowns !== void 0) {
|
|
2602
|
+
const result = this.cooldowns.consume(command2.name, cooldown, actorOf2(interaction));
|
|
2603
|
+
if (!result.allowed) {
|
|
2604
|
+
await this.replyCooldown(interaction, cooldown, result.remaining);
|
|
2605
|
+
return;
|
|
2606
|
+
}
|
|
2607
|
+
}
|
|
2608
|
+
const guards = combineGuards3(this.defaultGuards, command2.guards);
|
|
2609
|
+
if (guards.length > 0) {
|
|
2610
|
+
const guardResult = await runGuards(interaction, guards);
|
|
2611
|
+
if (!guardResult.allowed) {
|
|
2612
|
+
this.logger?.debug("command denied", {
|
|
2613
|
+
data: {
|
|
2614
|
+
command: command2.name,
|
|
2615
|
+
user: interaction.user.id,
|
|
2616
|
+
reason: guardResult.reason ?? ""
|
|
2617
|
+
}
|
|
2618
|
+
});
|
|
2619
|
+
await this.replyDenied(interaction, guardResult.reason);
|
|
2620
|
+
return;
|
|
2621
|
+
}
|
|
2622
|
+
}
|
|
2623
|
+
const start = Date.now();
|
|
487
2624
|
try {
|
|
488
2625
|
await command2.execute(interaction);
|
|
2626
|
+
this.onUsage?.({
|
|
2627
|
+
type: "command",
|
|
2628
|
+
name: command2.name,
|
|
2629
|
+
outcome: "success",
|
|
2630
|
+
durationMs: Date.now() - start,
|
|
2631
|
+
userId: interaction.user.id,
|
|
2632
|
+
userTag: interaction.user.tag,
|
|
2633
|
+
guildId: interaction.guildId,
|
|
2634
|
+
channelId: interaction.channelId,
|
|
2635
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
2636
|
+
});
|
|
489
2637
|
} catch (error) {
|
|
490
2638
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
2639
|
+
this.onUsage?.({
|
|
2640
|
+
type: "command",
|
|
2641
|
+
name: command2.name,
|
|
2642
|
+
outcome: "error",
|
|
2643
|
+
errorMessage: err.message,
|
|
2644
|
+
durationMs: Date.now() - start,
|
|
2645
|
+
userId: interaction.user.id,
|
|
2646
|
+
userTag: interaction.user.tag,
|
|
2647
|
+
guildId: interaction.guildId,
|
|
2648
|
+
channelId: interaction.channelId,
|
|
2649
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
2650
|
+
});
|
|
491
2651
|
if (this.errorHandler !== void 0) {
|
|
492
2652
|
await this.errorHandler(err, interaction);
|
|
493
2653
|
} else {
|
|
@@ -537,10 +2697,56 @@ var CommandRegistry = class {
|
|
|
537
2697
|
} catch {
|
|
538
2698
|
}
|
|
539
2699
|
}
|
|
2700
|
+
async replyCooldown(interaction, config, remaining) {
|
|
2701
|
+
this.logger?.debug("cooldown", {
|
|
2702
|
+
data: { command: interaction.commandName, user: interaction.user.id, remaining }
|
|
2703
|
+
});
|
|
2704
|
+
const content = formatCooldownMessage(config, remaining);
|
|
2705
|
+
try {
|
|
2706
|
+
if (interaction.deferred) await interaction.editReply({ content });
|
|
2707
|
+
else if (interaction.replied) await interaction.followUp({ content, flags: MessageFlags.Ephemeral });
|
|
2708
|
+
else await interaction.reply({ content, flags: MessageFlags.Ephemeral });
|
|
2709
|
+
} catch {
|
|
2710
|
+
}
|
|
2711
|
+
}
|
|
2712
|
+
async replyDenied(interaction, reason) {
|
|
2713
|
+
const embeds = clientEmbeds4(interaction.client);
|
|
2714
|
+
const text = reason ?? "You don't have permission to use this.";
|
|
2715
|
+
try {
|
|
2716
|
+
const payload = { embeds: [embeds.error(text)], flags: MessageFlags.Ephemeral };
|
|
2717
|
+
if (interaction.deferred) await interaction.editReply({ embeds: payload.embeds });
|
|
2718
|
+
else if (interaction.replied) await interaction.followUp(payload);
|
|
2719
|
+
else await interaction.reply(payload);
|
|
2720
|
+
} catch {
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
540
2723
|
};
|
|
2724
|
+
function combineGuards3(defaults, own) {
|
|
2725
|
+
if (own === void 0 || own.length === 0) return defaults;
|
|
2726
|
+
if (defaults.length === 0) return own;
|
|
2727
|
+
return [...defaults, ...own];
|
|
2728
|
+
}
|
|
2729
|
+
function clientEmbeds4(client) {
|
|
2730
|
+
const host = client;
|
|
2731
|
+
return host.embeds ?? defaultEmbeds;
|
|
2732
|
+
}
|
|
2733
|
+
function actorOf2(interaction) {
|
|
2734
|
+
const member = interaction.member;
|
|
2735
|
+
let roleIds = [];
|
|
2736
|
+
if (member !== null) {
|
|
2737
|
+
const roles = member.roles;
|
|
2738
|
+
roleIds = Array.isArray(roles) ? roles : [...roles.cache.keys()];
|
|
2739
|
+
}
|
|
2740
|
+
return {
|
|
2741
|
+
userId: interaction.user.id,
|
|
2742
|
+
roleIds,
|
|
2743
|
+
guildId: interaction.guildId,
|
|
2744
|
+
channelId: interaction.channelId
|
|
2745
|
+
};
|
|
2746
|
+
}
|
|
541
2747
|
|
|
542
2748
|
// src/events.ts
|
|
543
|
-
function
|
|
2749
|
+
function toError2(value) {
|
|
544
2750
|
return value instanceof Error ? value : new Error(String(value));
|
|
545
2751
|
}
|
|
546
2752
|
function build(name, once, run) {
|
|
@@ -553,10 +2759,10 @@ function build(name, once, run) {
|
|
|
553
2759
|
try {
|
|
554
2760
|
const result = run(...args);
|
|
555
2761
|
if (result instanceof Promise) {
|
|
556
|
-
result.catch((error) => client.emit("error",
|
|
2762
|
+
result.catch((error) => client.emit("error", toError2(error)));
|
|
557
2763
|
}
|
|
558
2764
|
} catch (error) {
|
|
559
|
-
client.emit("error",
|
|
2765
|
+
client.emit("error", toError2(error));
|
|
560
2766
|
}
|
|
561
2767
|
};
|
|
562
2768
|
listeners.set(client, listener);
|
|
@@ -762,7 +2968,7 @@ var ModalContext = class extends BaseContext {
|
|
|
762
2968
|
return this.interaction.customId;
|
|
763
2969
|
}
|
|
764
2970
|
};
|
|
765
|
-
function
|
|
2971
|
+
function toError3(value) {
|
|
766
2972
|
return value instanceof Error ? value : new Error(String(value));
|
|
767
2973
|
}
|
|
768
2974
|
var ComponentRegistry = class {
|
|
@@ -774,6 +2980,9 @@ var ComponentRegistry = class {
|
|
|
774
2980
|
mentionableSelects = /* @__PURE__ */ new Map();
|
|
775
2981
|
modals = /* @__PURE__ */ new Map();
|
|
776
2982
|
errorHandler;
|
|
2983
|
+
logger;
|
|
2984
|
+
onUsage;
|
|
2985
|
+
defaultGuards = [];
|
|
777
2986
|
/** Register one or more components. Later registrations override by namespace. */
|
|
778
2987
|
add(...defs) {
|
|
779
2988
|
for (const def of defs) {
|
|
@@ -808,6 +3017,21 @@ var ComponentRegistry = class {
|
|
|
808
3017
|
this.errorHandler = handler;
|
|
809
3018
|
return this;
|
|
810
3019
|
}
|
|
3020
|
+
/** Attach a logger used for dispatch tracing (debug level). */
|
|
3021
|
+
setLogger(logger) {
|
|
3022
|
+
this.logger = logger;
|
|
3023
|
+
return this;
|
|
3024
|
+
}
|
|
3025
|
+
/** Attach a hook called after each successful component handler run. */
|
|
3026
|
+
setUsageHook(hook) {
|
|
3027
|
+
this.onUsage = hook;
|
|
3028
|
+
return this;
|
|
3029
|
+
}
|
|
3030
|
+
/** Guards that run before every component's own guards. */
|
|
3031
|
+
setDefaultGuards(guards) {
|
|
3032
|
+
this.defaultGuards = guards;
|
|
3033
|
+
return this;
|
|
3034
|
+
}
|
|
811
3035
|
/** Total number of registered components. */
|
|
812
3036
|
get size() {
|
|
813
3037
|
return this.buttons.size + this.stringSelects.size + this.userSelects.size + this.roleSelects.size + this.channelSelects.size + this.mentionableSelects.size + this.modals.size;
|
|
@@ -842,12 +3066,48 @@ var ComponentRegistry = class {
|
|
|
842
3066
|
}
|
|
843
3067
|
async exec(route, interaction) {
|
|
844
3068
|
if (route === void 0) return false;
|
|
3069
|
+
this.logger?.debug("component", { data: { customId: interaction.customId } });
|
|
3070
|
+
const guards = combineGuards4(this.defaultGuards, route.guards);
|
|
3071
|
+
if (guards.length > 0) {
|
|
3072
|
+
const guardResult = await runGuards(interaction, guards);
|
|
3073
|
+
if (!guardResult.allowed) {
|
|
3074
|
+
this.logger?.debug("component denied", {
|
|
3075
|
+
data: { customId: interaction.customId, reason: guardResult.reason ?? "" }
|
|
3076
|
+
});
|
|
3077
|
+
await replyDeniedComponent(interaction, guardResult.reason);
|
|
3078
|
+
return true;
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
845
3081
|
const { values } = parseCustomId(interaction.customId);
|
|
846
3082
|
const params = paramsFromValues(route.paramNames, values);
|
|
3083
|
+
const start = Date.now();
|
|
847
3084
|
try {
|
|
848
3085
|
await route.handle(interaction, params);
|
|
3086
|
+
this.onUsage?.({
|
|
3087
|
+
type: "component",
|
|
3088
|
+
name: route.namespace,
|
|
3089
|
+
outcome: "success",
|
|
3090
|
+
durationMs: Date.now() - start,
|
|
3091
|
+
userId: interaction.user.id,
|
|
3092
|
+
userTag: interaction.user.tag,
|
|
3093
|
+
guildId: interaction.guildId,
|
|
3094
|
+
channelId: interaction.channelId,
|
|
3095
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
3096
|
+
});
|
|
849
3097
|
} catch (error) {
|
|
850
|
-
const err =
|
|
3098
|
+
const err = toError3(error);
|
|
3099
|
+
this.onUsage?.({
|
|
3100
|
+
type: "component",
|
|
3101
|
+
name: route.namespace,
|
|
3102
|
+
outcome: "error",
|
|
3103
|
+
errorMessage: err.message,
|
|
3104
|
+
durationMs: Date.now() - start,
|
|
3105
|
+
userId: interaction.user.id,
|
|
3106
|
+
userTag: interaction.user.tag,
|
|
3107
|
+
guildId: interaction.guildId,
|
|
3108
|
+
channelId: interaction.channelId,
|
|
3109
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
3110
|
+
});
|
|
851
3111
|
if (this.errorHandler !== void 0) {
|
|
852
3112
|
await this.errorHandler(err, interaction);
|
|
853
3113
|
} else {
|
|
@@ -863,6 +3123,25 @@ var ComponentRegistry = class {
|
|
|
863
3123
|
function namespaceOf(customId) {
|
|
864
3124
|
return parseCustomId(customId).namespace;
|
|
865
3125
|
}
|
|
3126
|
+
function combineGuards4(defaults, own) {
|
|
3127
|
+
if (own === void 0 || own.length === 0) return defaults;
|
|
3128
|
+
if (defaults.length === 0) return own;
|
|
3129
|
+
return [...defaults, ...own];
|
|
3130
|
+
}
|
|
3131
|
+
function clientEmbeds5(client) {
|
|
3132
|
+
return client.embeds ?? defaultEmbeds;
|
|
3133
|
+
}
|
|
3134
|
+
async function replyDeniedComponent(interaction, reason) {
|
|
3135
|
+
const embeds = clientEmbeds5(interaction.client);
|
|
3136
|
+
const text = reason ?? "You don't have permission to use this.";
|
|
3137
|
+
try {
|
|
3138
|
+
const payload = { embeds: [embeds.error(text)], flags: MessageFlags.Ephemeral };
|
|
3139
|
+
if (interaction.deferred) await interaction.editReply({ embeds: payload.embeds });
|
|
3140
|
+
else if (interaction.replied) await interaction.followUp(payload);
|
|
3141
|
+
else await interaction.reply(payload);
|
|
3142
|
+
} catch {
|
|
3143
|
+
}
|
|
3144
|
+
}
|
|
866
3145
|
function resolveButtonStyle(input) {
|
|
867
3146
|
if (input === void 0) return ButtonStyle.Secondary;
|
|
868
3147
|
return typeof input === "number" ? input : ButtonStyle[input];
|
|
@@ -874,6 +3153,7 @@ function button(config) {
|
|
|
874
3153
|
kind: "button",
|
|
875
3154
|
namespace: compiled.namespace,
|
|
876
3155
|
paramNames: compiled.paramNames,
|
|
3156
|
+
guards: config.guards,
|
|
877
3157
|
async handle(interaction, params) {
|
|
878
3158
|
await config.run(new ButtonContext(interaction, params));
|
|
879
3159
|
},
|
|
@@ -906,6 +3186,7 @@ function stringSelect(config) {
|
|
|
906
3186
|
kind: "stringSelect",
|
|
907
3187
|
namespace: compiled.namespace,
|
|
908
3188
|
paramNames: compiled.paramNames,
|
|
3189
|
+
guards: config.guards,
|
|
909
3190
|
async handle(interaction, params) {
|
|
910
3191
|
await config.run(new StringSelectContext(interaction, params));
|
|
911
3192
|
},
|
|
@@ -923,6 +3204,7 @@ function userSelect(config) {
|
|
|
923
3204
|
kind: "userSelect",
|
|
924
3205
|
namespace: compiled.namespace,
|
|
925
3206
|
paramNames: compiled.paramNames,
|
|
3207
|
+
guards: config.guards,
|
|
926
3208
|
async handle(interaction, params) {
|
|
927
3209
|
await config.run(new UserSelectContext(interaction, params));
|
|
928
3210
|
},
|
|
@@ -940,6 +3222,7 @@ function roleSelect(config) {
|
|
|
940
3222
|
kind: "roleSelect",
|
|
941
3223
|
namespace: compiled.namespace,
|
|
942
3224
|
paramNames: compiled.paramNames,
|
|
3225
|
+
guards: config.guards,
|
|
943
3226
|
async handle(interaction, params) {
|
|
944
3227
|
await config.run(new RoleSelectContext(interaction, params));
|
|
945
3228
|
},
|
|
@@ -957,6 +3240,7 @@ function channelSelect(config) {
|
|
|
957
3240
|
kind: "channelSelect",
|
|
958
3241
|
namespace: compiled.namespace,
|
|
959
3242
|
paramNames: compiled.paramNames,
|
|
3243
|
+
guards: config.guards,
|
|
960
3244
|
async handle(interaction, params) {
|
|
961
3245
|
await config.run(new ChannelSelectContext(interaction, params));
|
|
962
3246
|
},
|
|
@@ -975,6 +3259,7 @@ function mentionableSelect(config) {
|
|
|
975
3259
|
kind: "mentionableSelect",
|
|
976
3260
|
namespace: compiled.namespace,
|
|
977
3261
|
paramNames: compiled.paramNames,
|
|
3262
|
+
guards: config.guards,
|
|
978
3263
|
async handle(interaction, params) {
|
|
979
3264
|
await config.run(new MentionableSelectContext(interaction, params));
|
|
980
3265
|
},
|
|
@@ -1017,6 +3302,7 @@ function modal(config) {
|
|
|
1017
3302
|
kind: "modal",
|
|
1018
3303
|
namespace: compiled.namespace,
|
|
1019
3304
|
paramNames: compiled.paramNames,
|
|
3305
|
+
guards: config.guards,
|
|
1020
3306
|
async handle(interaction, params) {
|
|
1021
3307
|
const fields = {};
|
|
1022
3308
|
for (const key of fieldKeys) {
|
|
@@ -1056,6 +3342,9 @@ function isRegisterable(value) {
|
|
|
1056
3342
|
if (typeof record["kind"] === "string" && typeof record["handle"] === "function") {
|
|
1057
3343
|
return true;
|
|
1058
3344
|
}
|
|
3345
|
+
if ((record["kind"] === "task" || record["kind"] === "prefixCommand") && typeof record["run"] === "function") {
|
|
3346
|
+
return true;
|
|
3347
|
+
}
|
|
1059
3348
|
return false;
|
|
1060
3349
|
}
|
|
1061
3350
|
async function collectModules(dir, options = {}) {
|
|
@@ -1110,15 +3399,64 @@ var SpearClient = class extends Client {
|
|
|
1110
3399
|
events = new EventRegistry();
|
|
1111
3400
|
/** Button / select / modal registry and router. */
|
|
1112
3401
|
components = new ComponentRegistry();
|
|
3402
|
+
/** Structured logger shared across spearkit and available to your code. */
|
|
3403
|
+
logger;
|
|
3404
|
+
/** Shared cooldown manager used by command dispatch; also usable directly. */
|
|
3405
|
+
cooldowns = new CooldownManager();
|
|
3406
|
+
/** Cron/interval task scheduler; started on ready and stopped on destroy. */
|
|
3407
|
+
scheduler = new TaskScheduler();
|
|
3408
|
+
/** Prefix (text) command registry, dispatched from `messageCreate`. */
|
|
3409
|
+
prefix = new PrefixRegistry();
|
|
3410
|
+
/** Usage tracker: records who used what to a store and/or a Discord channel. */
|
|
3411
|
+
usage = new UsageTracker();
|
|
3412
|
+
/** Preset embed factory used by `ctx.error/success/info/warn` and available to your code. */
|
|
3413
|
+
embeds;
|
|
3414
|
+
/** User- and message-context-menu command registry. */
|
|
3415
|
+
contextMenus = new ContextMenuRegistry();
|
|
3416
|
+
envConfig;
|
|
1113
3417
|
constructor(options = {}) {
|
|
1114
|
-
const { intents, ...rest } = options;
|
|
3418
|
+
const { intents, logger, dotenv, cooldown, prefix, usage, embeds, guards, ...rest } = options;
|
|
1115
3419
|
super({ ...rest, intents: intents ?? Intents.default });
|
|
3420
|
+
this.embeds = embeds instanceof Embeds ? embeds : new Embeds(embeds);
|
|
3421
|
+
this.envConfig = dotenv === false ? false : dotenv === void 0 || dotenv === true ? {} : dotenv;
|
|
3422
|
+
this.logger = logger instanceof Logger ? logger : new Logger(logger);
|
|
3423
|
+
const defaultCooldown = cooldown !== void 0 ? normalizeCooldown(cooldown) : void 0;
|
|
3424
|
+
this.commands.setLogger(this.logger.child("commands"));
|
|
3425
|
+
this.commands.setCooldowns(this.cooldowns, defaultCooldown);
|
|
3426
|
+
this.components.setLogger(this.logger.child("components"));
|
|
3427
|
+
this.contextMenus.setLogger(this.logger.child("contextMenus"));
|
|
3428
|
+
this.contextMenus.setCooldowns(this.cooldowns, defaultCooldown);
|
|
3429
|
+
this.prefix.setLogger(this.logger.child("prefix"));
|
|
3430
|
+
this.prefix.setCooldowns(this.cooldowns, defaultCooldown);
|
|
3431
|
+
if (prefix !== void 0) this.prefix.setOptions(prefix);
|
|
3432
|
+
this.scheduler.setLogger(this.logger.child("scheduler"));
|
|
3433
|
+
if (guards !== void 0 && guards.length > 0) {
|
|
3434
|
+
this.commands.setDefaultGuards(guards);
|
|
3435
|
+
this.contextMenus.setDefaultGuards(guards);
|
|
3436
|
+
this.components.setDefaultGuards(guards);
|
|
3437
|
+
this.prefix.setDefaultGuards(guards);
|
|
3438
|
+
}
|
|
3439
|
+
this.usage.setClient(this).setLogger(this.logger.child("usage"));
|
|
3440
|
+
if (usage !== void 0) {
|
|
3441
|
+
if (usage.store !== void 0) this.usage.setStore(usage.store);
|
|
3442
|
+
if (usage.channel !== void 0) this.usage.reportTo(usage.channel, usage.format);
|
|
3443
|
+
const onUsage = (event2) => this.usage.track(event2);
|
|
3444
|
+
this.commands.setUsageHook(onUsage);
|
|
3445
|
+
this.contextMenus.setUsageHook(onUsage);
|
|
3446
|
+
this.components.setUsageHook(onUsage);
|
|
3447
|
+
this.prefix.setUsageHook(onUsage);
|
|
3448
|
+
}
|
|
1116
3449
|
this.events.attachAll(this);
|
|
1117
3450
|
this.on("interactionCreate", (interaction) => this.route(interaction));
|
|
3451
|
+
this.on("error", (error) => this.logger.error("client error", { error: toError(error) }));
|
|
3452
|
+
this.once("clientReady", () => this.scheduler.start(this));
|
|
3453
|
+
this.on("messageCreate", (message) => {
|
|
3454
|
+
void this.prefix.handle(message);
|
|
3455
|
+
});
|
|
1118
3456
|
}
|
|
1119
3457
|
/**
|
|
1120
|
-
* Register commands, events
|
|
1121
|
-
*
|
|
3458
|
+
* Register commands, events, components, scheduled tasks, prefix commands
|
|
3459
|
+
* and context menus in one call. Each item is routed to its matching registry.
|
|
1122
3460
|
*/
|
|
1123
3461
|
register(...items) {
|
|
1124
3462
|
for (const item of items) {
|
|
@@ -1126,6 +3464,14 @@ var SpearClient = class extends Client {
|
|
|
1126
3464
|
this.commands.add(item);
|
|
1127
3465
|
} else if ("attach" in item) {
|
|
1128
3466
|
this.events.add(item);
|
|
3467
|
+
} else if (item.kind === "task") {
|
|
3468
|
+
this.scheduler.add(item);
|
|
3469
|
+
} else if (item.kind === "prefixCommand") {
|
|
3470
|
+
this.prefix.add(item);
|
|
3471
|
+
} else if (item.kind === "userMenu") {
|
|
3472
|
+
this.contextMenus.add(item);
|
|
3473
|
+
} else if (item.kind === "messageMenu") {
|
|
3474
|
+
this.contextMenus.add(item);
|
|
1129
3475
|
} else {
|
|
1130
3476
|
this.components.add(item);
|
|
1131
3477
|
}
|
|
@@ -1151,6 +3497,7 @@ var SpearClient = class extends Client {
|
|
|
1151
3497
|
* token is passed.
|
|
1152
3498
|
*/
|
|
1153
3499
|
async start(token) {
|
|
3500
|
+
if (this.envConfig !== false) loadEnv(this.envConfig);
|
|
1154
3501
|
const resolved = token ?? process.env.DISCORD_TOKEN;
|
|
1155
3502
|
if (resolved === void 0 || resolved.length === 0) {
|
|
1156
3503
|
throw new Error("spearkit: start() needs a token (pass one or set DISCORD_TOKEN)");
|
|
@@ -1159,8 +3506,9 @@ var SpearClient = class extends Client {
|
|
|
1159
3506
|
return this;
|
|
1160
3507
|
}
|
|
1161
3508
|
/**
|
|
1162
|
-
* Push the registered slash commands to
|
|
1163
|
-
*
|
|
3509
|
+
* Push the registered slash commands to Discord using the client's REST
|
|
3510
|
+
* connection. Slash-only — use {@link deployAllCommands} to include context
|
|
3511
|
+
* menus in the same request.
|
|
1164
3512
|
*/
|
|
1165
3513
|
async deployCommands(options = {}) {
|
|
1166
3514
|
const applicationId = this.application?.id ?? this.user?.id;
|
|
@@ -1169,22 +3517,108 @@ var SpearClient = class extends Client {
|
|
|
1169
3517
|
}
|
|
1170
3518
|
return this.commands.deploy({ rest: this.rest, applicationId, guildId: options.guildId });
|
|
1171
3519
|
}
|
|
3520
|
+
/**
|
|
3521
|
+
* Deploy slash commands AND context menus together to Discord in a single
|
|
3522
|
+
* PUT. Use this once you mix `userCommand` / `messageCommand` with `command`.
|
|
3523
|
+
*/
|
|
3524
|
+
/**
|
|
3525
|
+
* Deploy slash commands AND context menus together. Supports a `diff`
|
|
3526
|
+
* strategy that fetches the remote set first and skips the PUT when
|
|
3527
|
+
* nothing changed, and a `dryRun` flag that returns the body without
|
|
3528
|
+
* touching Discord (perfect for CI deploy gates).
|
|
3529
|
+
*
|
|
3530
|
+
* @returns the API's DeployResult on PUT, or a skipped report when
|
|
3531
|
+
* `dryRun: true` is set OR `strategy: "diff"` finds no changes.
|
|
3532
|
+
*/
|
|
3533
|
+
async deployAllCommands(options = {}) {
|
|
3534
|
+
const applicationId = options.applicationId ?? this.application?.id ?? this.user?.id;
|
|
3535
|
+
if (applicationId == null) {
|
|
3536
|
+
throw new Error("spearkit: deployAllCommands() must run after the client is ready");
|
|
3537
|
+
}
|
|
3538
|
+
const body = [...this.commands.toJSON(), ...this.contextMenus.toJSON()];
|
|
3539
|
+
const route = options.guildId !== void 0 ? Routes.applicationGuildCommands(applicationId, options.guildId) : Routes.applicationCommands(applicationId);
|
|
3540
|
+
if (options.dryRun === true) {
|
|
3541
|
+
return { skipped: true, reason: "dry-run", body };
|
|
3542
|
+
}
|
|
3543
|
+
if (options.strategy === "diff") {
|
|
3544
|
+
const remote = await this.rest.get(route);
|
|
3545
|
+
if (commandsEqual(body, remote)) {
|
|
3546
|
+
return { skipped: true, reason: "no-changes", body };
|
|
3547
|
+
}
|
|
3548
|
+
}
|
|
3549
|
+
return await this.rest.put(route, { body });
|
|
3550
|
+
}
|
|
3551
|
+
/** Define and register a scheduled task in one call. */
|
|
3552
|
+
schedule(config) {
|
|
3553
|
+
const scheduled = task(config);
|
|
3554
|
+
this.scheduler.add(scheduled);
|
|
3555
|
+
return scheduled;
|
|
3556
|
+
}
|
|
3557
|
+
/** Stop the scheduler, then tear down the discord.js client. */
|
|
3558
|
+
async destroy() {
|
|
3559
|
+
this.scheduler.stop();
|
|
3560
|
+
await super.destroy();
|
|
3561
|
+
}
|
|
1172
3562
|
async route(interaction) {
|
|
1173
3563
|
if (interaction.isChatInputCommand()) {
|
|
1174
3564
|
await this.commands.handle(interaction);
|
|
1175
3565
|
} else if (interaction.isAutocomplete()) {
|
|
1176
3566
|
await this.commands.handleAutocomplete(interaction);
|
|
3567
|
+
} else if (interaction.isUserContextMenuCommand()) {
|
|
3568
|
+
await this.contextMenus.handleUser(interaction);
|
|
3569
|
+
} else if (interaction.isMessageContextMenuCommand()) {
|
|
3570
|
+
await this.contextMenus.handleMessage(interaction);
|
|
1177
3571
|
} else {
|
|
1178
3572
|
await this.components.handle(interaction);
|
|
1179
3573
|
}
|
|
1180
3574
|
}
|
|
1181
3575
|
};
|
|
3576
|
+
function commandsEqual(local, remote) {
|
|
3577
|
+
if (local.length !== remote.length) return false;
|
|
3578
|
+
const lset = new Set(local.map(commandHash));
|
|
3579
|
+
for (const r of remote) {
|
|
3580
|
+
if (!lset.has(commandHash(r))) return false;
|
|
3581
|
+
}
|
|
3582
|
+
return true;
|
|
3583
|
+
}
|
|
3584
|
+
function commandHash(cmd) {
|
|
3585
|
+
const c = cmd;
|
|
3586
|
+
return JSON.stringify({
|
|
3587
|
+
name: c.name,
|
|
3588
|
+
type: c.type ?? 1,
|
|
3589
|
+
description: c.description ?? "",
|
|
3590
|
+
nsfw: c.nsfw === true,
|
|
3591
|
+
default_member_permissions: c.default_member_permissions ?? null,
|
|
3592
|
+
contexts: Array.isArray(c.contexts) ? [...c.contexts].sort((a, b) => a - b) : null,
|
|
3593
|
+
options: normaliseOptions(c.options)
|
|
3594
|
+
});
|
|
3595
|
+
}
|
|
3596
|
+
function normaliseOptions(options) {
|
|
3597
|
+
if (!Array.isArray(options)) return [];
|
|
3598
|
+
return options.map((o) => {
|
|
3599
|
+
const opt = o;
|
|
3600
|
+
return {
|
|
3601
|
+
name: opt.name,
|
|
3602
|
+
type: opt.type,
|
|
3603
|
+
description: opt.description ?? "",
|
|
3604
|
+
required: opt.required === true,
|
|
3605
|
+
choices: Array.isArray(opt.choices) ? [...opt.choices].map((ch) => ({ name: ch.name, value: ch.value })).sort((a, b) => String(a.name).localeCompare(String(b.name))) : null,
|
|
3606
|
+
options: normaliseOptions(opt.options),
|
|
3607
|
+
channel_types: Array.isArray(opt.channel_types) ? [...opt.channel_types].sort((a, b) => a - b) : null,
|
|
3608
|
+
min_value: opt.min_value ?? null,
|
|
3609
|
+
max_value: opt.max_value ?? null,
|
|
3610
|
+
min_length: opt.min_length ?? null,
|
|
3611
|
+
max_length: opt.max_length ?? null,
|
|
3612
|
+
autocomplete: opt.autocomplete === true
|
|
3613
|
+
};
|
|
3614
|
+
}).sort((a, b) => String(a.name).localeCompare(String(b.name)));
|
|
3615
|
+
}
|
|
1182
3616
|
|
|
1183
3617
|
// src/plugin.ts
|
|
1184
3618
|
function definePlugin(plugin) {
|
|
1185
3619
|
return plugin;
|
|
1186
3620
|
}
|
|
1187
3621
|
|
|
1188
|
-
export { AutocompleteContext, BaseContext, ButtonContext, ChannelSelectContext, CommandContext, CommandRegistry, ComponentRegistry, EventRegistry, Intents, MAX_CUSTOM_ID_LENGTH, MentionableSelectContext, MessageComponentContext, ModalContext, RoleSelectContext, SlashCommand, SpearClient, StringSelectContext, UserSelectContext, asEphemeral, buildCustomId, button, channelSelect, collectModules, command, commandGroup, compilePattern, definePlugin, event, linkButton, loadInto, mentionableSelect, modal, normalizeReply, option, optionsHaveAutocomplete, paramsFromValues, parseCustomId, readOption, roleSelect, row, stringSelect, subcommand, subcommandGroup, textInput, toAPIOption, userSelect };
|
|
3622
|
+
export { AutocompleteContext, BaseContext, ButtonContext, ChannelSelectContext, CommandContext, CommandRegistry, ComponentRegistry, ContextMenuRegistry, CooldownManager, CronExpression, DEFAULT_EMBED_COLORS, DEFAULT_EMBED_ICONS, Embeds, EventRegistry, Intents, JsonFileUsageStore, KeyedLock, Logger, MAX_CUSTOM_ID_LENGTH, MemoryCache, MemoryUsageStore, MentionableSelectContext, MessageComponentContext, MessageContextMenuContext, ModalContext, PrefixArgsBuilder, PrefixContext, PrefixRegistry, RoleSelectContext, SlashCommand, SpearClient, StringSelectContext, TaskScheduler, UsageTracker, UserContextMenuContext, UserSelectContext, asEphemeral, buildCustomId, buildPaginatorPage, button, channelSelect, collectModules, command, commandGroup, compilePattern, confirm, consoleSink, createCache, cron, defaultEmbeds, definePlugin, denied, discordTimestamp, dmOnly, effectiveDuration, env, event, fetchChannel, fetchGuild, fetchMember, fetchMessage, fetchRole, fetchUser, formatCooldownMessage, formatDuration, formatUsage, guard, guildOnly, jsonlSink, linkButton, loadConfig, loadConfigAsync, loadEnv, loadInto, lookup, lookupOptional, mentionableSelect, messageCommand, modal, normalizeCooldown, normalizeReply, option, optionsHaveAutocomplete, paginate, paramsFromValues, parseCustomId, parseDuration, parseEnv, prefixArgs, prefixCommand, readOption, relativeTimestamp, requireAllRoles, requireAnyRole, requireBotPermissions, requireOwner, requireUserPermissions, roleSelect, row, runGuards, safeFetch, safeTry, stringSelect, subcommand, subcommandGroup, task, textInput, toAPIOption, toError, userCommand, userSelect, webhookSink, withSafeTimeout };
|
|
1189
3623
|
//# sourceMappingURL=index.js.map
|
|
1190
3624
|
//# sourceMappingURL=index.js.map
|