seyfert 2.1.1-dev-11767975974.0 → 2.1.1-dev-11842640994.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/api/api.d.ts CHANGED
@@ -19,6 +19,7 @@ export declare class ApiHandler {
19
19
  }>;
20
20
  onRatelimit?: OnRatelimitCallback;
21
21
  constructor(options: ApiHandlerOptions);
22
+ set debug(active: boolean);
22
23
  get proxy(): APIRoutes;
23
24
  globalUnblock(): void;
24
25
  request<T = unknown>(method: HttpMethods, url: `/${string}`, { auth, ...request }?: ApiRequestOptions): Promise<T>;
package/lib/api/api.js CHANGED
@@ -20,16 +20,13 @@ class ApiHandler {
20
20
  constructor(options) {
21
21
  this.options = {
22
22
  baseUrl: 'api/v10',
23
- domain: 'https://discord.com',
23
+ domain: common_1.BASE_HOST,
24
24
  type: 'Bot',
25
25
  ...options,
26
26
  userAgent: shared_1.DefaultUserAgent,
27
27
  };
28
- if (options.debug) {
29
- this.debugger = new common_1.Logger({
30
- name: '[API]',
31
- });
32
- }
28
+ if (options.debug)
29
+ this.debug = true;
33
30
  const worker_threads = (0, common_1.lazyLoadPackage)('node:worker_threads');
34
31
  if (options.workerProxy && !worker_threads?.parentPort)
35
32
  throw new Error('Cannot use workerProxy without a parent.');
@@ -41,6 +38,13 @@ class ApiHandler {
41
38
  parentPort = worker_threads.parentPort;
42
39
  }
43
40
  }
41
+ set debug(active) {
42
+ this.debugger = active
43
+ ? new common_1.Logger({
44
+ name: '[API]',
45
+ })
46
+ : undefined;
47
+ }
44
48
  get proxy() {
45
49
  return (this._proxy_ ??= new Router_1.Router(this).createProxy());
46
50
  }
@@ -34,7 +34,6 @@ export type DisabledCache = {
34
34
  export declare class Cache {
35
35
  intents: number;
36
36
  adapter: Adapter;
37
- readonly disabledCache: DisabledCache;
38
37
  users?: Users;
39
38
  guilds?: Guilds;
40
39
  members?: Members;
@@ -49,7 +48,8 @@ export declare class Cache {
49
48
  messages?: Messages;
50
49
  bans?: Bans;
51
50
  __logger__?: Logger;
52
- constructor(intents: number, adapter: Adapter, disabledCache?: DisabledCache, client?: UsingClient);
51
+ constructor(intents: number, adapter: Adapter, disabledCache: DisabledCache, client: UsingClient);
52
+ buildCache(disabledCache: DisabledCache, client: UsingClient): void;
53
53
  flush(): ReturnCache<void>;
54
54
  hasIntent(intent: keyof typeof GatewayIntentBits): boolean;
55
55
  get hasGuildsIntent(): boolean;
@@ -76,7 +76,6 @@ export declare class Cache {
76
76
  members: import("..").GuildMember[];
77
77
  users: import("..").User[];
78
78
  channels: NonNullable<ReturnCache<import("..").AllChannels | undefined>>[];
79
- messages: import("..").Message[];
80
79
  voiceStates: import("..").VoiceState[];
81
80
  presences: (Omit<import("../types").GatewayPresenceUpdate, "user"> & {
82
81
  id: string;
@@ -94,6 +93,7 @@ export declare class Cache {
94
93
  allow: import("../structures/extra/Permissions").PermissionsBitField;
95
94
  guildId: string;
96
95
  }[][];
96
+ messages: import("..").Message[];
97
97
  bans: import("../structures/GuildBan").GuildBan[];
98
98
  }>>;
99
99
  bulkPatch(keys: (readonly [
@@ -117,6 +117,7 @@ export declare class Cache {
117
117
  string
118
118
  ])[]): Promise<void>;
119
119
  onPacket(event: GatewayDispatchPayload): Promise<void>;
120
+ protected onPacketDefault(event: GatewayDispatchPayload): Promise<void>;
120
121
  testAdapter(): Promise<void>;
121
122
  private testUsersAndMembers;
122
123
  private testChannelsAndOverwrites;
@@ -40,7 +40,6 @@ __exportStar(require("./adapters/index"), exports);
40
40
  class Cache {
41
41
  intents;
42
42
  adapter;
43
- disabledCache;
44
43
  // non-guild based
45
44
  users;
46
45
  guilds;
@@ -58,74 +57,33 @@ class Cache {
58
57
  messages;
59
58
  bans;
60
59
  __logger__;
61
- constructor(intents, adapter, disabledCache = {}, client) {
60
+ constructor(intents, adapter, disabledCache, client) {
62
61
  this.intents = intents;
63
62
  this.adapter = adapter;
64
- this.disabledCache = disabledCache;
63
+ this.buildCache(disabledCache, client);
64
+ }
65
+ buildCache(disabledCache, client) {
65
66
  // non-guild based
66
- if (!this.disabledCache.users) {
67
- this.users = new users_1.Users(this, client);
68
- }
69
- if (!this.disabledCache.guilds) {
70
- this.guilds = new guilds_1.Guilds(this, client);
71
- }
67
+ this.users = disabledCache.users ? undefined : new users_1.Users(this, client);
68
+ this.guilds = disabledCache.guilds ? undefined : new guilds_1.Guilds(this, client);
72
69
  // guild related
73
- if (!this.disabledCache.members) {
74
- this.members = new members_1.Members(this, client);
75
- }
76
- if (!this.disabledCache.voiceStates) {
77
- this.voiceStates = new voice_states_1.VoiceStates(this, client);
78
- }
70
+ this.members = disabledCache.members ? undefined : new members_1.Members(this, client);
71
+ this.voiceStates = disabledCache.voiceStates ? undefined : new voice_states_1.VoiceStates(this, client);
79
72
  // guild based
80
- if (!this.disabledCache.roles) {
81
- this.roles = new roles_1.Roles(this, client);
82
- }
83
- if (!this.disabledCache.overwrites) {
84
- this.overwrites = new overwrites_1.Overwrites(this, client);
85
- }
86
- if (!this.disabledCache.channels) {
87
- this.channels = new channels_1.Channels(this, client);
88
- }
89
- if (!this.disabledCache.emojis) {
90
- this.emojis = new emojis_1.Emojis(this, client);
91
- }
92
- if (!this.disabledCache.stickers) {
93
- this.stickers = new stickers_1.Stickers(this, client);
94
- }
95
- if (!this.disabledCache.presences) {
96
- this.presences = new presence_1.Presences(this, client);
97
- }
98
- if (!this.disabledCache.stageInstances) {
99
- this.stageInstances = new stage_instances_1.StageInstances(this, client);
100
- }
101
- if (!this.disabledCache.messages) {
102
- this.messages = new messages_1.Messages(this, client);
103
- }
104
- if (!this.disabledCache.bans) {
105
- this.bans = new bans_1.Bans(this, client);
106
- }
107
- if (this.disabledCache.onPacket) {
108
- //@ts-expect-error
109
- this.onPacket = () => {
110
- // disable cache
111
- };
112
- }
113
- }
114
- /** @internal */
115
- __setClient(client) {
116
- this.users?.__setClient(client);
117
- this.guilds?.__setClient(client);
118
- this.members?.__setClient(client);
119
- this.voiceStates?.__setClient(client);
120
- this.roles?.__setClient(client);
121
- this.overwrites?.__setClient(client);
122
- this.channels?.__setClient(client);
123
- this.emojis?.__setClient(client);
124
- this.stickers?.__setClient(client);
125
- this.presences?.__setClient(client);
126
- this.stageInstances?.__setClient(client);
127
- this.messages?.__setClient(client);
128
- this.bans?.__setClient(client);
73
+ this.roles = disabledCache.roles ? undefined : new roles_1.Roles(this, client);
74
+ this.overwrites = disabledCache.overwrites ? undefined : new overwrites_1.Overwrites(this, client);
75
+ this.channels = disabledCache.channels ? undefined : new channels_1.Channels(this, client);
76
+ this.emojis = disabledCache.emojis ? undefined : new emojis_1.Emojis(this, client);
77
+ this.stickers = disabledCache.stickers ? undefined : new stickers_1.Stickers(this, client);
78
+ this.presences = disabledCache.presences ? undefined : new presence_1.Presences(this, client);
79
+ this.stageInstances = disabledCache.stageInstances ? undefined : new stage_instances_1.StageInstances(this, client);
80
+ this.messages = disabledCache.messages ? undefined : new messages_1.Messages(this, client);
81
+ this.bans = disabledCache.bans ? undefined : new bans_1.Bans(this, client);
82
+ this.onPacket = disabledCache.onPacket
83
+ ? (() => {
84
+ //
85
+ })
86
+ : this.onPacketDefault.bind(this);
129
87
  }
130
88
  flush() {
131
89
  return this.adapter.flush();
@@ -353,7 +311,10 @@ class Cache {
353
311
  await this.adapter.bulkAddToRelationShip(relationshipsData);
354
312
  await this.adapter.bulkSet(allData);
355
313
  }
356
- async onPacket(event) {
314
+ onPacket(event) {
315
+ return this.onPacketDefault(event);
316
+ }
317
+ async onPacketDefault(event) {
357
318
  switch (event.t) {
358
319
  case 'READY':
359
320
  await this.users?.set(event.d.user.id, event.d.user);
@@ -3,9 +3,9 @@ import type { GatewayIntentBits } from '../../../types';
3
3
  import type { Cache, ReturnCache } from '../../index';
4
4
  export declare class BaseResource<T = any, S = any> {
5
5
  protected cache: Cache;
6
- client: UsingClient;
6
+ readonly client: UsingClient;
7
7
  namespace: string;
8
- constructor(cache: Cache, client?: UsingClient);
8
+ constructor(cache: Cache, client: UsingClient);
9
9
  filter(data: any, id: string): boolean;
10
10
  get adapter(): import("../../index").Adapter;
11
11
  removeIfNI(intent: keyof typeof GatewayIntentBits, id: string): import("../../../common").Awaitable<void>;
@@ -8,12 +8,6 @@ class BaseResource {
8
8
  namespace = 'base';
9
9
  constructor(cache, client) {
10
10
  this.cache = cache;
11
- if (client) {
12
- this.client = client;
13
- }
14
- }
15
- /** @internal */
16
- __setClient(client) {
17
11
  this.client = client;
18
12
  }
19
13
  //@ts-expect-error
@@ -3,9 +3,9 @@ import type { GatewayIntentBits } from '../../../types';
3
3
  import type { Cache, ReturnCache } from '../../index';
4
4
  export declare class GuildBasedResource<T = any, S = any> {
5
5
  protected cache: Cache;
6
- client: UsingClient;
6
+ readonly client: UsingClient;
7
7
  namespace: string;
8
- constructor(cache: Cache, client?: UsingClient);
8
+ constructor(cache: Cache, client: UsingClient);
9
9
  filter(data: any, id: string, guild_id: string): boolean;
10
10
  parse(data: any, id: string, guild_id: string): any;
11
11
  get adapter(): import("../../index").Adapter;
@@ -8,12 +8,6 @@ class GuildBasedResource {
8
8
  namespace = 'base';
9
9
  constructor(cache, client) {
10
10
  this.cache = cache;
11
- if (client) {
12
- this.client = client;
13
- }
14
- }
15
- /** @internal */
16
- __setClient(client) {
17
11
  this.client = client;
18
12
  }
19
13
  //@ts-expect-error
@@ -3,9 +3,9 @@ import type { GatewayIntentBits } from '../../../types';
3
3
  import type { Cache, ReturnCache } from '../../index';
4
4
  export declare class GuildRelatedResource<T = any, S = any> {
5
5
  protected cache: Cache;
6
- client: UsingClient;
6
+ readonly client: UsingClient;
7
7
  namespace: string;
8
- constructor(cache: Cache, client?: UsingClient);
8
+ constructor(cache: Cache, client: UsingClient);
9
9
  filter(data: any, id: string, guild_id?: string): boolean;
10
10
  parse(data: any, id: string, guild_id: string): any;
11
11
  get adapter(): import("../../index").Adapter;
@@ -8,12 +8,6 @@ class GuildRelatedResource {
8
8
  namespace = 'base';
9
9
  constructor(cache, client) {
10
10
  this.cache = cache;
11
- if (client) {
12
- this.client = client;
13
- }
14
- }
15
- /** @internal */
16
- __setClient(client) {
17
11
  this.client = client;
18
12
  }
19
13
  //@ts-expect-error
@@ -1,5 +1,5 @@
1
1
  import { ApiHandler } from '../api';
2
- import type { Adapter } from '../cache';
2
+ import type { Adapter, DisabledCache } from '../cache';
3
3
  import { Cache } from '../cache';
4
4
  import type { Command, CommandContext, ContextMenuCommand, ExtendedRC, ExtendedRCLocations, ExtraProps, MenuCommandContext, RegisteredMiddlewares, SubCommand, UsingClient } from '../commands';
5
5
  import { type InferWithPrefix, type MiddlewareContext } from '../commands/applications/shared';
@@ -155,7 +155,7 @@ export interface ServicesOptions {
155
155
  rest?: ApiHandler;
156
156
  cache?: {
157
157
  adapter?: Adapter;
158
- disabledCache?: boolean | Cache['disabledCache'] | ((cacheType: keyof Cache['disabledCache']) => boolean);
158
+ disabledCache?: boolean | DisabledCache | ((cacheType: keyof DisabledCache) => boolean);
159
159
  };
160
160
  langs?: {
161
161
  default?: string;
@@ -14,8 +14,8 @@ const voiceStates_1 = require("../common/shorters/voiceStates");
14
14
  const handler_2 = require("../components/handler");
15
15
  const handler_3 = require("../langs/handler");
16
16
  class BaseClient {
17
- rest;
18
- cache;
17
+ rest = new api_1.ApiHandler({ token: 'INVALID' });
18
+ cache = new cache_1.Cache(0, new cache_1.MemoryAdapter(), {}, this);
19
19
  applications = new common_1.ApplicationShorter(this);
20
20
  users = new common_1.UsersShorter(this);
21
21
  channels = new common_1.ChannelShorter(this);
@@ -122,6 +122,7 @@ class BaseClient {
122
122
  }
123
123
  setServices({ rest, cache, langs, middlewares, handleCommand }) {
124
124
  if (rest) {
125
+ rest.onRatelimit ??= this.rest.onRatelimit?.bind(rest);
125
126
  this.rest = rest;
126
127
  }
127
128
  if (cache) {
@@ -141,7 +142,7 @@ class BaseClient {
141
142
  'users',
142
143
  'voiceStates',
143
144
  ];
144
- let disabledCache = this.cache?.disabledCache ?? {};
145
+ let disabledCache = {};
145
146
  if (typeof cache.disabledCache === 'boolean') {
146
147
  for (const i of caches) {
147
148
  disabledCache[i] = cache.disabledCache;
@@ -155,7 +156,10 @@ class BaseClient {
155
156
  else if (typeof cache.disabledCache === 'object') {
156
157
  disabledCache = cache.disabledCache;
157
158
  }
158
- this.cache = new cache_1.Cache(this.cache?.intents ?? 0, cache?.adapter ?? this.cache?.adapter ?? new cache_1.MemoryAdapter(), disabledCache, this);
159
+ if (cache.adapter)
160
+ this.cache.adapter = cache.adapter;
161
+ if (cache.disabledCache)
162
+ this.cache.buildCache(disabledCache, this);
159
163
  }
160
164
  if (middlewares) {
161
165
  this.middlewares = middlewares;
@@ -190,21 +194,10 @@ class BaseClient {
190
194
  await this.loadComponents(options.componentsDir);
191
195
  const { token: tokenRC, debug } = await this.getRC();
192
196
  const token = options?.token ?? tokenRC;
193
- if (!this.rest) {
194
- BaseClient.assertString(token, 'token is not a string');
195
- this.rest = new api_1.ApiHandler({
196
- token,
197
- baseUrl: 'api/v10',
198
- domain: 'https://discord.com',
199
- debug,
200
- });
201
- }
202
- if (this.cache) {
203
- this.cache.__setClient(this);
204
- }
205
- else {
206
- this.cache = new cache_1.Cache(0, new cache_1.MemoryAdapter(), {}, this);
207
- }
197
+ BaseClient.assertString(token, 'token is not a string');
198
+ if (this.rest.options.token === 'INVALID')
199
+ this.rest.options.token = token;
200
+ this.rest.debug = debug;
208
201
  if (!this.handleCommand)
209
202
  this.handleCommand = new handle_1.HandleCommand(this);
210
203
  // The reason of this method is so for adapters that need to connect somewhere, have time to connect.
@@ -223,7 +216,6 @@ class BaseClient {
223
216
  });
224
217
  }
225
218
  syncCachePath(cachePath) {
226
- this.logger.debug('Syncing commands cache');
227
219
  return node_fs_1.promises.writeFile(cachePath, JSON.stringify(this.commands.values.filter(cmd => !('ignore' in cmd) || cmd.ignore !== shared_1.IgnoreCommand.Slash).map(x => x.toJSON())));
228
220
  }
229
221
  async uploadCommands({ applicationId, cachePath } = {}) {
@@ -68,6 +68,7 @@ class Client extends base_1.BaseClient {
68
68
  const { token: tokenRC, intents: intentsRC, debug: debugRC } = await this.getRC();
69
69
  const token = options?.token ?? tokenRC;
70
70
  const intents = options?.connection?.intents ?? intentsRC;
71
+ this.cache.intents = intents;
71
72
  if (!this.gateway) {
72
73
  base_1.BaseClient.assertString(token, 'token is not a string');
73
74
  this.gateway = new websocket_1.ShardManager({
@@ -95,7 +96,6 @@ class Client extends base_1.BaseClient {
95
96
  },
96
97
  });
97
98
  }
98
- this.cache.intents = this.gateway.options.intents;
99
99
  if (execute) {
100
100
  await this.execute(options.connection);
101
101
  }
@@ -109,7 +109,6 @@ class Client extends base_1.BaseClient {
109
109
  this.collectors.run('RAW', packet, this),
110
110
  ]); //ignore promise
111
111
  switch (packet.t) {
112
- // Cases where we must obtain the old data before updating
113
112
  case 'GUILD_MEMBER_UPDATE':
114
113
  {
115
114
  if (!this.memberUpdateHandler.check(packet.d)) {
@@ -1,14 +1,15 @@
1
- import { type DeepPartial, type When } from '../common';
1
+ import { type DeepPartial, type MakeRequired, type When } from '../common';
2
2
  import { EventHandler } from '../events';
3
3
  import type { GatewayDispatchPayload } from '../types';
4
4
  import { Shard, type ShardManagerOptions, type WorkerData } from '../websocket';
5
5
  import type { WorkerMessage, WorkerShardInfo } from '../websocket/discord/worker';
6
- import type { ManagerMessages } from '../websocket/discord/workermanager';
6
+ import type { ManagerMessages, ManagerSpawnShards } from '../websocket/discord/workermanager';
7
7
  import type { BaseClientOptions, ServicesOptions, StartOptions } from './base';
8
8
  import { BaseClient } from './base';
9
9
  import type { Client, ClientOptions } from './client';
10
10
  import { MemberUpdateHandler } from '../websocket/discord/events/memberUpdate';
11
11
  import { PresenceUpdateHandler } from '../websocket/discord/events/presenceUpdate';
12
+ import type { ShardData } from '../websocket/discord/shared';
12
13
  import { Collectors } from './collectors';
13
14
  import { type ClientUserStructure } from './transformers';
14
15
  export declare class WorkerClient<Ready extends boolean = boolean> extends BaseClient {
@@ -40,8 +41,10 @@ export declare class WorkerClient<Ready extends boolean = boolean> extends BaseC
40
41
  handleManagerMessages(data: ManagerMessages): Promise<any>;
41
42
  private generateNonce;
42
43
  private generateSendPromise;
43
- tellWorker<R>(workerId: number, func: (_: this) => R): Promise<R>;
44
- tellWorkers<R>(func: (_: this) => R): Promise<Awaited<R>[]>;
44
+ tellWorker<R, V extends Record<string, unknown>>(workerId: number, func: (_: this, vars: V) => R, vars: V): Promise<R>;
45
+ tellWorkers<R, V extends Record<string, unknown>>(func: (_: this, vars: V) => R, vars: V): Promise<Awaited<R>[]>;
46
+ createShard(id: number, data: Pick<ManagerSpawnShards, 'info' | 'compress'>): Shard;
47
+ resumeShard(shardId: number, shardData: MakeRequired<ShardData>): Promise<unknown>;
45
48
  protected onPacket(packet: GatewayDispatchPayload, shardId: number): Promise<void>;
46
49
  }
47
50
  export declare function generateShardInfo(shard: Shard): WorkerShardInfo;
@@ -20,7 +20,7 @@ try {
20
20
  debug: process.env.SEYFERT_WORKER_DEBUG === 'true',
21
21
  intents: Number(process.env.SEYFERT_WORKER_INTENTS),
22
22
  path: process.env.SEYFERT_WORKER_PATH,
23
- shards: process.env.SEYFERT_WORKER_SHARDS.split(',').map(id => Number(id)),
23
+ shards: JSON.parse(process.env.SEYFERT_WORKER_SHARDS),
24
24
  token: process.env.SEYFERT_WORKER_TOKEN,
25
25
  workerId: Number(process.env.SEYFERT_WORKER_WORKERID),
26
26
  workerProxy: process.env.SEYFERT_WORKER_WORKERPROXY === 'true',
@@ -28,6 +28,8 @@ try {
28
28
  mode: process.env.SEYFERT_WORKER_MODE,
29
29
  resharding: process.env.SEYFERT_WORKER_RESHARDING === 'true',
30
30
  totalWorkers: Number(process.env.SEYFERT_WORKER_TOTALWORKERS),
31
+ info: JSON.parse(process.env.SEYFERT_WORKER_INFO),
32
+ compress: process.env.SEYFERT_WORKER_COMPRESS === 'true',
31
33
  };
32
34
  }
33
35
  catch {
@@ -62,7 +64,7 @@ class WorkerClient extends base_1.BaseClient {
62
64
  }
63
65
  setServices(rest) {
64
66
  super.setServices(rest);
65
- if (rest.cache) {
67
+ if (rest.cache?.adapter) {
66
68
  this.__setServicesCache = true;
67
69
  }
68
70
  }
@@ -82,13 +84,8 @@ class WorkerClient extends base_1.BaseClient {
82
84
  this.logger = new __1.Logger({
83
85
  name: `[Worker #${workerData.workerId}]`,
84
86
  });
85
- if (this.__setServicesCache) {
86
- this.setServices({
87
- cache: {
88
- disabledCache: this.cache.disabledCache,
89
- },
90
- });
91
- }
87
+ if (this.__setServicesCache)
88
+ delete this.__setServicesCache;
92
89
  else {
93
90
  const adapter = new cache_1.WorkerAdapter(workerData);
94
91
  if (this.options.postMessage) {
@@ -97,11 +94,9 @@ class WorkerClient extends base_1.BaseClient {
97
94
  this.setServices({
98
95
  cache: {
99
96
  adapter,
100
- disabledCache: this.cache.disabledCache,
101
97
  },
102
98
  });
103
99
  }
104
- delete this.__setServicesCache;
105
100
  if (workerData.debug) {
106
101
  this.debugger = new __1.Logger({
107
102
  name: `[Worker #${workerData.workerId}]`,
@@ -117,6 +112,7 @@ class WorkerClient extends base_1.BaseClient {
117
112
  }),
118
113
  });
119
114
  }
115
+ this.cache.intents = workerData.intents;
120
116
  this.postMessage({
121
117
  type: workerData.resharding ? 'WORKER_START_RESHARDING' : 'WORKER_START',
122
118
  workerId: workerData.workerId,
@@ -126,7 +122,6 @@ class WorkerClient extends base_1.BaseClient {
126
122
  }
127
123
  await super.start(options);
128
124
  await this.loadEvents(options.eventsDir);
129
- this.cache.intents = workerData.intents;
130
125
  }
131
126
  async loadEvents(dir) {
132
127
  dir ??= await this.getRC().then(x => ('events' in x.locations ? x.locations.events : undefined));
@@ -250,37 +245,13 @@ class WorkerClient extends base_1.BaseClient {
250
245
  break;
251
246
  case 'SPAWN_SHARDS':
252
247
  {
253
- const onPacket = this.onPacket.bind(this);
254
- const handlePayload = this.options?.handlePayload?.bind(this);
255
- const self = this;
256
248
  for (const id of workerData.shards) {
257
249
  const existsShard = this.shards.has(id);
258
250
  if (existsShard) {
259
251
  this.logger.warn(`Trying to spawn existing shard #${id}`);
260
252
  continue;
261
253
  }
262
- const shard = new websocket_1.Shard(id, {
263
- token: workerData.token,
264
- intents: workerData.intents,
265
- info: data.info,
266
- compress: data.compress,
267
- debugger: this.debugger,
268
- properties: {
269
- ...websocket_1.properties,
270
- ...this.options.gateway?.properties,
271
- },
272
- async handlePayload(shardId, payload) {
273
- await handlePayload?.(shardId, payload);
274
- await onPacket(payload, shardId);
275
- if (self.options.sendPayloadToParent)
276
- self.postMessage({
277
- workerId: workerData.workerId,
278
- shardId,
279
- type: 'RECEIVE_PAYLOAD',
280
- payload,
281
- });
282
- },
283
- });
254
+ const shard = this.createShard(id, data);
284
255
  this.shards.set(id, shard);
285
256
  this.postMessage({
286
257
  type: 'CONNECT_QUEUE',
@@ -335,7 +306,7 @@ class WorkerClient extends base_1.BaseClient {
335
306
  let result;
336
307
  try {
337
308
  result = await eval(`
338
- (${data.func})(this)
309
+ (${data.func})(this, ${data.vars})
339
310
  `);
340
311
  }
341
312
  catch (e) {
@@ -410,7 +381,7 @@ class WorkerClient extends base_1.BaseClient {
410
381
  this.promises.set(nonce, { resolve: res, timeout });
411
382
  });
412
383
  }
413
- tellWorker(workerId, func) {
384
+ tellWorker(workerId, func, vars) {
414
385
  const nonce = this.generateNonce();
415
386
  this.postMessage({
416
387
  type: 'EVAL_TO_WORKER',
@@ -418,23 +389,67 @@ class WorkerClient extends base_1.BaseClient {
418
389
  toWorkerId: workerId,
419
390
  workerId: workerData.workerId,
420
391
  nonce,
392
+ vars: JSON.stringify(vars),
421
393
  });
422
394
  return this.generateSendPromise(nonce);
423
395
  }
424
- tellWorkers(func) {
396
+ tellWorkers(func, vars) {
425
397
  const promises = [];
426
398
  for (let i = 0; i < workerData.totalWorkers; i++) {
427
- promises.push(this.tellWorker(i, func));
399
+ promises.push(this.tellWorker(i, func, vars));
428
400
  }
429
401
  return Promise.all(promises);
430
402
  }
403
+ createShard(id, data) {
404
+ const onPacket = this.onPacket.bind(this);
405
+ const handlePayload = this.options?.handlePayload?.bind(this);
406
+ const self = this;
407
+ const shard = new websocket_1.Shard(id, {
408
+ token: workerData.token,
409
+ intents: workerData.intents,
410
+ info: data.info,
411
+ compress: data.compress,
412
+ debugger: this.debugger,
413
+ properties: {
414
+ ...websocket_1.properties,
415
+ ...this.options.gateway?.properties,
416
+ },
417
+ async handlePayload(shardId, payload) {
418
+ await handlePayload?.(shardId, payload);
419
+ await onPacket(payload, shardId);
420
+ if (self.options.sendPayloadToParent)
421
+ self.postMessage({
422
+ workerId: workerData.workerId,
423
+ shardId,
424
+ type: 'RECEIVE_PAYLOAD',
425
+ payload,
426
+ });
427
+ },
428
+ });
429
+ return shard;
430
+ }
431
+ async resumeShard(shardId, shardData) {
432
+ const exists = (await this.tellWorkers((r, vars) => r.shards.has(vars.shardId), { shardId })).some(x => x);
433
+ if (exists)
434
+ throw new Error('Cannot override existing shard');
435
+ const shard = this.createShard(shardId, {
436
+ info: this.workerData.info,
437
+ compress: this.workerData.compress,
438
+ });
439
+ shard.data = shardData;
440
+ this.shards.set(shardId, shard);
441
+ return this.postMessage({
442
+ workerId: this.workerId,
443
+ shardId,
444
+ type: 'CONNECT_QUEUE',
445
+ });
446
+ }
431
447
  async onPacket(packet, shardId) {
432
448
  Promise.allSettled([
433
449
  this.events?.runEvent('RAW', this, packet, shardId, false),
434
450
  this.collectors.run('RAW', packet, this),
435
451
  ]); //ignore promise
436
452
  switch (packet.t) {
437
- //// Cases where we must obtain the old data before updating
438
453
  case 'GUILD_MEMBER_UPDATE':
439
454
  {
440
455
  if (!this.memberUpdateHandler.check(packet.d)) {
@@ -39,8 +39,8 @@ export declare abstract class ContextMenuCommand {
39
39
  reload(): Promise<void>;
40
40
  abstract run?(context: MenuCommandContext<any>): any;
41
41
  onAfterRun?(context: MenuCommandContext<any>, error: unknown | undefined): any;
42
- onRunError(context: MenuCommandContext<any, never>, error: unknown): any;
43
- onMiddlewaresError(context: MenuCommandContext<any, never>, error: string): any;
44
- onBotPermissionsFail(context: MenuCommandContext<any, never>, permissions: PermissionStrings): any;
45
- onInternalError(client: UsingClient, command: ContextMenuCommand, error?: unknown): any;
42
+ onRunError?(context: MenuCommandContext<any, never>, error: unknown): any;
43
+ onMiddlewaresError?(context: MenuCommandContext<any, never>, error: string): any;
44
+ onBotPermissionsFail?(context: MenuCommandContext<any, never>, permissions: PermissionStrings): any;
45
+ onInternalError?(client: UsingClient, command: ContextMenuCommand, error?: unknown): any;
46
46
  }
@@ -39,17 +39,5 @@ class ContextMenuCommand {
39
39
  const __tempCommand = await (0, common_1.magicImport)(this.__filePath).then(x => x.default ?? x);
40
40
  Object.setPrototypeOf(this, __tempCommand.prototype);
41
41
  }
42
- onRunError(context, error) {
43
- context.client.logger.fatal(`${this.name}.<onRunError>`, context.author.id, error);
44
- }
45
- onMiddlewaresError(context, error) {
46
- context.client.logger.fatal(`${this.name}.<onMiddlewaresError>`, context.author.id, error);
47
- }
48
- onBotPermissionsFail(context, permissions) {
49
- context.client.logger.fatal(`${this.name}.<onBotPermissionsFail>`, context.author.id, permissions);
50
- }
51
- onInternalError(client, command, error) {
52
- client.logger.fatal(command.name, error);
53
- }
54
42
  }
55
43
  exports.ContextMenuCommand = ContextMenuCommand;
@@ -40,7 +40,7 @@ class HandleCommand {
40
40
  if (context.guildId && command.botPermissions) {
41
41
  const permissions = this.checkPermissions(interaction.appPermissions, command.botPermissions);
42
42
  if (permissions)
43
- return command.onBotPermissionsFail(context, permissions);
43
+ return command.onBotPermissionsFail?.(context, permissions);
44
44
  }
45
45
  const resultGlobal = await this.runGlobalMiddlewares(command, context);
46
46
  if (typeof resultGlobal === 'boolean')
@@ -54,13 +54,13 @@ class HandleCommand {
54
54
  await command.onAfterRun?.(context, undefined);
55
55
  }
56
56
  catch (error) {
57
- await command.onRunError(context, error);
57
+ await command.onRunError?.(context, error);
58
58
  await command.onAfterRun?.(context, error);
59
59
  }
60
60
  }
61
61
  catch (error) {
62
62
  try {
63
- await command.onInternalError(this.client, command, error);
63
+ await command.onInternalError?.(this.client, command, error);
64
64
  }
65
65
  catch {
66
66
  // pass
@@ -448,15 +448,9 @@ class CommandHandler extends common_1.BaseHandler {
448
448
  if (!(commandInstance instanceof menu_1.ContextMenuCommand))
449
449
  return false;
450
450
  commandInstance.onAfterRun ??= this.client.options.commands?.defaults?.onAfterRun;
451
- //@ts-expect-error magic.
452
451
  commandInstance.onBotPermissionsFail ??= this.client.options.commands?.defaults?.onBotPermissionsFail;
453
- //@ts-expect-error magic.
454
452
  commandInstance.onInternalError ??= this.client.options.commands?.defaults?.onInternalError;
455
- //@ts-expect-error magic.
456
453
  commandInstance.onMiddlewaresError ??= this.client.options.commands?.defaults?.onMiddlewaresError;
457
- //@ts-expect-error magic.
458
- commandInstance.onPermissionsFail ??= this.client.options.commands?.defaults?.onPermissionsFail;
459
- //@ts-expect-error magic.
460
454
  commandInstance.onRunError ??= this.client.options.commands?.defaults?.onRunError;
461
455
  return commandInstance;
462
456
  }
@@ -3,6 +3,7 @@ import type { GuildMemberStructure, GuildStructure } from '../client/transformer
3
3
  import type { CommandMetadata, ExtendContext, GlobalMetadata, RegisteredMiddlewares, UsingClient } from '../commands';
4
4
  import { BaseContext } from '../commands/basecontext';
5
5
  import type { InteractionCreateBodyRequest, InteractionMessageUpdateBodyRequest, MakeRequired, ModalCreateBodyRequest, UnionToTuple } from '../common';
6
+ import type { Interaction } from '../structures/Interaction';
6
7
  export interface ModalContext extends BaseContext, ExtendContext {
7
8
  }
8
9
  /**
@@ -67,7 +68,7 @@ export declare class ModalContext<M extends keyof RegisteredMiddlewares = never>
67
68
  * @returns A promise that resolves when the response is deleted.
68
69
  */
69
70
  deleteResponse(): Promise<void | undefined>;
70
- modal(body: ModalCreateBodyRequest): any;
71
+ modal(body: ModalCreateBodyRequest): ReturnType<Interaction['modal']>;
71
72
  /**
72
73
  * Gets the channel of the interaction.
73
74
  * @param mode - The mode to fetch the channel.
@@ -192,20 +192,20 @@ class EventHandler extends common_1.BaseHandler {
192
192
  async runCustom(name, ...args) {
193
193
  const Event = this.values[name];
194
194
  if (!Event) {
195
- // @ts-expect-error working with non-existent types is hard
195
+ // @ts-expect-error
196
196
  return this.client.collectors.run(name, args, this.client);
197
197
  }
198
198
  try {
199
199
  if (Event.data.once && Event.fired) {
200
- // @ts-expect-error working with non-existent types is hard
200
+ // @ts-expect-error
201
201
  return this.client.collectors.run(name, args, this.client);
202
202
  }
203
203
  Event.fired = true;
204
204
  this.logger.debug(`executed a custom event [${name}]`, Event.data.once ? 'once' : '');
205
205
  await Promise.all([
206
- // @ts-expect-error working with non-existent types is hard
206
+ // @ts-expect-error
207
207
  Event.run(...args, this.client),
208
- // @ts-expect-error working with non-existent types is hard
208
+ // @ts-expect-error
209
209
  this.client.collectors.run(name, args, this.client),
210
210
  ]);
211
211
  }
@@ -75,8 +75,8 @@ class Shard {
75
75
  }
76
76
  clearTimeout(this.heart.nodeInterval);
77
77
  this.debugger?.debug(`[Shard #${this.id}] Connecting to ${this.currentGatewayURL}`);
78
- // @ts-expect-error @types/bun cause erros in compile
79
- // biome-ignore lint/correctness/noUndeclaredVariables: /\ bun lol
78
+ // @ts-expect-error Use native websocket when using Bun
79
+ // biome-ignore lint/correctness/noUndeclaredVariables: /\
80
80
  this.websocket = new basesocket_1.BaseSocket(typeof Bun === 'undefined' ? 'ws' : 'bun', this.currentGatewayURL);
81
81
  this.websocket.onmessage = ({ data }) => {
82
82
  this.handleMessage(data);
@@ -117,6 +117,8 @@ export interface WorkerData {
117
117
  workerId: number;
118
118
  debug: boolean;
119
119
  workerProxy: boolean;
120
+ info: APIGatewayBotInfo;
121
+ compress: boolean;
120
122
  __USING_WATCHER__?: boolean;
121
123
  resharding: boolean;
122
124
  }
@@ -57,6 +57,7 @@ export type WorkerSendEvalResponse = CreateWorkerMessage<'EVAL_RESPONSE', {
57
57
  export type WorkerSendToWorkerEval = CreateWorkerMessage<'EVAL_TO_WORKER', {
58
58
  func: string;
59
59
  nonce: string;
60
+ vars: string;
60
61
  toWorkerId: number;
61
62
  }>;
62
63
  export type WorkerMessage = WorkerRequestConnect | WorkerReceivePayload | WorkerSendResultPayload | WorkerSendCacheRequest | WorkerSendShardInfo | WorkerSendInfo | WorkerReady | WorkerShardsConnected | WorkerSendApiRequest | WorkerSendEvalResponse | WorkerSendToWorkerEval | WorkerStart | WorkerStartResharding | WorkerRequestConnectResharding | WorkerReadyResharding | WorkerDisconnectedAllShardsResharding;
@@ -68,8 +68,8 @@ export declare class WorkerManager extends Map<number, (ClusterWorker | WorkerTh
68
68
  send(data: GatewaySendPayload, shardId: number): Promise<true>;
69
69
  getShardInfo(shardId: number): Promise<WorkerShardInfo>;
70
70
  getWorkerInfo(workerId: number): Promise<WorkerInfo>;
71
- tellWorker<R>(workerId: number, func: (_: WorkerClient & UsingClient) => R): Promise<R>;
72
- tellWorkers<R>(func: (_: WorkerClient & UsingClient) => R): Promise<Awaited<R>[]>;
71
+ tellWorker<R, V extends Record<string, unknown>>(workerId: number, func: (_: WorkerClient & UsingClient, vars: V) => R, vars: V): Promise<R>;
72
+ tellWorkers<R, V extends Record<string, unknown>>(func: (_: WorkerClient & UsingClient, vars: V) => R, vars: V): Promise<Awaited<R>[]>;
73
73
  start(): Promise<void>;
74
74
  startResharding(): Promise<void>;
75
75
  }
@@ -113,10 +113,12 @@ export type ManagerSendApiResponse = CreateManagerMessage<'API_RESPONSE', {
113
113
  export type ManagerExecuteEvalToWorker = CreateManagerMessage<'EXECUTE_EVAL_TO_WORKER', {
114
114
  func: string;
115
115
  nonce: string;
116
+ vars: string;
116
117
  toWorkerId: number;
117
118
  }>;
118
119
  export type ManagerExecuteEval = CreateManagerMessage<'EXECUTE_EVAL', {
119
120
  func: string;
121
+ vars: string;
120
122
  nonce: string;
121
123
  }>;
122
124
  export type ManagerSendEvalResponse = CreateManagerMessage<'EVAL_RESPONSE', {
@@ -124,6 +124,11 @@ class WorkerManager extends Map {
124
124
  mode: this.options.mode,
125
125
  resharding,
126
126
  totalWorkers: shards.length,
127
+ info: {
128
+ ...this.options.info,
129
+ shards: this.totalShards,
130
+ },
131
+ compress: this.options.compress,
127
132
  });
128
133
  this.set(i, worker);
129
134
  });
@@ -149,7 +154,8 @@ class WorkerManager extends Map {
149
154
  if (workerData.resharding)
150
155
  env.SEYFERT_WORKER_RESHARDING = 'true';
151
156
  for (const i in workerData) {
152
- env[`SEYFERT_WORKER_${i.toUpperCase()}`] = workerData[i];
157
+ const data = workerData[i];
158
+ env[`SEYFERT_WORKER_${i.toUpperCase()}`] = typeof data === 'object' && data ? JSON.stringify(data) : data;
153
159
  }
154
160
  switch (this.options.mode) {
155
161
  case 'threads': {
@@ -381,6 +387,7 @@ class WorkerManager extends Map {
381
387
  func: message.func,
382
388
  type: 'EXECUTE_EVAL_TO_WORKER',
383
389
  toWorkerId: message.toWorkerId,
390
+ vars: message.vars,
384
391
  });
385
392
  this.generateSendPromise(nonce, 'Eval timeout').then(val => this.postMessage(message.workerId, {
386
393
  nonce: message.nonce,
@@ -440,19 +447,20 @@ class WorkerManager extends Map {
440
447
  this.postMessage(workerId, { nonce, type: 'WORKER_INFO' });
441
448
  return this.generateSendPromise(nonce, 'Get worker info timeout');
442
449
  }
443
- tellWorker(workerId, func) {
450
+ tellWorker(workerId, func, vars) {
444
451
  const nonce = this.generateNonce();
445
452
  this.postMessage(workerId, {
446
453
  type: 'EXECUTE_EVAL',
447
454
  func: func.toString(),
448
455
  nonce,
456
+ vars: JSON.stringify(vars),
449
457
  });
450
458
  return this.generateSendPromise(nonce);
451
459
  }
452
- tellWorkers(func) {
460
+ tellWorkers(func, vars) {
453
461
  const promises = [];
454
462
  for (const i of this.keys()) {
455
- promises.push(this.tellWorker(i, func));
463
+ promises.push(this.tellWorker(i, func, vars));
456
464
  }
457
465
  return Promise.all(promises);
458
466
  }
@@ -464,7 +472,7 @@ class WorkerManager extends Map {
464
472
  this.rest ??= new __1.ApiHandler({
465
473
  token: this.options.token,
466
474
  baseUrl: 'api/v10',
467
- domain: 'https://discord.com',
475
+ domain: common_1.BASE_HOST,
468
476
  debug: this.options.debug,
469
477
  });
470
478
  this.options.info ??= await this.rest.proxy.gateway.bot.get();
@@ -487,7 +495,7 @@ class WorkerManager extends Map {
487
495
  shardEnd: this.shardEnd,
488
496
  shardsPerWorker: this.shardsPerWorker,
489
497
  }, this.debugger);
490
- await this.prepareWorkers(spaces);
498
+ this.prepareWorkers(spaces);
491
499
  // Start workers queue
492
500
  this.workerQueue.shift()();
493
501
  await this.startResharding();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "seyfert",
3
- "version": "2.1.1-dev-11767975974.0",
3
+ "version": "2.1.1-dev-11842640994.0",
4
4
  "description": "The most advanced framework for discord bots",
5
5
  "main": "./lib/index.js",
6
6
  "module": "./lib/index.js",