wumbly 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +275 -2
  3. package/dist/client.cjs +1437 -0
  4. package/dist/client.cjs.map +1 -0
  5. package/dist/client.d.cts +3 -0
  6. package/dist/client.d.ts +3 -0
  7. package/dist/client.js +1400 -0
  8. package/dist/client.js.map +1 -0
  9. package/dist/commands.cjs +244 -0
  10. package/dist/commands.cjs.map +1 -0
  11. package/dist/commands.d.cts +3 -0
  12. package/dist/commands.d.ts +3 -0
  13. package/dist/commands.js +209 -0
  14. package/dist/commands.js.map +1 -0
  15. package/dist/events.cjs +133 -0
  16. package/dist/events.cjs.map +1 -0
  17. package/dist/events.d.cts +3 -0
  18. package/dist/events.d.ts +3 -0
  19. package/dist/events.js +97 -0
  20. package/dist/events.js.map +1 -0
  21. package/dist/index-0P9mmVy0.d.cts +597 -0
  22. package/dist/index-CR7RtVXn.d.ts +597 -0
  23. package/dist/index.cjs +1578 -0
  24. package/dist/index.cjs.map +1 -0
  25. package/dist/index.d.cts +77 -0
  26. package/dist/index.d.ts +77 -0
  27. package/dist/index.js +1494 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/loader.cjs +208 -0
  30. package/dist/loader.cjs.map +1 -0
  31. package/dist/loader.d.cts +3 -0
  32. package/dist/loader.d.ts +3 -0
  33. package/dist/loader.js +178 -0
  34. package/dist/loader.js.map +1 -0
  35. package/dist/permissions.cjs +250 -0
  36. package/dist/permissions.cjs.map +1 -0
  37. package/dist/permissions.d.cts +135 -0
  38. package/dist/permissions.d.ts +135 -0
  39. package/dist/permissions.js +214 -0
  40. package/dist/permissions.js.map +1 -0
  41. package/dist/voice.cjs +125 -0
  42. package/dist/voice.cjs.map +1 -0
  43. package/dist/voice.d.cts +3 -0
  44. package/dist/voice.d.ts +3 -0
  45. package/dist/voice.js +97 -0
  46. package/dist/voice.js.map +1 -0
  47. package/package.json +81 -4
