bakit 2.0.0-alpha.7 → 2.0.0-alpha.9

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/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;
@@ -103,54 +109,27 @@ declare const BaseParamSchema: z.ZodObject<{
103
109
  description: z.ZodOptional<z.ZodString>;
104
110
  required: z.ZodDefault<z.ZodBoolean>;
105
111
  }, z.core.$strip>;
106
- declare const StringParamSchema: z.ZodPipe<z.ZodObject<{
112
+ declare const StringParamSchema: z.ZodObject<{
107
113
  name: z.ZodString;
108
114
  description: z.ZodOptional<z.ZodString>;
109
115
  required: z.ZodDefault<z.ZodBoolean>;
110
116
  maxLength: z.ZodOptional<z.ZodNumber>;
111
117
  minLength: z.ZodOptional<z.ZodNumber>;
112
- }, z.core.$strip>, z.ZodTransform<{
113
- name: string;
114
- required: boolean;
115
- description?: string | undefined;
116
- maxLength?: number | undefined;
117
- minLength?: number | undefined;
118
- } & {
119
- description: string;
120
- }, {
121
- name: string;
122
- required: boolean;
123
- description?: string | undefined;
124
- maxLength?: number | undefined;
125
- minLength?: number | undefined;
126
- }>>;
127
- declare const NumberParamSchema: z.ZodPipe<z.ZodObject<{
118
+ }, z.core.$strip>;
119
+ declare const NumberParamSchema: z.ZodObject<{
128
120
  name: z.ZodString;
129
121
  description: z.ZodOptional<z.ZodString>;
130
122
  required: z.ZodDefault<z.ZodBoolean>;
131
123
  maxValue: z.ZodOptional<z.ZodNumber>;
132
124
  minValue: z.ZodOptional<z.ZodNumber>;
133
- }, z.core.$strip>, z.ZodTransform<{
134
- name: string;
135
- required: boolean;
136
- description?: string | undefined;
137
- maxValue?: number | undefined;
138
- minValue?: number | undefined;
139
- } & {
140
- description: string;
141
- }, {
142
- name: string;
143
- required: boolean;
144
- description?: string | undefined;
145
- maxValue?: number | undefined;
146
- minValue?: number | undefined;
147
- }>>;
125
+ }, z.core.$strip>;
148
126
  type BaseParamOptions = z.input<typeof BaseParamSchema>;
149
127
  type StringOptions = z.input<typeof StringParamSchema>;
150
128
  type NumberOptions = z.input<typeof NumberParamSchema>;
151
129
 
152
130
  type ParamResolvedOutputType<OutputType, Required extends boolean = true> = Required extends true ? OutputType : OutputType | null;
153
131
  declare abstract class BaseParam<Options extends BaseParamOptions, OutputType, Required extends boolean = true> {
132
+ private schema;
154
133
  options: Options & {
155
134
  required: Required;
156
135
  };
@@ -163,7 +142,7 @@ declare abstract class BaseParam<Options extends BaseParamOptions, OutputType, R
163
142
  * @internal
164
143
  */
165
144
  readonly _type: Required extends true ? OutputType : OutputType | null;
166
- constructor(options: Options);
145
+ constructor(options: Options, schema: z$1.ZodObject);
167
146
  protected setOption(key: keyof Options, value: any): this;
168
147
  name(value: string): this;
169
148
  description(value: string): this;
@@ -298,11 +277,6 @@ declare function defineCommand<const ParamsList extends readonly AnyParam<any>[]
298
277
  params?: ParamsList;
299
278
  }) | string): Command<ParamsList>;
300
279
 
