bakit 2.0.0-alpha.6 → 2.0.0-alpha.8

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/bin/bakit.js CHANGED
@@ -31,10 +31,6 @@ program.command("dev").action(async () => {
31
31
  console.log("Bakit detected changes! Restarting...");
32
32
  });
33
33
 
34
- nodemon.on("exit", () => {
35
- console.log("Proccess exited! Did you start bakit correctly?");
36
- });
37
-
38
34
  nodemon.on("quit", () => {
39
35
  process.exit();
40
36
  });
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import * as discord_js from 'discord.js';
2
- import { GatewayIntentBits, ClientOptions, ChatInputCommandInteraction, CacheType, Message, User, MessageCreateOptions, InteractionReplyOptions, Awaitable, Collection, Events, IntentsBitField, ClientEvents, Client } from 'discord.js';
2
+ import { GatewayIntentBits, ClientOptions, ChatInputCommandInteraction, CacheType, Message, User, MessageCreateOptions, InteractionReplyOptions, Awaitable, Collection, Events, IntentsBitField, Client, ClientEvents } from 'discord.js';
3
3
  import z$1, { z } from 'zod';
4
- import { inspect } from 'node:util';
5
4
  import * as jiti from 'jiti';
5
+ import { inspect } from 'node:util';
6
6
 
7
7
  declare const ProjectConfigSchema: z.ZodObject<{
8
8
  intents: z.ZodDefault<z.ZodUnion<readonly [z.ZodLiteral<"auto">, z.ZodBigInt, z.ZodArray<z.ZodEnum<typeof GatewayIntentBits>>]>>;
@@ -31,6 +31,12 @@ declare function loadConfig(cwd?: string): Promise<ProjectConfig>;
31
31
  */
32
32
  declare function getConfig(): ProjectConfig;
33
33
 
34
+ declare const EVENT_INTENT_MAPPING: Record<string, number[]>;
35
+
36
+ declare function tokenize(content: string): string[];
37
+
38
+ declare const $jiti: jiti.Jiti;
39
+
34
40
  declare class Context {
35
41
  canceled: boolean;
36
42
  cancel(): void;
@@ -298,11 +304,6 @@ declare function defineCommand<const ParamsList extends readonly AnyParam<any>[]
298
304
  params?: ParamsList;
299
305
  }) | string): Command<ParamsList>;
300
306
 