package/dist/index.cjs ADDED
@@ -0,0 +1,1578 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ ALL_PERMISSIONS: () => ALL_PERMISSIONS,
34
+ COMMAND_BRAND: () => COMMAND_BRAND,
35
+ Client: () => Client,
36
+ Command: () => Command,
37
+ CommandStore: () => CommandStore,
38
+ CooldownStore: () => CooldownStore,
39
+ EVENT_BRAND: () => EVENT_BRAND,
40
+ Event: () => Event,
41
+ EventStore: () => EventStore,
42
+ Events: () => Events,
43
+ Gateway: () => Gateway,
44
+ GatewayOpcodes: () => GatewayOpcodes,
45
+ LISTENER_BRAND: () => LISTENER_BRAND,
46
+ Listener: () => Listener,
47
+ ListenerStore: () => ListenerStore,
48
+ Middleware: () => Middleware,
49
+ ModuleLoadError: () => ModuleLoadError,
50
+ OverwriteType: () => OverwriteType,
51
+ PermissionFlags: () => PermissionFlags,
52
+ Permissions: () => Permissions,
53
+ PlatformClient: () => PlatformClient,
54
+ RestClient: () => RestClient,
55
+ VoiceManager: () => VoiceManager,
56
+ VoiceUnavailableError: () => VoiceUnavailableError,
57
+ collectFiles: () => collectFiles,
58
+ computePermissions: () => computePermissions,
59
+ createCommand: () => createCommand,
60
+ createCommandContext: () => createCommandContext,
61
+ createEvent: () => createEvent,
62
+ createListener: () => createListener,
63
+ createMiddleware: () => createMiddleware,
64
+ defaultExtensions: () => defaultExtensions,
65
+ formatDuration: () => formatDuration,
66
+ hasAnyPermission: () => hasAnyPermission,
67
+ hasPermission: () => hasPermission,
68
+ isBun: () => isBun,
69
+ isCommand: () => isCommand,
70
+ isEvent: () => isEvent,
71
+ isListener: () => isListener,
72
+ loadDirectory: () => loadDirectory,
73
+ loadFile: () => loadFile,
74
+ memberRoleIds: () => memberRoleIds,
75
+ normalizeOverwrite: () => normalizeOverwrite,
76
+ readOverwrites: () => readOverwrites,
77
+ resolvePermission: () => resolvePermission,
78
+ resolvePermissions: () => resolvePermissions,
79
+ runtimeName: () => runtimeName,
80
+ tokenize: () => tokenize
81
+ });
82
+ module.exports = __toCommonJS(src_exports);
83
+
84
+ // src/commands/types.ts
85
+ var COMMAND_BRAND = /* @__PURE__ */ Symbol.for("wumbly.command");
86
+
87
+ // src/commands/command.ts
88
+ function normalizeCooldown(cooldown) {
89
+ if (cooldown === void 0) return null;
90
+ const value = typeof cooldown === "number" ? { limit: 1, window: cooldown, scope: "user" } : { ...cooldown };
91
+ if (!Number.isFinite(value.limit) || value.limit <= 0) {
92
+ throw new TypeError("cooldown.limit must be a positive number");
93
+ }
94
+ if (!Number.isFinite(value.window) || value.window <= 0) {
95
+ throw new TypeError("cooldown.window must be a positive number");
96
+ }
97
+ return Object.freeze({
98
+ limit: Math.floor(value.limit),
99
+ window: Math.floor(value.window),
100
+ scope: value.scope ?? "user"
101
+ });
102
+ }
103
+ var Command = class {
104
+ [COMMAND_BRAND] = true;
105
+ name;
106
+ description;
107
+ aliases;
108
+ category;
109
+ guildOnly;
110
+ ownerOnly;
111
+ cooldown;
112
+ middlewares;
113
+ run;
114
+ constructor(options) {
115
+ const name = options.name.trim();
116
+ if (!name) throw new TypeError("Command name is required");
117
+ if (/\s/.test(name)) throw new TypeError("Command names cannot contain whitespace");
118
+ this.name = name;
119
+ this.description = options.description ?? "";
120
+ this.aliases = Object.freeze([...new Set(options.aliases ?? [])]);
121
+ this.category = options.category ?? null;
122
+ this.guildOnly = options.guildOnly ?? false;
123
+ this.ownerOnly = options.ownerOnly ?? false;
124
+ this.cooldown = normalizeCooldown(options.cooldown);
125
+ this.middlewares = Object.freeze([...options.middlewares ?? []]);
126
+ this.run = options.run;
127
+ Object.freeze(this);
128
+ }
129
+ };
130
+ function isCommand(value) {
131
+ return typeof value === "object" && value !== null && value[COMMAND_BRAND] === true;
132
+ }
133
+ function createCommandContext(client, message, command, args, input) {
134
+ const frozenArgs = Object.freeze([...args]);
135
+ return {
136
+ client,
137
+ message,
138
+ command,
139
+ author: message.author,
140
+ args: frozenArgs,
141
+ input,
142
+ get rest() {
143
+ return frozenArgs.join(" ");
144
+ },
145
+ get channel() {
146
+ return message.channel ?? null;
147
+ },
148
+ get guild() {
149
+ return message.guild ?? null;
150
+ },
151
+ get member() {
152
+ return message.member ?? null;
153
+ },
154
+ reply(options) {
155
+ return message.reply(options);
156
+ },
157
+ send(options) {
158
+ const channel = message.channel;
159
+ if (!channel?.send) {
160
+ return Promise.reject(new Error("The message has no text-based channel"));
161
+ }
162
+ return channel.send(options);
163
+ }
164
+ };
165
+ }
166
+ function createCommand(options) {
167
+ return new Command(options);
168
+ }
169
+
170
+ // src/commands/cooldown.ts
171
+ function scopeKey(ctx, scope) {
172
+ switch (scope) {
173
+ case "user":
174
+ return ctx.author.id;
175
+ case "guild":
176
+ return ctx.message.guildId ?? "dm";
177
+ case "channel":
178
+ return ctx.message.channelId ?? "unknown";
179
+ case "global":
180
+ return "*";
181
+ }
182
+ }
183
+ var CooldownStore = class {
184
+ buckets = /* @__PURE__ */ new Map();
185
+ /** Register a use, or report how long the caller has to wait. */
186
+ consume(command, ctx) {
187
+ const cooldown = command.cooldown;
188
+ if (!cooldown) return { ok: true };
189
+ const key = `${command.name}:${cooldown.scope ?? "user"}:${scopeKey(
190
+ ctx,
191
+ cooldown.scope ?? "user"
192
+ )}`;
193
+ const now = Date.now();
194
+ const windowStart = now - cooldown.window;
195
+ const hits = (this.buckets.get(key) ?? []).filter((time) => time > windowStart);
196
+ if (hits.length >= cooldown.limit) {
197
+ const oldest = hits[0] ?? now;
198
+ this.buckets.set(key, hits);
199
+ return {
200
+ ok: false,
201
+ retryAfter: Math.max(0, oldest + cooldown.window - now)
202
+ };
203
+ }
204
+ hits.push(now);
205
+ this.buckets.set(key, hits);
206
+ return { ok: true };
207
+ }
208
+ clear() {
209
+ this.buckets.clear();
210
+ }
211
+ };
212
+
213
+ // src/commands/middleware.ts
214
+ var Middleware = class {
215
+ name;
216
+ run;
217
+ constructor(options) {
218
+ this.name = options.name ?? null;
219
+ this.run = options.run;
220
+ Object.freeze(this);
221
+ }
222
+ };
223
+ function createMiddleware(options) {
224
+ return new Middleware(options);
225
+ }
226
+
227
+ // src/commands/store.ts
228
+ function assertFree(key, command, names, aliases) {
229
+ const existing = names.get(key) ?? aliases.get(key);
230
+ if (existing && existing !== command) {
231
+ throw new Error(`Command key "${key}" is already used by "${existing.name}"`);
232
+ }
233
+ }
234
+ var CommandStore = class {
235
+ byName = /* @__PURE__ */ new Map();
236
+ byAlias = /* @__PURE__ */ new Map();
237
+ /** Register one command. Throws if its name or an alias is already taken. */
238
+ add(command) {
239
+ this.addMany([command]);
240
+ }
241
+ /** Register several commands, validating every key before committing. */
242
+ addMany(commands) {
243
+ const names = new Map(this.byName);
244
+ const aliases = new Map(this.byAlias);
245
+ for (const command of commands) {
246
+ const nameKey = command.name.toLowerCase();
247
+ assertFree(nameKey, command, names, aliases);
248
+ names.set(nameKey, command);
249
+ const localAliases = /* @__PURE__ */ new Set();
250
+ for (const alias of command.aliases) {
251
+ const aliasKey = alias.toLowerCase();
252
+ if (!aliasKey || aliasKey === nameKey || localAliases.has(aliasKey)) continue;
253
+ assertFree(aliasKey, command, names, aliases);
254
+ localAliases.add(aliasKey);
255
+ aliases.set(aliasKey, command);
256
+ }
257
+ }
258
+ this.byName = names;
259
+ this.byAlias = aliases;
260
+ }
261
+ /** Find a command by name or alias. */
262
+ get(name) {
263
+ const key = name.toLowerCase();
264
+ return this.byName.get(key) ?? this.byAlias.get(key) ?? null;
265
+ }
266
+ has(name) {
267
+ return this.get(name) !== null;
268
+ }
269
+ /** All registered commands, in insertion order. */
270
+ list() {
271
+ return [...this.byName.values()];
272
+ }
273
+ get size() {
274
+ return this.byName.size;
275
+ }
276
+ clear() {
277
+ this.byName.clear();
278
+ this.byAlias.clear();
279
+ }
280
+ };
281
+
282
+ // src/events/event.ts
283
+ var EVENT_BRAND = /* @__PURE__ */ Symbol.for("wumbly.event");
284
+ var Event = class {
285
+ [EVENT_BRAND] = true;
286
+ event;
287
+ once;
288
+ run;
289
+ constructor(input) {
290
+ if (!input.event) throw new TypeError("Event name is required");
291
+ this.event = input.event;
292
+ this.once = input.once ?? false;
293
+ this.run = input.run;
294
+ Object.freeze(this);
295
+ }
296
+ };
297
+ function isEvent(value) {
298
+ return typeof value === "object" && value !== null && value[EVENT_BRAND] === true;
299
+ }
300
+ function createEvent(input) {
301
+ return new Event(input);
302
+ }
303
+ function createListener(input) {
304
+ return new Event(input);
305
+ }
306
+ var LISTENER_BRAND = EVENT_BRAND;
307
+ var Listener = Event;
308
+ function isListener(value) {
309
+ return isEvent(value);
310
+ }
311
+
312
+ // src/events/event-store.ts
313
+ var EventStore = class {
314
+ items = /* @__PURE__ */ new Set();
315
+ handlers = /* @__PURE__ */ new Map();
316
+ add(event) {
317
+ this.items.add(event);
318
+ }
319
+ addMany(events) {
320
+ for (const event of events) this.add(event);
321
+ }
322
+ list() {
323
+ return [...this.items];
324
+ }
325
+ get size() {
326
+ return this.items.size;
327
+ }
328
+ /** Attach a event if it has not been attached yet. */
329
+ attachOne(client, event) {
330
+ if (this.handlers.has(event)) return;
331
+ const handler = (...args) => {
332
+ try {
333
+ Promise.resolve(
334
+ event.run(client, ...args)
335
+ ).catch((error) => {
336
+ void client.handleEventError(error, event, args);
337
+ });
338
+ } catch (error) {
339
+ void client.handleEventError(error, event, args);
340
+ }
341
+ };
342
+ if (event.once) {
343
+ client.once(event.event, handler);
344
+ } else {
345
+ client.on(event.event, handler);
346
+ }
347
+ this.handlers.set(event, handler);
348
+ }
349
+ /** Attach every known event. */
350
+ attach(client) {
351
+ for (const event of this.items) this.attachOne(client, event);
352
+ }
353
+ /** Remove every attached handler from the client. */
354
+ detach(client) {
355
+ for (const [event, handler] of this.handlers) {
356
+ client.off(event.event, handler);
357
+ }
358
+ this.handlers.clear();
359
+ }
360
+ clear() {
361
+ this.items.clear();
362
+ this.handlers.clear();
363
+ }
364
+ };
365
+ var ListenerStore = EventStore;
366
+
367
+ // src/loaders/files.ts
368
+ var import_promises = require("fs/promises");
369
+ var import_node_path = require("path");
370
+
371
+ // src/runtime/environment.ts
372
+ var runtime = globalThis;
373
+ var isBun = typeof runtime.Bun !== "undefined";
374
+ var runtimeName = isBun ? "bun" : "node";
375
+ var defaultExtensions = Object.freeze(
376
+ isBun ? [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"] : [".js", ".mjs", ".cjs"]
377
+ );
378
+
379
+ // src/loaders/files.ts
380
+ function isDeclarationFile(name) {
381
+ return /\.d\.[cm]?ts$/.test(name);
382
+ }
383
+ async function collectFiles(directory, options = {}) {
384
+ const root = (0, import_node_path.resolve)(directory);
385
+ const extensions = new Set(options.extensions ?? defaultExtensions);
386
+ const ignored = new Set(options.ignore ?? []);
387
+ const files = [];
388
+ async function walk(current) {
389
+ const entries = await (0, import_promises.readdir)(current, { withFileTypes: true });
390
+ for (const entry of entries) {
391
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
392
+ if (ignored.has(entry.name)) continue;
393
+ const fullPath = (0, import_node_path.resolve)(current, entry.name);
394
+ if (entry.isDirectory()) {
395
+ await walk(fullPath);
396
+ continue;
397
+ }
398
+ if (!entry.isFile() || entry.isSymbolicLink()) continue;
399
+ if (isDeclarationFile(entry.name)) continue;
400
+ if (extensions.has((0, import_node_path.extname)(entry.name))) files.push(fullPath);
401
+ }
402
+ }
403
+ await walk(root);
404
+ return files.sort();
405
+ }
406
+
407
+ // src/loaders/load.ts
408
+ var import_node_url = require("url");
409
+ var ModuleLoadError = class extends Error {
410
+ file;
411
+ constructor(file, cause) {
412
+ super(`Could not load module: ${file}`, { cause });
413
+ this.name = "ModuleLoadError";
414
+ this.file = file;
415
+ }
416
+ };
417
+ var importCounter = 0;
418
+ function flatten(value, output, seen) {
419
+ if (Array.isArray(value)) {
420
+ for (const item of value) flatten(item, output, seen);
421
+ return;
422
+ }
423
+ if (value === null || value === void 0 || seen.has(value)) return;
424
+ seen.add(value);
425
+ output.push(value);
426
+ }
427
+ function extractExports(module2) {
428
+ const values = [];
429
+ const seen = /* @__PURE__ */ new Set();
430
+ for (const value of Object.values(module2)) {
431
+ flatten(value, values, seen);
432
+ }
433
+ const commands = [];
434
+ const events = [];
435
+ for (const value of values) {
436
+ if (isCommand(value)) commands.push(value);
437
+ else if (isEvent(value)) events.push(value);
438
+ }
439
+ return { commands, events };
440
+ }
441
+ async function importFile(file, options) {
442
+ const url = (0, import_node_url.pathToFileURL)(file);
443
+ if (options.cacheBust !== false) {
444
+ url.searchParams.set("wumbly", `${Date.now()}-${++importCounter}`);
445
+ }
446
+ let module2;
447
+ try {
448
+ module2 = await import(url.href);
449
+ } catch (error) {
450
+ throw new ModuleLoadError(file, error);
451
+ }
452
+ return extractExports(module2);
453
+ }
454
+ async function loadFile(file, options = {}) {
455
+ return importFile(file, options);
456
+ }
457
+ async function loadDirectory(directory, options = {}) {
458
+ const files = await collectFiles(directory, options);
459
+ const commands = [];
460
+ const events = [];
461
+ for (const file of files) {
462
+ const loaded = await importFile(file, options);
463
+ commands.push(...loaded.commands);
464
+ events.push(...loaded.events);
465
+ }
466
+ return { commands, events, files };
467
+ }
468
+
469
+ // src/platform/events.ts
470
+ var Events = {
471
+ Ready: "ready",
472
+ MessageCreate: "messageCreate",
473
+ MessageUpdate: "messageUpdate",
474
+ MessageDelete: "messageDelete",
475
+ GuildCreate: "guildCreate",
476
+ VoiceStateUpdate: "voiceStateUpdate",
477
+ VoiceServerUpdate: "voiceServerUpdate",
478
+ VoiceStateAck: "voiceStateAck",
479
+ VoiceStatesSync: "voiceStatesSync",
480
+ GuildDelete: "guildDelete"
481
+ };
482
+
483
+ // src/voice/manager.ts
484
+ var VoiceUnavailableError = class extends Error {
485
+ constructor() {
486
+ super(
487
+ "Voice is not enabled. Pass a provider to `new Client({ voice })` or call `client.voice.use(provider)`."
488
+ );
489
+ this.name = "VoiceUnavailableError";
490
+ }
491
+ };
492
+ var VoiceManager = class {
493
+ constructor(client, provider = null) {
494
+ this.client = client;
495
+ this.provider = provider;
496
+ }
497
+ client;
498
+ provider;
499
+ sessions = /* @__PURE__ */ new Map();
500
+ voiceStates = /* @__PURE__ */ new Map();
501
+ attached = false;
502
+ /** Start tracking gateway voice states for `getVoiceChannelId`. */
503
+ attach() {
504
+ if (this.attached) return this;
505
+ this.attached = true;
506
+ this.client.on(Events.VoiceStateUpdate, ((data) => {
507
+ const guildId = data.guild_id;
508
+ const userId = data.user_id;
509
+ if (!guildId || !userId) return;
510
+ let guild = this.voiceStates.get(guildId);
511
+ if (!guild) {
512
+ guild = /* @__PURE__ */ new Map();
513
+ this.voiceStates.set(guildId, guild);
514
+ }
515
+ guild.set(userId, data.channel_id ?? null);
516
+ }));
517
+ this.client.on(Events.VoiceStatesSync, ((data) => {
518
+ const guild = /* @__PURE__ */ new Map();
519
+ for (const state of data.voiceStates ?? []) {
520
+ if (state.user_id) guild.set(state.user_id, state.channel_id ?? null);
521
+ }
522
+ this.voiceStates.set(data.guildId, guild);
523
+ }));
524
+ return this;
525
+ }
526
+ getVoiceChannelId(guildId, userId) {
527
+ return this.voiceStates.get(guildId)?.get(userId) ?? null;
528
+ }
529
+ get available() {
530
+ return this.provider !== null;
531
+ }
532
+ use(provider) {
533
+ this.provider = provider;
534
+ return this;
535
+ }
536
+ get(channelId) {
537
+ return this.sessions.get(channelId) ?? null;
538
+ }
539
+ async join(channel) {
540
+ const existing = this.sessions.get(channel.id);
541
+ if (existing) return existing;
542
+ if (!this.provider) throw new VoiceUnavailableError();
543
+ const session = await this.provider.join(this.client, channel);
544
+ this.sessions.set(channel.id, session);
545
+ return session;
546
+ }
547
+ async leave(channelOrId) {
548
+ const channelId = typeof channelOrId === "string" ? channelOrId : channelOrId.id;
549
+ const session = this.sessions.get(channelId);
550
+ if (!session) return false;
551
+ this.sessions.delete(channelId);
552
+ await session.leave();
553
+ return true;
554
+ }
555
+ async leaveAll() {
556
+ const sessions = [...this.sessions.values()];
557
+ this.sessions.clear();
558
+ await Promise.allSettled(sessions.map((s) => s.leave()));
559
+ }
560
+ };
561
+
562
+ // src/platform/rest.ts
563
+ var RestClient = class {
564
+ token = null;
565
+ baseUrl;
566
+ constructor(options = {}) {
567
+ this.token = options.token ?? null;
568
+ this.baseUrl = options.baseUrl ?? "https://api.fluxer.app/v1";
569
+ }
570
+ setToken(token) {
571
+ this.token = token;
572
+ }
573
+ async request(method, path, body) {
574
+ const url = path.startsWith("http") ? path : `${this.baseUrl}${path.startsWith("/") ? "" : "/"}${path}`;
575
+ const headers = {};
576
+ if (this.token) headers.Authorization = `Bot ${this.token}`;
577
+ let payload;
578
+ if (body !== void 0) {
579
+ headers["Content-Type"] = "application/json";
580
+ payload = JSON.stringify(body);
581
+ }
582
+ const res = await fetch(url, { method, headers, body: payload });
583
+ if (res.status === 204) return void 0;
584
+ const text = await res.text();
585
+ const data = text ? JSON.parse(text) : void 0;
586
+ if (!res.ok) {
587
+ const err = new Error(data?.message ?? `HTTP ${res.status}`);
588
+ err.status = res.status;
589
+ err.data = data;
590
+ throw err;
591
+ }
592
+ return data;
593
+ }
594
+ get(path) {
595
+ return this.request("GET", path);
596
+ }
597
+ post(path, body) {
598
+ return this.request("POST", path, body);
599
+ }
600
+ patch(path, body) {
601
+ return this.request("PATCH", path, body);
602
+ }
603
+ put(path, body) {
604
+ return this.request("PUT", path, body);
605
+ }
606
+ delete(path, body) {
607
+ return this.request("DELETE", path, body);
608
+ }
609
+ };
610
+
611
+ // src/platform/gateway.ts
612
+ var import_node_events = require("events");
613
+ var ws = __toESM(require("ws"), 1);
614
+ var Gateway = class extends import_node_events.EventEmitter {
615
+ ws = null;
616
+ heartbeatTimer = null;
617
+ seq = null;
618
+ sessionId = null;
619
+ token;
620
+ url;
621
+ intents;
622
+ constructor(options) {
623
+ super();
624
+ this.token = options.token;
625
+ this.url = options.url ?? "wss://gateway.fluxer.app/?v=1&encoding=json";
626
+ this.intents = options.intents ?? 513;
627
+ }
628
+ connect() {
629
+ return new Promise((resolve3, reject) => {
630
+ const socket = new ws.WebSocket(this.url);
631
+ this.ws = socket;
632
+ socket.on("open", () => resolve3());
633
+ socket.on("error", (err) => {
634
+ this.emit("error", err);
635
+ reject(err);
636
+ });
637
+ socket.on("close", (code, reason) => {
638
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
639
+ this.emit("close", code, String(reason));
640
+ });
641
+ socket.on("message", (raw) => {
642
+ let payload;
643
+ try {
644
+ payload = JSON.parse(String(raw));
645
+ } catch {
646
+ return;
647
+ }
648
+ this.handlePayload(payload);
649
+ });
650
+ });
651
+ }
652
+ handlePayload(payload) {
653
+ const { op, d, s, t } = payload;
654
+ if (typeof s === "number") this.seq = s;
655
+ if (op === 10) {
656
+ const interval = d?.heartbeat_interval ?? 41250;
657
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
658
+ this.heartbeatTimer = setInterval(() => this.send({ op: 1, d: this.seq }), interval);
659
+ this.identify();
660
+ return;
661
+ }
662
+ if (op === 11) return;
663
+ if (op === 0) {
664
+ if (t === "READY") this.sessionId = d?.session_id ?? null;
665
+ this.emit("dispatch", t, d);
666
+ return;
667
+ }
668
+ if (op === 7 || op === 9) {
669
+ try {
670
+ this.ws?.close();
671
+ } catch {
672
+ }
673
+ return;
674
+ }
675
+ this.emit("packet", payload);
676
+ }
677
+ identify() {
678
+ this.send({
679
+ op: 2,
680
+ d: {
681
+ token: this.token,
682
+ intents: this.intents,
683
+ properties: { os: process.platform, browser: "wumbly", device: "wumbly" }
684
+ }
685
+ });
686
+ }
687
+ send(payload) {
688
+ if (this.ws?.readyState === ws.WebSocket.OPEN) {
689
+ this.ws.send(JSON.stringify(payload));
690
+ }
691
+ }
692
+ close() {
693
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
694
+ try {
695
+ this.ws?.close();
696
+ } catch {
697
+ }
698
+ this.ws = null;
699
+ }
700
+ };
701
+
702
+ // src/platform/permissions.ts
703
+ var PermissionFlags = {
704
+ CreateInstantInvite: 1n << 0n,
705
+ KickMembers: 1n << 1n,
706
+ BanMembers: 1n << 2n,
707
+ Administrator: 1n << 3n,
708
+ ManageChannels: 1n << 4n,
709
+ ManageGuild: 1n << 5n,
710
+ AddReactions: 1n << 6n,
711
+ ViewAuditLog: 1n << 7n,
712
+ PrioritySpeaker: 1n << 8n,
713
+ Stream: 1n << 9n,
714
+ ViewChannel: 1n << 10n,
715
+ SendMessages: 1n << 11n,
716
+ SendTtsMessages: 1n << 12n,
717
+ ManageMessages: 1n << 13n,
718
+ EmbedLinks: 1n << 14n,
719
+ AttachFiles: 1n << 15n,
720
+ ReadMessageHistory: 1n << 16n,
721
+ MentionEveryone: 1n << 17n,
722
+ UseExternalEmojis: 1n << 18n,
723
+ ViewGuildInsights: 1n << 19n,
724
+ Connect: 1n << 20n,
725
+ Speak: 1n << 21n,
726
+ MuteMembers: 1n << 22n,
727
+ DeafenMembers: 1n << 23n,
728
+ MoveMembers: 1n << 24n,
729
+ UseVad: 1n << 25n,
730
+ ChangeNickname: 1n << 26n,
731
+ ManageNicknames: 1n << 27n,
732
+ ManageRoles: 1n << 28n,
733
+ ManageWebhooks: 1n << 29n,
734
+ ManageGuildExpressions: 1n << 30n,
735
+ UseApplicationCommands: 1n << 31n,
736
+ RequestToSpeak: 1n << 32n,
737
+ ManageEvents: 1n << 33n,
738
+ ManageThreads: 1n << 34n,
739
+ CreatePublicThreads: 1n << 35n,
740
+ CreatePrivateThreads: 1n << 36n,
741
+ UseExternalStickers: 1n << 37n,
742
+ SendMessagesInThreads: 1n << 38n,
743
+ UseEmbeddedActivities: 1n << 39n,
744
+ ModerateMembers: 1n << 40n
745
+ };
746
+ var ALL_PERMISSIONS = (1n << 64n) - 1n;
747
+ var OverwriteType = {
748
+ Role: 0,
749
+ Member: 1
750
+ };
751
+ function resolvePermission(value) {
752
+ if (typeof value === "bigint") return value;
753
+ if (typeof value === "number") {
754
+ return Number.isFinite(value) ? BigInt(Math.trunc(value)) : 0n;
755
+ }
756
+ if (typeof value === "string") {
757
+ const trimmed = value.trim();
758
+ if (!trimmed) return 0n;
759
+ const named = PermissionFlags[trimmed];
760
+ if (named !== void 0) return named;
761
+ try {
762
+ return BigInt(trimmed);
763
+ } catch {
764
+ return 0n;
765
+ }
766
+ }
767
+ if (value instanceof Permissions) return value.bitfield;
768
+ return 0n;
769
+ }
770
+ function resolvePermissions(...values) {
771
+ let bitfield = 0n;
772
+ for (const value of values.flat()) bitfield |= resolvePermission(value);
773
+ return bitfield;
774
+ }
775
+ function hasPermission(bitfield, ...flags) {
776
+ const bits = resolvePermission(bitfield);
777
+ return flags.every((flag) => {
778
+ const required = resolvePermission(flag);
779
+ return (bits & required) === required;
780
+ });
781
+ }
782
+ function hasAnyPermission(bitfield, ...flags) {
783
+ const bits = resolvePermission(bitfield);
784
+ return flags.some((flag) => (bits & resolvePermission(flag)) !== 0n);
785
+ }
786
+ var Permissions = class {
787
+ bitfield;
788
+ constructor(value = 0n) {
789
+ this.bitfield = resolvePermission(value);
790
+ Object.freeze(this);
791
+ }
792
+ /** `true` when every given flag is present. */
793
+ has(...flags) {
794
+ return hasPermission(this.bitfield, ...flags);
795
+ }
796
+ /** `true` when at least one of the given flags is present. */
797
+ any(...flags) {
798
+ return hasAnyPermission(this.bitfield, ...flags);
799
+ }
800
+ /** Names of the given flags that are not present. */
801
+ missing(...flags) {
802
+ const missing = [];
803
+ for (const [name, bit] of Object.entries(PermissionFlags)) {
804
+ const requested = flags.some((flag) => resolvePermission(flag) === bit);
805
+ if (requested && (this.bitfield & bit) === 0n) missing.push(name);
806
+ }
807
+ return missing;
808
+ }
809
+ /** Names of every single-bit permission that is present. */
810
+ toArray() {
811
+ const names = [];
812
+ for (const [name, bit] of Object.entries(PermissionFlags)) {
813
+ if ((this.bitfield & bit) === bit) names.push(name);
814
+ }
815
+ return names;
816
+ }
817
+ equals(other) {
818
+ return this.bitfield === resolvePermission(other);
819
+ }
820
+ toString() {
821
+ return this.bitfield.toString();
822
+ }
823
+ toJSON() {
824
+ return this.toString();
825
+ }
826
+ valueOf() {
827
+ return this.bitfield;
828
+ }
829
+ [Symbol.toPrimitive]() {
830
+ return this.bitfield;
831
+ }
832
+ };
833
+ var normalizeOverwrite = (raw) => ({
834
+ id: String(raw?.id ?? ""),
835
+ type: Number(raw?.type ?? OverwriteType.Role),
836
+ allow: resolvePermission(raw?.allow ?? 0n),
837
+ deny: resolvePermission(raw?.deny ?? 0n)
838
+ });
839
+ function readOverwrites(channel) {
840
+ if (!channel) return [];
841
+ const manager = channel.permissionOverwrites;
842
+ if (manager instanceof Map) {
843
+ return [...manager.values()].map(normalizeOverwrite);
844
+ }
845
+ if (manager?.cache instanceof Map) {
846
+ return [...manager.cache.values()].map(normalizeOverwrite);
847
+ }
848
+ if (typeof manager?.values === "function") {
849
+ return [...manager.values()].map(normalizeOverwrite);
850
+ }
851
+ const raw = Array.isArray(channel.permission_overwrites) ? channel.permission_overwrites : Array.isArray(manager) ? manager : [];
852
+ return raw.map(normalizeOverwrite);
853
+ }
854
+ var memberRoleIds = (member) => {
855
+ const roles = member?.roles;
856
+ if (!Array.isArray(roles)) return [];
857
+ return roles.map((role) => typeof role === "string" ? role : role?.id).filter((id) => typeof id === "string" && id.length > 0);
858
+ };
859
+ function computePermissions(guild, member, channel = null) {
860
+ const guildId = String(guild?.id ?? "");
861
+ const memberId = String(member?.id ?? member?.user?.id ?? "");
862
+ const ownerId = String(guild?.ownerId ?? guild?.owner_id ?? "");
863
+ if (ownerId && ownerId === memberId) return new Permissions(ALL_PERMISSIONS);
864
+ const roles = Array.isArray(guild?.roles) ? guild.roles : [];
865
+ const roleIds = new Set(memberRoleIds(member));
866
+ let bitfield = 0n;
867
+ for (const role of roles) {
868
+ const roleId = String(role?.id ?? "");
869
+ if (!roleId) continue;
870
+ if (roleId === guildId || roleIds.has(roleId)) {
871
+ bitfield |= resolvePermission(role.permissions ?? 0n);
872
+ }
873
+ }
874
+ if ((bitfield & PermissionFlags.Administrator) === PermissionFlags.Administrator) {
875
+ return new Permissions(ALL_PERMISSIONS);
876
+ }
877
+ if (!channel) return new Permissions(bitfield);
878
+ const overwrites = readOverwrites(channel);
879
+ const everyone = overwrites.find(
880
+ (overwrite) => overwrite.id === guildId && overwrite.type === OverwriteType.Role
881
+ );
882
+ if (everyone) bitfield = bitfield & ~everyone.deny | everyone.allow;
883
+ let roleAllow = 0n;
884
+ let roleDeny = 0n;
885
+ for (const overwrite of overwrites) {
886
+ if (overwrite.type !== OverwriteType.Role) continue;
887
+ if (overwrite.id === guildId) continue;
888
+ if (!roleIds.has(overwrite.id)) continue;
889
+ roleAllow |= overwrite.allow;
890
+ roleDeny |= overwrite.deny;
891
+ }
892
+ bitfield = bitfield & ~roleDeny | roleAllow;
893
+ const memberOverwrite = overwrites.find(
894
+ (overwrite) => overwrite.id === memberId && overwrite.type === OverwriteType.Member
895
+ );
896
+ if (memberOverwrite) {
897
+ bitfield = bitfield & ~memberOverwrite.deny | memberOverwrite.allow;
898
+ }
899
+ return new Permissions(bitfield);
900
+ }
901
+
902
+ // src/platform/client.ts
903
+ var import_node_events2 = require("events");
904
+ var LOG_LEVELS = {
905
+ debug: 10,
906
+ info: 20,
907
+ warn: 30,
908
+ error: 40
909
+ };
910
+ function makeLogger(level = "info") {
911
+ const threshold = LOG_LEVELS[level] ?? LOG_LEVELS.info;
912
+ const wrap = (name) => (msg, data) => {
913
+ if (LOG_LEVELS[name] < threshold) return;
914
+ let line = msg;
915
+ if (data !== void 0) {
916
+ try {
917
+ line = `${msg} ${JSON.stringify(data)}`;
918
+ } catch {
919
+ line = `${msg} [unserializable]`;
920
+ }
921
+ }
922
+ if (name === "error") console.error(line);
923
+ else if (name === "warn") console.warn(line);
924
+ else console.log(line);
925
+ };
926
+ return { debug: wrap("debug"), info: wrap("info"), warn: wrap("warn"), error: wrap("error") };
927
+ }
928
+ function makeMessage(client, raw) {
929
+ const author = raw.author ?? { id: raw.author_id };
930
+ const channelId = raw.channel_id;
931
+ const cached = client.channels.get(channelId);
932
+ const guildId = raw.guild_id ?? cached?.guildId ?? null;
933
+ const guild = guildId ? client.guilds.get(guildId) ?? null : null;
934
+ const channel = cached ?? client.wrapChannel({ id: channelId, guildId, type: 0 }, guild);
935
+ const message = {
936
+ ...raw,
937
+ id: raw.id,
938
+ content: raw.content ?? "",
939
+ author,
940
+ guildId,
941
+ channelId,
942
+ channel,
943
+ guild,
944
+ member: raw.member ? guild ? client.wrapMember(raw.member, guild) : { ...raw.member, user: author } : null,
945
+ reply: async (options) => {
946
+ const payload = typeof options === "string" ? { content: options } : { ...options };
947
+ payload.message_reference = { message_id: raw.id, channel_id: channelId, ...guildId ? { guild_id: guildId } : {} };
948
+ return client.sendMessage(channelId, payload);
949
+ }
950
+ };
951
+ return message;
952
+ }
953
+ var PlatformClient = class extends import_node_events2.EventEmitter {
954
+ rest = new RestClient();
955
+ logger;
956
+ guilds = /* @__PURE__ */ new Map();
957
+ channels = /* @__PURE__ */ new Map();
958
+ users = /* @__PURE__ */ new Map();
959
+ user = null;
960
+ ws = null;
961
+ options;
962
+ readyAt = null;
963
+ readyResolve = null;
964
+ constructor(options = {}) {
965
+ super();
966
+ this.options = options;
967
+ this.logger = makeLogger(options.logLevel ?? "info");
968
+ if (options.apiBase) this.rest.baseUrl = options.apiBase;
969
+ this.channels.fetch = async (id) => {
970
+ const cached = this.channels.get(id);
971
+ if (cached) return cached;
972
+ const raw = await this.rest.get(`/channels/${id}`);
973
+ const ch = this.wrapChannel(raw);
974
+ this.channels.set(ch.id, ch);
975
+ return ch;
976
+ };
977
+ this.guilds.fetch = async (id) => {
978
+ const cached = this.guilds.get(id);
979
+ if (cached) return cached;
980
+ const raw = await this.rest.get(`/guilds/${id}`);
981
+ const g = this.wrapGuild(raw);
982
+ this.guilds.set(g.id, g);
983
+ return g;
984
+ };
985
+ }
986
+ get uptime() {
987
+ return this.readyAt ? Date.now() - this.readyAt : null;
988
+ }
989
+ /**
990
+ * Normalize a guild payload. Gateway payloads often omit `owner_id` and
991
+ * deliver members as an array, so both are handled here.
992
+ */
993
+ wrapGuild(guild) {
994
+ if (!guild) return guild;
995
+ const g = { ...guild };
996
+ g.shardId = g.shardId ?? 0;
997
+ g.ownerId = g.ownerId ?? g.owner_id ?? null;
998
+ g.roles = Array.isArray(g.roles) ? g.roles : [];
999
+ g.iconURL = (opts) => g.icon ? `https://fluxerusercontent.com/icons/${g.id}/${g.icon}${opts?.extension ? "." + opts.extension : ""}` : null;
1000
+ const rawMembers = g.members;
1001
+ const cache = /* @__PURE__ */ new Map();
1002
+ const members = { cache, me: null };
1003
+ members.get = (id) => cache.get(String(id)) ?? null;
1004
+ members.fetch = async (id) => {
1005
+ const cached = cache.get(String(id));
1006
+ if (cached) return cached;
1007
+ const raw = await this.rest.get(`/guilds/${g.id}/members/${id}`);
1008
+ const member = this.wrapMember(raw, g);
1009
+ if (member?.id) cache.set(member.id, member);
1010
+ return member;
1011
+ };
1012
+ members.fetchMe = async () => {
1013
+ const raw = await this.rest.get(`/guilds/${g.id}/members/@me`);
1014
+ const member = this.wrapMember(raw, g);
1015
+ if (member?.id) cache.set(member.id, member);
1016
+ members.me = member;
1017
+ return member;
1018
+ };
1019
+ if (Array.isArray(rawMembers)) {
1020
+ for (const raw of rawMembers) {
1021
+ const member = this.wrapMember(raw, g);
1022
+ if (member?.id) cache.set(member.id, member);
1023
+ }
1024
+ }
1025
+ const meId = String(this.user?.id ?? "");
1026
+ members.me = meId ? cache.get(meId) ?? null : null;
1027
+ g.members = members;
1028
+ g.channels = g.channels && !Array.isArray(g.channels) ? { ...g.channels } : {};
1029
+ g.channels.cache = this.channels;
1030
+ g.channels.get = (id) => this.channels.get(id);
1031
+ g.channels.fetch = (id) => this.channels.fetch(id);
1032
+ return g;
1033
+ }
1034
+ /** Attach permission helpers to a raw member payload. */
1035
+ wrapMember(raw, guild) {
1036
+ if (!raw) return raw;
1037
+ const member = { ...raw };
1038
+ member.id = String(member.id ?? member.user?.id ?? "");
1039
+ if (!member.user && member.id) member.user = { id: member.id };
1040
+ Object.defineProperty(member, "permissions", {
1041
+ enumerable: true,
1042
+ configurable: true,
1043
+ get: () => computePermissions(guild, member)
1044
+ });
1045
+ member.permissionsIn = (channel) => computePermissions(guild, member, channel);
1046
+ member.has = (...flags) => member.permissions.has(...flags);
1047
+ return member;
1048
+ }
1049
+ wrapChannel(ch, guild) {
1050
+ if (!ch) return ch;
1051
+ const c = { ...ch };
1052
+ c.guildId = c.guildId ?? c.guild_id ?? guild?.id;
1053
+ c.guild = guild ?? (c.guildId ? this.guilds.get(c.guildId) ?? null : c.guild ?? null);
1054
+ c.isVoice = () => [2, 13].includes(c.type);
1055
+ c.isTextBased = () => [0, 1, 5, 10, 11, 12].includes(c.type);
1056
+ c.send = (options) => this.sendMessage(c.id, options);
1057
+ const rawOverwrites = Array.isArray(ch.permission_overwrites) ? ch.permission_overwrites : [];
1058
+ const manager = this.createOverwriteManager(c.id, rawOverwrites);
1059
+ c.permissionOverwrites = manager;
1060
+ Object.defineProperty(c, "permission_overwrites", {
1061
+ enumerable: true,
1062
+ configurable: true,
1063
+ get: () => manager.toArray()
1064
+ });
1065
+ return c;
1066
+ }
1067
+ /** Overwrite manager backed by `PUT/DELETE /channels/:id/permissions/:id`. */
1068
+ createOverwriteManager(channelId, raw) {
1069
+ const cache = /* @__PURE__ */ new Map();
1070
+ for (const item of raw) {
1071
+ const overwrite = normalizeOverwrite(item);
1072
+ if (overwrite.id) cache.set(overwrite.id, overwrite);
1073
+ }
1074
+ const write = async (id, options = {}) => {
1075
+ const overwriteId = String(id);
1076
+ const existing = cache.get(overwriteId);
1077
+ const type = options.type ?? existing?.type ?? OverwriteType.Role;
1078
+ const allow = resolvePermission(options.allow ?? 0n);
1079
+ const deny = resolvePermission(options.deny ?? 0n);
1080
+ await this.rest.put(`/channels/${channelId}/permissions/${overwriteId}`, {
1081
+ type,
1082
+ allow: allow.toString(),
1083
+ deny: deny.toString()
1084
+ });
1085
+ const overwrite = { id: overwriteId, type, allow, deny };
1086
+ cache.set(overwriteId, overwrite);
1087
+ return overwrite;
1088
+ };
1089
+ return {
1090
+ cache,
1091
+ get: (id) => cache.get(String(id)) ?? null,
1092
+ has: (id) => cache.has(String(id)),
1093
+ values: () => cache.values(),
1094
+ toArray: () => [...cache.values()],
1095
+ edit: write,
1096
+ create: write,
1097
+ delete: async (id) => {
1098
+ const overwriteId = String(id);
1099
+ await this.rest.delete(`/channels/${channelId}/permissions/${overwriteId}`);
1100
+ cache.delete(overwriteId);
1101
+ }
1102
+ };
1103
+ }
1104
+ async login(token, _options) {
1105
+ this.rest.setToken(token);
1106
+ const gw = new Gateway({ token, url: this.options.gatewayUrl, intents: this.options.intents });
1107
+ this.ws = gw;
1108
+ this.ws.ping = -1;
1109
+ gw.on("dispatch", (t, d) => this.handleDispatch(t, d));
1110
+ gw.on("error", (e) => this.emit("error", e));
1111
+ await gw.connect();
1112
+ await new Promise((resolve3) => {
1113
+ this.readyResolve = resolve3;
1114
+ });
1115
+ }
1116
+ async destroy() {
1117
+ try {
1118
+ this.ws?.close();
1119
+ } catch {
1120
+ }
1121
+ this.ws = null;
1122
+ }
1123
+ sendToGateway(_shardId, payload) {
1124
+ this.logger.debug("[gateway send]", payload);
1125
+ this.ws?.send(payload);
1126
+ }
1127
+ handleDispatch(t, d) {
1128
+ this.emit("raw", { t, d });
1129
+ if (t.includes("VOICE")) this.logger.debug("[voice dispatch]", { t, d });
1130
+ switch (t) {
1131
+ case "READY": {
1132
+ this.user = d?.user ?? null;
1133
+ if (this.user) this.user.setPresence = async (_p) => {
1134
+ };
1135
+ if (this.user) this.users.set(this.user.id, this.user);
1136
+ for (const g of d?.guilds ?? []) this.guilds.set(g.id, this.wrapGuild({ ...g, shardId: 0 }));
1137
+ this.readyAt = Date.now();
1138
+ this.emit(Events.Ready);
1139
+ this.readyResolve?.();
1140
+ this.readyResolve = null;
1141
+ return;
1142
+ }
1143
+ case "MESSAGE_CREATE": {
1144
+ const msg = makeMessage(this, d);
1145
+ this.emit(Events.MessageCreate, msg);
1146
+ return;
1147
+ }
1148
+ case "MESSAGE_UPDATE": {
1149
+ const msg = makeMessage(this, d);
1150
+ this.emit(Events.MessageUpdate, msg, msg);
1151
+ return;
1152
+ }
1153
+ case "MESSAGE_DELETE": {
1154
+ this.emit(Events.MessageDelete, d);
1155
+ return;
1156
+ }
1157
+ case "GUILD_CREATE": {
1158
+ void this.handleGuildCreate(d).catch((error) => {
1159
+ this.logger.warn("Could not load guild", { guildId: d?.id, error: String(error) });
1160
+ });
1161
+ return;
1162
+ }
1163
+ case "GUILD_DELETE": {
1164
+ this.guilds.delete(d?.id);
1165
+ this.emit(Events.GuildDelete ?? "guildDelete", d);
1166
+ return;
1167
+ }
1168
+ case "CHANNEL_CREATE":
1169
+ case "CHANNEL_UPDATE": {
1170
+ const guild = d.guild_id ? this.guilds.get(d.guild_id) ?? null : null;
1171
+ const ch = this.wrapChannel({ ...d, guildId: d.guild_id, guild }, guild);
1172
+ this.channels.set(ch.id, ch);
1173
+ return;
1174
+ }
1175
+ case "VOICE_STATE_UPDATE":
1176
+ this.emit(Events.VoiceStateUpdate, d);
1177
+ return;
1178
+ case "VOICE_SERVER_UPDATE":
1179
+ this.emit(Events.VoiceServerUpdate, d);
1180
+ return;
1181
+ case "VOICE_STATE_ACK":
1182
+ this.emit(Events.VoiceStateAck, d);
1183
+ return;
1184
+ default:
1185
+ this.emit(t.toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase()), d);
1186
+ }
1187
+ }
1188
+ /**
1189
+ * Cache a gateway guild. Gateway payloads can include `roles` but omit
1190
+ * `owner_id`, so the REST guild is fetched once and merged before the
1191
+ * `guildCreate` event is emitted.
1192
+ */
1193
+ async handleGuildCreate(raw) {
1194
+ if (!raw?.id) return;
1195
+ let data = raw;
1196
+ if (!raw.owner_id && !raw.ownerId) {
1197
+ const fetched = await this.rest.get(`/guilds/${raw.id}`).catch(() => null);
1198
+ if (fetched) {
1199
+ data = {
1200
+ ...raw,
1201
+ ...fetched,
1202
+ channels: raw.channels ?? fetched.channels,
1203
+ members: raw.members ?? fetched.members
1204
+ };
1205
+ }
1206
+ }
1207
+ const guild = this.wrapGuild({ ...data, shardId: 0 });
1208
+ this.guilds.set(guild.id, guild);
1209
+ for (const ch of data?.channels ?? []) {
1210
+ const channel = this.wrapChannel({ ...ch, guildId: guild.id }, guild);
1211
+ this.channels.set(channel.id, channel);
1212
+ }
1213
+ this.emit(Events.GuildCreate, guild);
1214
+ this.emit(Events.VoiceStatesSync, {
1215
+ guildId: guild.id,
1216
+ voiceStates: data?.voice_states ?? []
1217
+ });
1218
+ }
1219
+ async sendMessage(channelId, options) {
1220
+ const payload = typeof options === "string" ? { content: options } : options;
1221
+ const raw = await this.rest.post(`/channels/${channelId}/messages`, payload);
1222
+ return makeMessage(this, raw);
1223
+ }
1224
+ };
1225
+
1226
+ // src/platform/opcodes.ts
1227
+ var GatewayOpcodes = {
1228
+ Dispatch: 0,
1229
+ Heartbeat: 1,
1230
+ Identify: 2,
1231
+ PresenceUpdate: 3,
1232
+ VoiceStateUpdate: 4,
1233
+ Resume: 6,
1234
+ Reconnect: 7,
1235
+ RequestGuildMembers: 8,
1236
+ InvalidSession: 9,
1237
+ Hello: 10,
1238
+ HeartbeatAck: 11
1239
+ };
1240
+
1241
+ // src/util/tokenize.ts
1242
+ function tokenize(input) {
1243
+ const tokens = [];
1244
+ let current = "";
1245
+ let quote = null;
1246
+ let escaped = false;
1247
+ for (const char of input) {
1248
+ if (escaped) {
1249
+ current += char;
1250
+ escaped = false;
1251
+ continue;
1252
+ }
1253
+ if (char === "\\") {
1254
+ escaped = true;
1255
+ continue;
1256
+ }
1257
+ if (quote) {
1258
+ if (char === quote) quote = null;
1259
+ else current += char;
1260
+ continue;
1261
+ }
1262
+ if (char === '"' || char === "'") {
1263
+ quote = char;
1264
+ continue;
1265
+ }
1266
+ if (/\s/.test(char)) {
1267
+ if (current) {
1268
+ tokens.push(current);
1269
+ current = "";
1270
+ }
1271
+ continue;
1272
+ }
1273
+ current += char;
1274
+ }
1275
+ if (escaped) current += "\\";
1276
+ if (current) tokens.push(current);
1277
+ return tokens;
1278
+ }
1279
+ function formatDuration(ms) {
1280
+ const totalSeconds = Math.max(0, Math.ceil(ms / 1e3));
1281
+ if (totalSeconds < 60) return `${totalSeconds}s`;
1282
+ const minutes = Math.floor(totalSeconds / 60);
1283
+ const seconds = totalSeconds % 60;
1284
+ if (minutes < 60) return seconds ? `${minutes}m ${seconds}s` : `${minutes}m`;
1285
+ const hours = Math.floor(minutes / 60);
1286
+ const rest = minutes % 60;
1287
+ return rest ? `${hours}h ${rest}m` : `${hours}h`;
1288
+ }
1289
+
1290
+ // src/client.ts
1291
+ var import_node_path2 = require("path");
1292
+ var DEFAULT_MESSAGES = {
1293
+ guildOnly: "This command can only be used in a server.",
1294
+ ownerOnly: "This command is restricted to the bot owner.",
1295
+ cooldown: (retryAfterMs) => `Wait ${formatDuration(retryAfterMs)} before using this command again.`,
1296
+ error: "Something went wrong while running this command."
1297
+ };
1298
+ function resolveOptions(options) {
1299
+ const dirs = /* @__PURE__ */ new Set();
1300
+ if (options.commandsDir) dirs.add(options.commandsDir);
1301
+ if (options.eventsDir) dirs.add(options.eventsDir);
1302
+ if (options.listenersDir) dirs.add(options.listenersDir);
1303
+ for (const dir of options.loadDirs ?? []) dirs.add(dir);
1304
+ return {
1305
+ prefix: options.prefix ?? "!",
1306
+ owners: Object.freeze([...options.owners ?? []]),
1307
+ allowBots: options.allowBots ?? false,
1308
+ allowDMs: options.allowDMs ?? true,
1309
+ middlewares: Object.freeze([...options.middlewares ?? []]),
1310
+ loadDirs: Object.freeze([...dirs]),
1311
+ ...options.extensions ? { extensions: Object.freeze([...options.extensions]) } : {},
1312
+ ignore: Object.freeze([...options.ignore ?? []]),
1313
+ cacheBust: options.cacheBust ?? true,
1314
+ messages: { ...DEFAULT_MESSAGES, ...options.messages },
1315
+ ...options.onCommandError ? { onCommandError: options.onCommandError } : {},
1316
+ ...options.onEventError ?? options.onListenerError ? { onEventError: options.onEventError ?? options.onListenerError } : {}
1317
+ };
1318
+ }
1319
+ async function resolvePrefix(option, message) {
1320
+ if (typeof option === "string") return option || null;
1321
+ if (typeof option !== "function") {
1322
+ const matches = option.filter(
1323
+ (prefix) => prefix.length > 0 && message.content.startsWith(prefix)
1324
+ );
1325
+ return matches.sort((a, b) => b.length - a.length)[0] ?? null;
1326
+ }
1327
+ const resolved = await option(message);
1328
+ return resolved || null;
1329
+ }
1330
+ var Client = class extends PlatformClient {
1331
+ commands = new CommandStore();
1332
+ eventStore = new EventStore();
1333
+ /** @deprecated Use `eventStore`. */
1334
+ get listenerStore() {
1335
+ return this.eventStore;
1336
+ }
1337
+ cooldowns = new CooldownStore();
1338
+ config;
1339
+ voice;
1340
+ loadedDirs = /* @__PURE__ */ new Set();
1341
+ started = false;
1342
+ onMessage = (message) => {
1343
+ void this.handleMessage(message).catch((error) => {
1344
+ this.logger.error("Message handling failed", { error: String(error) });
1345
+ });
1346
+ };
1347
+ constructor(options = {}) {
1348
+ super(options.client ?? {});
1349
+ this.config = resolveOptions(options);
1350
+ this.voice = new VoiceManager(this, options.voice ?? null).attach();
1351
+ this.on(Events.MessageCreate, this.onMessage);
1352
+ }
1353
+ /** Register commands and/or events. */
1354
+ register(...items) {
1355
+ const commands = [];
1356
+ const events = [];
1357
+ for (const item of items) {
1358
+ if (isEvent(item)) events.push(item);
1359
+ else if (isCommand(item)) commands.push(item);
1360
+ else throw new TypeError("register() expects a command or an event");
1361
+ }
1362
+ this.registerCommand(...commands);
1363
+ this.registerEvent(...events);
1364
+ return this;
1365
+ }
1366
+ registerCommand(...commands) {
1367
+ this.commands.addMany(commands);
1368
+ return this;
1369
+ }
1370
+ registerEvent(...events) {
1371
+ this.eventStore.addMany(events);
1372
+ for (const event of events) this.eventStore.attachOne(this, event);
1373
+ return this;
1374
+ }
1375
+ /** @deprecated Use `registerEvent`. */
1376
+ registerListener(...events) {
1377
+ return this.registerEvent(...events);
1378
+ }
1379
+ /** Load commands and events from the configured directories. */
1380
+ async load() {
1381
+ const result = { commands: [], events: [], files: [] };
1382
+ for (const directory of this.config.loadDirs) {
1383
+ const absolute = (0, import_node_path2.resolve)(directory);
1384
+ if (this.loadedDirs.has(absolute)) continue;
1385
+ const loaded = await loadDirectory(absolute, {
1386
+ ...this.config.extensions ? { extensions: this.config.extensions } : {},
1387
+ ignore: this.config.ignore,
1388
+ cacheBust: this.config.cacheBust
1389
+ });
1390
+ this.commands.addMany(loaded.commands);
1391
+ this.registerEvent(...loaded.events);
1392
+ this.loadedDirs.add(absolute);
1393
+ result.commands.push(...loaded.commands);
1394
+ result.events.push(...loaded.events);
1395
+ result.files.push(...loaded.files);
1396
+ }
1397
+ return result;
1398
+ }
1399
+ /** Drop loaded commands/events and scan the configured directories again. */
1400
+ async reload() {
1401
+ this.eventStore.detach(this);
1402
+ this.eventStore.clear();
1403
+ this.commands.clear();
1404
+ this.cooldowns.clear();
1405
+ this.loadedDirs.clear();
1406
+ return this.load();
1407
+ }
1408
+ /**
1409
+ * Load modules, attach events and log in.
1410
+ *
1411
+ * @param token Token to use. Defaults to `FLUXER_BOT_TOKEN`.
1412
+ */
1413
+ async start(token, options) {
1414
+ await this.load();
1415
+ this.eventStore.attach(this);
1416
+ const resolvedToken = (token ?? process.env.FLUXER_BOT_TOKEN)?.trim();
1417
+ if (!resolvedToken) {
1418
+ throw new Error(
1419
+ "A Fluxer bot token is required. Pass it to start() or set FLUXER_BOT_TOKEN."
1420
+ );
1421
+ }
1422
+ await this.login(resolvedToken, options);
1423
+ this.started = true;
1424
+ return this;
1425
+ }
1426
+ /** Detach events, leave voice, and disconnect from Fluxer. */
1427
+ async stop() {
1428
+ this.eventStore.detach(this);
1429
+ this.cooldowns.clear();
1430
+ this.started = false;
1431
+ await this.voice.leaveAll();
1432
+ await this.destroy();
1433
+ }
1434
+ /** Whether `start()` has been called on this instance. */
1435
+ get isStarted() {
1436
+ return this.started;
1437
+ }
1438
+ /** Whether a user ID is in `owners`. */
1439
+ isOwner(userId) {
1440
+ return this.config.owners.includes(userId);
1441
+ }
1442
+ /** Called by the event store when an event throws. */
1443
+ async handleEventError(error, event, args) {
1444
+ if (this.config.onEventError) {
1445
+ await this.config.onEventError(error, event.event, args);
1446
+ return;
1447
+ }
1448
+ this.logger.error("Event failed", {
1449
+ event: event.event,
1450
+ error: String(error)
1451
+ });
1452
+ }
1453
+ /** @deprecated Use `handleEventError`. */
1454
+ async handleListenerError(error, event, args) {
1455
+ return this.handleEventError(error, event, args);
1456
+ }
1457
+ async handleMessage(message) {
1458
+ if (message.author.bot && !this.config.allowBots) return;
1459
+ if (!message.guildId && !this.config.allowDMs) return;
1460
+ const prefix = await resolvePrefix(this.config.prefix, message).catch((error) => {
1461
+ this.logger.error("Prefix resolver failed", { error: String(error) });
1462
+ return null;
1463
+ });
1464
+ if (!prefix || !message.content.startsWith(prefix)) return;
1465
+ const input = message.content.slice(prefix.length).trimStart();
1466
+ if (!input) return;
1467
+ const [name, ...args] = tokenize(input);
1468
+ if (!name) return;
1469
+ const command = this.commands.get(name);
1470
+ if (!command) return;
1471
+ if (command.guildOnly && !message.guildId) {
1472
+ await this.replySafely(message, this.config.messages.guildOnly);
1473
+ return;
1474
+ }
1475
+ if (command.ownerOnly && !this.isOwner(message.author.id)) {
1476
+ await this.replySafely(message, this.config.messages.ownerOnly);
1477
+ return;
1478
+ }
1479
+ const ctx = createCommandContext(this, message, command, args, input);
1480
+ await this.runMiddlewares(ctx);
1481
+ }
1482
+ async runMiddlewares(ctx) {
1483
+ const stack = [...this.config.middlewares, ...ctx.command.middlewares];
1484
+ let position = -1;
1485
+ const dispatch = async (index) => {
1486
+ if (index <= position) {
1487
+ throw new Error("next() called more than once in a middleware");
1488
+ }
1489
+ position = index;
1490
+ const middleware = stack[index];
1491
+ if (middleware) {
1492
+ await middleware.run(ctx, () => dispatch(index + 1));
1493
+ return;
1494
+ }
1495
+ const cooldown = this.cooldowns.consume(ctx.command, ctx);
1496
+ if (!cooldown.ok) {
1497
+ await this.replySafely(
1498
+ ctx.message,
1499
+ this.config.messages.cooldown(cooldown.retryAfter)
1500
+ );
1501
+ return;
1502
+ }
1503
+ await ctx.command.run(ctx);
1504
+ };
1505
+ try {
1506
+ await dispatch(0);
1507
+ } catch (error) {
1508
+ await this.handleCommandError(error, ctx);
1509
+ }
1510
+ }
1511
+ async handleCommandError(error, ctx) {
1512
+ if (this.config.onCommandError) {
1513
+ await this.config.onCommandError(error, ctx);
1514
+ return;
1515
+ }
1516
+ this.logger.error("Command failed", { command: ctx.command.name, userId: ctx.author.id, error: String(error) });
1517
+ await this.replySafely(ctx.message, this.config.messages.error);
1518
+ }
1519
+ async replySafely(message, content) {
1520
+ try {
1521
+ await message.reply(content);
1522
+ } catch (error) {
1523
+ this.logger.warn("Could not send reply", { error: String(error) });
1524
+ }
1525
+ }
1526
+ };
1527
+ // Annotate the CommonJS export names for ESM import in node:
1528
+ 0 && (module.exports = {
1529
+ ALL_PERMISSIONS,
1530
+ COMMAND_BRAND,
1531
+ Client,
1532
+ Command,
1533
+ CommandStore,
1534
+ CooldownStore,
1535
+ EVENT_BRAND,
1536
+ Event,
1537
+ EventStore,
1538
+ Events,
1539
+ Gateway,
1540
+ GatewayOpcodes,
1541
+ LISTENER_BRAND,
1542
+ Listener,
1543
+ ListenerStore,
1544
+ Middleware,
1545
+ ModuleLoadError,
1546
+ OverwriteType,
1547
+ PermissionFlags,
1548
+ Permissions,
1549
+ PlatformClient,
1550
+ RestClient,
1551
+ VoiceManager,
1552
+ VoiceUnavailableError,
1553
+ collectFiles,
1554
+ computePermissions,
1555
+ createCommand,
1556
+ createCommandContext,
1557
+ createEvent,
1558
+ createListener,
1559
+ createMiddleware,
1560
+ defaultExtensions,
1561
+ formatDuration,
1562
+ hasAnyPermission,
1563
+ hasPermission,
1564
+ isBun,
1565
+ isCommand,
1566
+ isEvent,
1567
+ isListener,
1568
+ loadDirectory,
1569
+ loadFile,
1570
+ memberRoleIds,
1571
+ normalizeOverwrite,
1572
+ readOverwrites,
1573
+ resolvePermission,
1574
+ resolvePermissions,
1575
+ runtimeName,
1576
+ tokenize
1577
+ });
1578
+ //# sourceMappingURL=index.cjs.map