301
- declare class BaseClientManager {
302
- client: BakitClient;
303
- constructor(client: BakitClient);
304
- }
305
-
306
280
  declare class CommandManager extends BaseClientManager {
307
281
  commands: Collection<string, Command<any[]>>;
308
282
  loadModules(): Promise<Command[]>;
@@ -337,17 +311,39 @@ declare class ListenerManager extends BaseClientManager {
337
311
  getNeededIntents(): IntentsBitField;
338
312
  }
339
313
 
314
+ declare class ProjectCacheManager {
315
+ private readonly rootDir;
316
+ constructor(root?: string);
317
+ private ensureRoot;
318
+ getHash(data: unknown): string;
319
+ write(path: string, data: unknown): Promise<void>;
320
+ read<T>(path: string): Promise<T | null>;
321
+ clear(): Promise<void>;
322
+ clearSync(): void;
323
+ }
324
+
325
+ declare class Instance {
326
+ client: BakitClient;
327
+ cache: ProjectCacheManager;
328
+ constructor();
329
+ start(): Promise<void>;
330
+ private loadModules;
331
+ private initIntents;
332
+ }
333
+ declare function useApp(): Instance;
334
+
340
335
  type GetPrefixFunction = (message: Message) => Awaitable<string[] | string>;
341
336
  interface BakitClientEvents extends ClientEvents {
342
337
  ready: [BakitClient<true>];
343
338
  clientReady: [BakitClient<true>];
344
339
  }
345
340
  declare class BakitClient<Ready extends boolean = boolean> extends Client<Ready> {
341
+ instance: Instance;
346
342
  managers: {
347
343
  commands: CommandManager;
348
344
  listeners: ListenerManager;
349
345
  };
350
- constructor(options: ClientOptions);
346
+ constructor(options: ClientOptions, instance: Instance);
351
347
  /**
352
348
  * Check if the client is connected to gateway successfully and finished initialization.
353
349
  */
@@ -365,28 +361,9 @@ declare class BakitClient<Ready extends boolean = boolean> extends Client<Ready>
365
361
  [inspect.custom](): string;
366
362
  }
367
363
 
368
- declare class Instance {
364
+ declare class BaseClientManager {
369
365
  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);
366
+ constructor(client: BakitClient);
390
367
  }
391
368
 
392
369
  declare const Params: {
@@ -406,4 +383,14 @@ declare const Params: {
406
383
  }) => NumberParam<Required>;
407
384
  };
408
385
 
386
+ declare class BakitError extends Error {
387
+ constructor(message: string);
388
+ }
389
+
390
+ declare class ArgumentError extends BakitError {
391
+ target: string;
392
+ reason: string;
393
+ constructor(target: string, reason: string);
394
+ }
395
+
409
396
  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
@@ -1,9 +1,12 @@
1
1
  import { GatewayIntentBits, Events, Client, IntentsBitField, Collection, SlashCommandBuilder, SlashCommandStringOption, SlashCommandNumberOption, ChatInputCommandInteraction, Message } from 'discord.js';
2
- import z3, { z } from 'zod';
2
+ import z4, { 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();
@@ -320,6 +330,17 @@ var HookState = /* @__PURE__ */ ((HookState2) => (HookState2.Pre = "PRE", HookSt
320
330
  }
321
331
  }
322
332
  };
333
+ var ParamUserType = /* @__PURE__ */ ((ParamUserType2) => (ParamUserType2.Bot = "bot", ParamUserType2.Normal = "normal", ParamUserType2.Any = "any", ParamUserType2))(ParamUserType || {}), BaseParamSchema = z.object({
334
+ name: z.string(),
335
+ description: z.string().optional(),
336
+ required: z.boolean().default(true)
337
+ }), StringParamSchema = BaseParamSchema.extend({
338
+ maxLength: z.number().min(1).optional(),
339
+ minLength: z.number().min(1).optional()
340
+ }), NumberParamSchema = BaseParamSchema.extend({
341
+ maxValue: z.number().optional(),
342
+ minValue: z.number().optional()
343
+ });
323
344
 
324
345
  // src/errors/BakitError.ts
325
346
  var BakitError = class extends Error {
@@ -337,15 +358,26 @@ var ArgumentError = class extends BakitError {
337
358
  }
338
359
  };
339
360
 