301
- declare class BaseClientManager {
302
- client: BakitClient;
303
- constructor(client: BakitClient);
304
- }
305
-
306
307
  declare class CommandManager extends BaseClientManager {
307
308
  commands: Collection<string, Command<any[]>>;
308
309
  loadModules(): Promise<Command[]>;
@@ -337,17 +338,39 @@ declare class ListenerManager extends BaseClientManager {
337
338
  getNeededIntents(): IntentsBitField;
338
339
  }
339
340
 
341
+ declare class ProjectCacheManager {
342
+ private readonly rootDir;
343
+ constructor(root?: string);
344
+ private ensureRoot;
345
+ getHash(data: unknown): string;
346
+ write(path: string, data: unknown): Promise<void>;
347
+ read<T>(path: string): Promise<T | null>;
348
+ clear(): Promise<void>;
349
+ clearSync(): void;
350
+ }
351
+
352
+ declare class Instance {
353
+ client: BakitClient;
354
+ cache: ProjectCacheManager;
355
+ constructor();
356
+ start(): Promise<void>;
357
+ private loadModules;
358
+ private initIntents;
359
+ }
360
+ declare function useApp(): Instance;
361
+
340
362
  type GetPrefixFunction = (message: Message) => Awaitable<string[] | string>;
341
363
  interface BakitClientEvents extends ClientEvents {
342
364
  ready: [BakitClient<true>];
343
365
  clientReady: [BakitClient<true>];
344
366
  }
345
367
  declare class BakitClient<Ready extends boolean = boolean> extends Client<Ready> {
368
+ instance: Instance;
346
369
  managers: {
347
370
  commands: CommandManager;
348
371
  listeners: ListenerManager;
349
372
  };
350
- constructor(options: ClientOptions);
373
+ constructor(options: ClientOptions, instance: Instance);
351
374
  /**
352
375
  * Check if the client is connected to gateway successfully and finished initialization.
353
376
  */
@@ -365,28 +388,9 @@ declare class BakitClient<Ready extends boolean = boolean> extends Client<Ready>
365
388
  [inspect.custom](): string;
366
389
  }
367
390
 
368
- declare class Instance {
391
+ declare class BaseClientManager {
369
392
  client: BakitClient;
370
- start(): Promise<void>;
371
- private loadModules;
372
- private initIntents;
373
- }
374
- declare function useApp(): Instance;
375
-
376
- declare const EVENT_INTENT_MAPPING: Record<string, number[]>;
377
-
378
- declare function tokenize(content: string): string[];
379
-
380
- declare const $jiti: jiti.Jiti;
381
-
382
- declare class BakitError extends Error {
383
- constructor(message: string);
384
- }
385
-
386
- declare class ArgumentError extends BakitError {
387
- target: string;
388
- reason: string;
389
- constructor(target: string, reason: string);
393
+ constructor(client: BakitClient);
390
394
  }
391
395
 
392
396
  declare const Params: {
@@ -406,4 +410,14 @@ declare const Params: {
406
410
  }) => NumberParam<Required>;
407
411
  };
408
412
 
413
+ declare class BakitError extends Error {
414
+ constructor(message: string);
415
+ }
416
+
417
+ declare class ArgumentError extends BakitError {
418
+ target: string;
419
+ reason: string;
420
+ constructor(target: string, reason: string);
421
+ }
422
+
409
423
  export { $jiti, type AnyParam, ArgumentError, BakitClient, type BakitClientEvents, BakitError, BaseClientManager, BaseCommandContext, BaseParam, type BaseParamOptions, BaseParamSchema, ChatInputContext, type ChatInputContextSendOptions, Command, type CommandContext, CommandManager, type CommandOptions, type CommandOptionsInput, CommandOptionsSchema, Context, type ContextSendOptions, EVENT_INTENT_MAPPING, type ErrorHookCallback, type GetPrefixFunction, HookOrder, HookState, type InferParamTuple, type InferParamValue, Instance, LifecycleManager, Listener, ListenerManager, type ListenerOptions, ListenerOptionsSchema, type MainHookCallback, MessageContext, type MessageContextSendOptions, type NumberOptions, NumberParam, NumberParamSchema, type ParamResolvedOutputType, ParamUserType, Params, type ProjectConfig, type ProjectConfigInput, ProjectConfigSchema, type StringOptions, StringParam, StringParamSchema, defineCommand, defineConfig, defineListener, getConfig, loadConfig, tokenize, useApp, validateParamsOrder };
package/dist/index.js CHANGED
@@ -3,7 +3,10 @@ import z3, { z } from 'zod';
3
3
  import glob from 'tiny-glob';
4
4
  import { createJiti } from 'jiti';
5
5
  import { inspect } from 'util';
6
- import { posix } from 'path';
6
+ import { posix, join, dirname } from 'path';
7
+ import { existsSync, mkdirSync, rmSync } from 'fs';
8
+ import { mkdir, writeFile, readFile, rm } from 'fs/promises';
9
+ import { createHash } from 'crypto';
7
10
 
8
11
  // src/config.ts
9
12
  var INTENT_GROUPS = {
@@ -178,6 +181,13 @@ function getConfig() {
178
181
  return _config;
179
182
  }
180
183
 
184
+ // src/base/BaseClientManager.ts
185
+ var BaseClientManager = class {
186
+ constructor(client) {
187
+ this.client = client;
188
+ }
189
+ };
190
+
181
191
  // src/base/lifecycle/Context.ts
182
192
  var Context = class {
183
193
  canceled = false;
@@ -186,7 +196,7 @@ var Context = class {
186
196
  }
187
197
  };
188
198
 
189
- // src/command/CommandContext.ts
199
+ // src/base/command/CommandContext.ts
190
200
  var BaseCommandContext = class extends Context {
191
201
  constructor(source) {
192
202
  super();
@@ -337,7 +347,7 @@ var ArgumentError = class extends BakitError {
337
347
  }
338
348
  };
339
349
 
340
- // src/command/param/Param.ts
350
+ // src/base/command/param/Param.ts
341
351
  var BaseParam = class {
342
352
  options;
343
353
  constructor(options) {
@@ -510,19 +520,13 @@ function defineCommand(options) {
510
520
  return new Command(options);
511
521
  }
512
522
 
513
- // src/base/BaseClientManager.ts
514
- var BaseClientManager = class {
515
- constructor(client) {
516
- this.client = client;
517
- }
518
- };
519
-
520
- // src/command/CommandManager.ts
523
+ // src/base/command/CommandManager.ts
521
524
  var CommandManager = class extends BaseClientManager {
522
525
  commands = new Collection();
523
526
  async loadModules() {
524
527
  let entryDir = posix.resolve(getConfig().entryDir), pattern = posix.join(entryDir, "commands", "**/*.{ts,js}"), loads = (await glob(pattern, {
525
- cwd: process.cwd()
528
+ cwd: process.cwd(),
529
+ absolute: true
526
530
  })).map(async (file) => {
527
531
  try {
528
532
  let command = await $jiti.import(file, { default: !0 });
@@ -579,7 +583,8 @@ var ListenerManager = class extends BaseClientManager {
579
583
  executors = /* @__PURE__ */ new WeakMap();
580
584
  async loadModules() {
581
585
  let entryDir = posix.resolve(getConfig().entryDir), pattern = posix.join(entryDir, "listeners", "**/*.{ts,js}"), loads = (await glob(pattern, {
582
- cwd: process.cwd()
586
+ cwd: process.cwd(),
587
+ absolute: true
583
588
  })).map(async (file) => {
584
589
  try {
585
590
  let listener = await $jiti.import(file, { default: !0 });
@@ -631,15 +636,17 @@ var ListenerManager = class extends BaseClientManager {
631
636
  }
632
637
  };
633
638
 
634
- // src/BakitClient.ts
635
- var BakitClient3 = class extends Client {
636
- managers;
637
- constructor(options) {
638
- super(options), this.managers = {
639
+ // src/base/BakitClient.ts
640
+ var BakitClient2 = class extends Client {
641
+ constructor(options, instance) {
642
+ super(options);
643
+ this.instance = instance;
644
+ this.managers = {
639
645
  commands: new CommandManager(this),
640
646
  listeners: new ListenerManager(this)
641
647
  };
642
648
  }
649
+ managers;
643
650
  /**
644
651
  * Check if the client is connected to gateway successfully and finished initialization.
645
652
  */
@@ -687,7 +694,7 @@ var ParamUserType = /* @__PURE__ */ ((ParamUserType2) => (ParamUserType2.Bot = "
687
694
  minValue: z.number().optional()
688
695
  }).transform(withDefaultDescription);
689
696
 
690
- // src/command/param/Params.ts
697
+ // src/base/command/param/Params.ts
691
698
  function createFactory(ctor) {
692
699
  return (...args) => new ctor(...args);
693
700
  }
@@ -702,8 +709,22 @@ var messageCommandHandler = defineListener(Events.MessageCreate), chatInputComma
702
709
  once: true
703
710
  });
704
711
  registerCommandsHandler.main(async (_, client) => {
705
- let { commands } = client.managers, data = commands.commands.map((cmd) => cmd.toSlashCommandJSON()), result = await client.application.commands.set(data);
706
- console.log(`Registered ${result.size} application command(s)`);
712
+ let { managers, instance } = client, { commands } = managers, { cache } = instance, payload = commands.commands.map((cmd) => cmd.toSlashCommandJSON()).sort((a, b) => a.name.localeCompare(b.name)), currentHash = cache.getHash(payload), CACHE_KEY = "commands/meta.json", cachedMeta = await cache.read(CACHE_KEY);
713
+ if (cachedMeta && cachedMeta.hash === currentHash) {
714
+ let { timestamp, count } = cachedMeta, time = new Date(timestamp).toLocaleString();
715
+ console.log(`${count} command(s) are up to date (Last sync: ${time}). Skipping registration.`);
716
+ return;
717
+ }
718
+ try {
719
+ let result = await client.application.commands.set(payload);
720
+ cache.write(CACHE_KEY, {
721
+ hash: currentHash,
722
+ timestamp: Date.now(),
723
+ count: result.size
724
+ }), cache.write("commands/debug_dump.json", payload), console.log(`Registered ${result.size} application command(s).`);
725
+ } catch (error) {
726
+ console.error("Failed to register commands:", error);
727
+ }
707
728
  });
708
729
  messageCommandHandler.main(async (_, message) => {
709
730
  let config = getConfig();
@@ -741,20 +762,61 @@ chatInputCommandHandler.main(async (_, interaction) => {
741
762
  }
742
763
  await command.execute(context, ...resolvedArgs);
743
764
  });
765
+ var ProjectCacheManager = class {
766
+ rootDir;
767
+ constructor(root = process.cwd()) {
768
+ this.rootDir = join(root, ".bakit"), this.ensureRoot();
769
+ }
770
+ ensureRoot() {
771
+ existsSync(this.rootDir) || mkdirSync(this.rootDir, { recursive: true });
772
+ }
773
+ getHash(data) {
774
+ return createHash("sha256").update(JSON.stringify(data)).digest("hex");
775
+ }
776
+ async write(path, data) {
777
+ let fullPath = join(this.rootDir, path), dir = dirname(fullPath);
778
+ await mkdir(dir, { recursive: true });
779
+ let content = typeof data == "string" ? data : JSON.stringify(data, null, 2);
780
+ await writeFile(fullPath, content, "utf-8");
781
+ }
782
+ async read(path) {
783
+ let fullPath = join(this.rootDir, path);
784
+ try {
785
+ let content = await readFile(fullPath, "utf-8");
786
+ return JSON.parse(content);
787
+ } catch {
788
+ return null;
789
+ }
790
+ }
791
+ async clear() {
792
+ await rm(this.rootDir, { recursive: true, force: true });
793
+ }
794
+ clearSync() {
795
+ existsSync(this.rootDir) && rmSync(this.rootDir, { recursive: true, force: true });
796
+ }
797
+ };
744
798
 
745
- // src/Instance.ts
799
+ // src/base/Instance.ts
746
800
  var Instance = class {
747
801
  client;
802
+ cache;
803
+ constructor() {
804
+ this.cache = new ProjectCacheManager();
805
+ }
748
806
  async start() {
749
807
  await loadConfig();
750
808
  let config = getConfig();
751
- this.client = new BakitClient3({
752
- intents: []
753
- }), await this.loadModules(), this.initIntents(), await this.client.login(config.token);
809
+ this.client = new BakitClient2(
810
+ {
811
+ intents: [],
812
+ ...config.clientOptions
813
+ },
814
+ this
815
+ ), await this.loadModules(), this.initIntents(), await this.client.login(config.token);
754
816
  }
755
817
  loadModules() {
756
818
  let { managers } = this.client, { commands, listeners } = managers;
757
- return listeners.add(chatInputCommandHandler), listeners.add(messageCommandHandler), Promise.all([commands.loadModules(), listeners.loadModules()]);
819
+ return listeners.add(chatInputCommandHandler), listeners.add(messageCommandHandler), listeners.add(registerCommandsHandler), Promise.all([commands.loadModules(), listeners.loadModules()]);
758
820
  }
759
821
  initIntents() {
760
822
  let config = getConfig(), { options, managers } = this.client, { listeners } = managers, intents;
@@ -765,4 +827,4 @@ function useApp() {
765
827
  return new Instance();
766
828
  }
767
829
 
768
- export { $jiti, ArgumentError, BakitClient3 as BakitClient, BakitError, BaseClientManager, BaseCommandContext, BaseParam, BaseParamSchema, ChatInputContext, Command, CommandManager, CommandOptionsSchema, Context, EVENT_INTENT_MAPPING, HookOrder, HookState, Instance, LifecycleManager, Listener, ListenerManager, ListenerOptionsSchema, MessageContext, NumberParam, NumberParamSchema, ParamUserType, Params, ProjectConfigSchema, StringParam, StringParamSchema, defineCommand, defineConfig, defineListener, getConfig, loadConfig, tokenize, useApp, validateParamsOrder };
830
+ export { $jiti, ArgumentError, BakitClient2 as BakitClient, BakitError, BaseClientManager, BaseCommandContext, BaseParam, BaseParamSchema, ChatInputContext, Command, CommandManager, CommandOptionsSchema, Context, EVENT_INTENT_MAPPING, HookOrder, HookState, Instance, LifecycleManager, Listener, ListenerManager, ListenerOptionsSchema, MessageContext, NumberParam, NumberParamSchema, ParamUserType, Params, ProjectConfigSchema, StringParam, StringParamSchema, defineCommand, defineConfig, defineListener, getConfig, loadConfig, tokenize, useApp, validateParamsOrder };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bakit",
3
- "version": "2.0.0-alpha.6",
3
+ "version": "2.0.0-alpha.8",
4
4
  "description": "A framework for discord.js",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",