340
- // src/command/param/Param.ts
361
+ // src/base/command/param/Param.ts
341
362
  var BaseParam = class {
342
- options;
343
- constructor(options) {
344
- this.options = { ...options, required: options.required ?? true };
363
+ constructor(options, schema) {
364
+ this.schema = schema;
365
+ let parsed = schema.parse({
366
+ ...options,
367
+ description: options.description ?? options.name
368
+ });
369
+ this.options = parsed;
345
370
  }
371
+ options;
346
372
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
347
373
  setOption(key, value) {
348
- return value === null ? delete this.options[key] : this.options[key] = value, this;
374
+ if (value === null)
375
+ return delete this.options[key], this;
376
+ let fieldValidator = this.schema.shape[key];
377
+ if (!fieldValidator)
378
+ return this.options[key] = value, this;
379
+ let parsedValue = fieldValidator.parse(value);
380
+ return this.options[key] = parsedValue, this;
349
381
  }
350
382
  name(value) {
351
383
  return this.setOption("name", value);
@@ -371,7 +403,7 @@ var BaseParam = class {
371
403
  }
372
404
  }, StringParam = class extends BaseParam {
373
405
  constructor(options) {
374
- super(BaseParam.getOptions(options));
406
+ super(BaseParam.getOptions(options), StringParamSchema);
375
407
  }
376
408
  required(value) {
377
409
  return super.required(value);
@@ -409,7 +441,7 @@ var BaseParam = class {
409
441
  }
410
442
  }, NumberParam = class extends BaseParam {
411
443
  constructor(options) {
412
- super(BaseParam.getOptions(options));
444
+ super(BaseParam.getOptions(options), NumberParamSchema);
413
445
  }
414
446
  required(value) {
415
447
  return super.required(value);
@@ -510,14 +542,7 @@ function defineCommand(options) {
510
542
  return new Command(options);
511
543
  }
512
544
 
513
- // src/base/BaseClientManager.ts
514
- var BaseClientManager = class {
515
- constructor(client) {
516
- this.client = client;
517
- }
518
- };
519
-
520
- // src/command/CommandManager.ts
545
+ // src/base/command/CommandManager.ts
521
546
  var CommandManager = class extends BaseClientManager {
522
547
  commands = new Collection();
523
548
  async loadModules() {
@@ -561,9 +586,9 @@ var CommandManager = class extends BaseClientManager {
561
586
  return this.commands.get(name);
562
587
  }
563
588
  };
564
- var ListenerOptionsSchema = z3.object({
565
- name: z3.enum(Events),
566
- once: z3.boolean().default(false)
589
+ var ListenerOptionsSchema = z4.object({
590
+ name: z4.enum(Events),
591
+ once: z4.boolean().default(false)
567
592
  }), Listener = class extends LifecycleManager {
568
593
  options;
569
594
  constructor(options) {
@@ -633,15 +658,17 @@ var ListenerManager = class extends BaseClientManager {
633
658
  }
634
659
  };
635
660
 
636
- // src/BakitClient.ts
637
- var BakitClient3 = class extends Client {
638
- managers;
639
- constructor(options) {
640
- super(options), this.managers = {
661
+ // src/base/BakitClient.ts
662
+ var BakitClient2 = class extends Client {
663
+ constructor(options, instance) {
664
+ super(options);
665
+ this.instance = instance;
666
+ this.managers = {
641
667
  commands: new CommandManager(this),
642
668
  listeners: new ListenerManager(this)
643
669
  };
644
670
  }
671
+ managers;
645
672
  /**
646
673
  * Check if the client is connected to gateway successfully and finished initialization.
647
674
  */
@@ -674,22 +701,8 @@ var BakitClient3 = class extends Client {
674
701
  return `${this.constructor.name} {}`;
675
702
  }
676
703
  };
677
- var ParamUserType = /* @__PURE__ */ ((ParamUserType2) => (ParamUserType2.Bot = "bot", ParamUserType2.Normal = "normal", ParamUserType2.Any = "any", ParamUserType2))(ParamUserType || {}), BaseParamSchema = z.object({
678
- name: z.string(),
679
- description: z.string().optional(),
680
- required: z.boolean().default(true)
681
- }), withDefaultDescription = (data) => ({
682
- ...data,
683
- description: data.description ?? `${data.name}`
684
- }), StringParamSchema = BaseParamSchema.extend({
685
- maxLength: z.number().min(1).optional(),
686
- minLength: z.number().min(1).optional()
687
- }).transform(withDefaultDescription), NumberParamSchema = BaseParamSchema.extend({
688
- maxValue: z.number().optional(),
689
- minValue: z.number().optional()
690
- }).transform(withDefaultDescription);
691
704
 
692
- // src/command/param/Params.ts
705
+ // src/base/command/param/Params.ts
693
706
  function createFactory(ctor) {
694
707
  return (...args) => new ctor(...args);
695
708
  }
@@ -704,8 +717,22 @@ var messageCommandHandler = defineListener(Events.MessageCreate), chatInputComma
704
717
  once: true
705
718
  });
706
719
  registerCommandsHandler.main(async (_, client) => {
707
- let { commands } = client.managers, data = commands.commands.map((cmd) => cmd.toSlashCommandJSON()), result = await client.application.commands.set(data);
708
- console.log(`Registered ${result.size} application command(s)`);
720
+ 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);
721
+ if (cachedMeta && cachedMeta.hash === currentHash) {
722
+ let { timestamp, count } = cachedMeta, time = new Date(timestamp).toLocaleString();
723
+ console.log(`${count} command(s) are up to date (Last sync: ${time}). Skipping registration.`);
724
+ return;
725
+ }
726
+ try {
727
+ let result = await client.application.commands.set(payload);
728
+ cache.write(CACHE_KEY, {
729
+ hash: currentHash,
730
+ timestamp: Date.now(),
731
+ count: result.size
732
+ }), cache.write("commands/debug_dump.json", payload), console.log(`Registered ${result.size} application command(s).`);
733
+ } catch (error) {
734
+ console.error("Failed to register commands:", error);
735
+ }
709
736
  });
710
737
  messageCommandHandler.main(async (_, message) => {
711
738
  let config = getConfig();
@@ -743,20 +770,61 @@ chatInputCommandHandler.main(async (_, interaction) => {
743
770
  }
744
771
  await command.execute(context, ...resolvedArgs);
745
772
  });
773
+ var ProjectCacheManager = class {
774
+ rootDir;
775
+ constructor(root = process.cwd()) {
776
+ this.rootDir = join(root, ".bakit"), this.ensureRoot();
777
+ }
778
+ ensureRoot() {
779
+ existsSync(this.rootDir) || mkdirSync(this.rootDir, { recursive: true });
780
+ }
781
+ getHash(data) {
782
+ return createHash("sha256").update(JSON.stringify(data)).digest("hex");
783
+ }
784
+ async write(path, data) {
785
+ let fullPath = join(this.rootDir, path), dir = dirname(fullPath);
786
+ await mkdir(dir, { recursive: true });
787
+ let content = typeof data == "string" ? data : JSON.stringify(data);
788
+ await writeFile(fullPath, content, "utf-8");
789
+ }
790
+ async read(path) {
791
+ let fullPath = join(this.rootDir, path);
792
+ try {
793
+ let content = await readFile(fullPath, "utf-8");
794
+ return JSON.parse(content);
795
+ } catch {
796
+ return null;
797
+ }
798
+ }
799
+ async clear() {
800
+ await rm(this.rootDir, { recursive: true, force: true });
801
+ }
802
+ clearSync() {
803
+ existsSync(this.rootDir) && rmSync(this.rootDir, { recursive: true, force: true });
804
+ }
805
+ };
746
806
 
747
- // src/Instance.ts
807
+ // src/base/Instance.ts
748
808
  var Instance = class {
749
809
  client;
810
+ cache;
811
+ constructor() {
812
+ this.cache = new ProjectCacheManager();
813
+ }
750
814
  async start() {
751
815
  await loadConfig();
752
816
  let config = getConfig();
753
- this.client = new BakitClient3({
754
- intents: []
755
- }), await this.loadModules(), this.initIntents(), await this.client.login(config.token);
817
+ this.client = new BakitClient2(
818
+ {
819
+ intents: [],
820
+ ...config.clientOptions
821
+ },
822
+ this
823
+ ), await this.loadModules(), this.initIntents(), await this.client.login(config.token);
756
824
  }
757
825
  loadModules() {
758
826
  let { managers } = this.client, { commands, listeners } = managers;
759
- return listeners.add(chatInputCommandHandler), listeners.add(messageCommandHandler), Promise.all([commands.loadModules(), listeners.loadModules()]);
827
+ return listeners.add(chatInputCommandHandler), listeners.add(messageCommandHandler), listeners.add(registerCommandsHandler), Promise.all([commands.loadModules(), listeners.loadModules()]);
760
828
  }
761
829
  initIntents() {
762
830
  let config = getConfig(), { options, managers } = this.client, { listeners } = managers, intents;
@@ -767,4 +835,4 @@ function useApp() {
767
835
  return new Instance();
768
836
  }
769
837
 
770
- 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 };
838
+ 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.7",
3
+ "version": "2.0.0-alpha.9",
4
4
  "description": "A framework for discord.js",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",