@kotori-bot/core 1.5.0 → 1.5.1

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.
@@ -1,12 +1,12 @@
1
1
 
2
2
  /**
3
3
  * @Package @kotori-bot/core
4
- * @Version 1.4.2-beta.1
4
+ * @Version 1.5.0
5
5
  * @Author Hotaru <biyuehuya@gmail.com>
6
6
  * @Copyright 2024 Hotaru. All rights reserved.
7
7
  * @License GPL-3.0
8
8
  * @Link https://github.com/kotorijs/kotori
9
- * @Date 2024/6/6 21:03:53
9
+ * @Date 2024/6/7 11:22:22
10
10
  */
11
11
 
12
12
  "use strict";
@@ -28,7 +28,6 @@ var __copyProps = (to, from, except, desc) => {
28
28
  }
29
29
  return to;
30
30
  };
31
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
32
31
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
33
32
  // If the importer is in node compatibility mode or this is not an ESM
34
33
  // file that has been converted to a CommonJS file using a Babel-
@@ -38,804 +37,35 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
38
37
  mod
39
38
  ));
40
39
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
41
-
42
- // src/components/core.ts
43
40
  var core_exports = {};
44
41
  __export(core_exports, {
45
42
  Core: () => Core,
46
43
  default: () => core_default
47
44
  });
48
45
  module.exports = __toCommonJS(core_exports);
49
- var import_tools8 = require("@kotori-bot/tools");
50
- var import_i18n2 = __toESM(require("@kotori-bot/i18n"));
51
- var import_fluoro2 = require("fluoro");
52
-
53
- // src/components/config.ts
54
- var import_tsukiko = __toESM(require("tsukiko"));
55
- var import_node_path = require("path");
56
46
  var import_tools = require("@kotori-bot/tools");
57
-
58
- // src/global/constants.ts
59
- var import_i18n = require("@kotori-bot/i18n");
60
- var OFFICIAL_MODULES_SCOPE = "@kotori-bot/";
61
- var PLUGIN_PREFIX = "kotori-plugin-";
62
- var DATABASE_PREFIX = `${PLUGIN_PREFIX}database-`;
63
- var ADAPTER_PREFIX = `${PLUGIN_PREFIX}adapter-`;
64
- var CUSTOM_PREFIX = `${PLUGIN_PREFIX}custom-`;
65
- var DEFAULT_PORT = 720;
66
- var DEFAULT_CORE_CONFIG = {
67
- global: {
68
- lang: import_i18n.DEFAULT_LANG,
69
- "command-prefix": "/",
70
- port: DEFAULT_PORT
71
- },
72
- adapter: {},
73
- plugin: {}
74
- };
75
-
76
- // src/global/symbols.ts
77
- var Symbols = class {
78
- static adapter = Symbol.for("kotori.core.adapter");
79
- static bot = Symbol.for("kotori.core.bot");
80
- static midware = Symbol.for("kotori.core.midware");
81
- static command = Symbol.for("kotori.core.command");
82
- static regexp = Symbol.for("kotori.core.regexp");
83
- static modules = Symbol.for("kotori.loader.module");
84
- static job = Symbol.for("kotori.loader.job");
85
- };
86
-
87
- // src/components/config.ts
88
- var packageInfoSchema = import_tsukiko.default.Object({
89
- name: import_tsukiko.default.String(),
90
- version: import_tsukiko.default.String(),
91
- description: import_tsukiko.default.String(),
92
- main: import_tsukiko.default.String(),
93
- license: import_tsukiko.default.Literal("GPL-3.0"),
94
- author: import_tsukiko.default.String()
95
- });
96
- var Config = class {
97
- config;
98
- pkg;
99
- constructor(config = DEFAULT_CORE_CONFIG) {
100
- this.config = config;
101
- const info = (0, import_tools.loadConfig)((0, import_node_path.resolve)(__dirname, "../../package.json"));
102
- if (!info || Object.values(info).length === 0) {
103
- process.stderr.write(`Cannot find kotori-bot package.json
104
- `);
105
- process.exit();
106
- }
107
- const result = packageInfoSchema.parseSafe(info);
108
- if (!result.value) {
109
- process.stderr.write(`File package.json format error: ${result.error.message}
110
- `);
111
- process.exit();
112
- }
113
- this.pkg = result.data;
114
- }
115
- };
116
- var config_default = Config;
117
-
118
- // src/components/message.ts
119
- var import_tools7 = require("@kotori-bot/tools");
120
- var import_cron = require("cron");
121
-
122
- // src/utils/factory.ts
123
- var import_tools6 = require("@kotori-bot/tools");
124
-
125
- // src/types/message.ts
126
- var import_tsukiko2 = __toESM(require("tsukiko"));
127
- var CommandAccess = /* @__PURE__ */ ((CommandAccess2) => {
128
- CommandAccess2[CommandAccess2["MEMBER"] = 0] = "MEMBER";
129
- CommandAccess2[CommandAccess2["MANGER"] = 1] = "MANGER";
130
- CommandAccess2[CommandAccess2["ADMIN"] = 2] = "ADMIN";
131
- return CommandAccess2;
132
- })(CommandAccess || {});
133
- var commandArgTypeSignSchema = import_tsukiko2.default.Union([
134
- import_tsukiko2.default.Union([import_tsukiko2.default.Literal("string"), import_tsukiko2.default.Literal("number")]),
135
- import_tsukiko2.default.Literal("boolean")
136
- ]);
137
- var MessageScope = /* @__PURE__ */ ((MessageScope2) => {
138
- MessageScope2[MessageScope2["PRIVATE"] = 0] = "PRIVATE";
139
- MessageScope2[MessageScope2["GROUP"] = 1] = "GROUP";
140
- return MessageScope2;
141
- })(MessageScope || {});
142
- var eventDataTargetIdSchema = import_tsukiko2.default.Union([import_tsukiko2.default.Number(), import_tsukiko2.default.String()]);
143
-
144
- // src/index.ts
145
- var src_exports = {};
146
- __export(src_exports, {
147
- ADAPTER_PREFIX: () => ADAPTER_PREFIX,
148
- Adapter: () => Adapter,
149
- Api: () => Api,
150
- CUSTOM_PREFIX: () => CUSTOM_PREFIX,
151
- Cache: () => Cache,
152
- Command: () => Command,
153
- CommandAccess: () => CommandAccess,
154
- CommandError: () => CommandError,
155
- Container: () => Container,
156
- Core: () => Core,
157
- DATABASE_PREFIX: () => DATABASE_PREFIX,
158
- DEFAULT_CORE_CONFIG: () => DEFAULT_CORE_CONFIG,
159
- DEFAULT_PORT: () => DEFAULT_PORT,
160
- DevError: () => DevError,
161
- Elements: () => Elements,
162
- KotoriError: () => KotoriError,
163
- MessageScope: () => MessageScope,
164
- ModuleError: () => ModuleError,
165
- OFFICIAL_MODULES_SCOPE: () => OFFICIAL_MODULES_SCOPE,
166
- PLUGIN_PREFIX: () => PLUGIN_PREFIX,
167
- Symbols: () => Symbols,
168
- cancelFactory: () => cancelFactory,
169
- commandArgTypeSignSchema: () => commandArgTypeSignSchema,
170
- confirmFactory: () => confirmFactory,
171
- disposeFactory: () => disposeFactory,
172
- eventDataTargetIdSchema: () => eventDataTargetIdSchema,
173
- formatFactory: () => formatFactory,
174
- promptFactory: () => promptFactory,
175
- quickFactory: () => quickFactory,
176
- sendMessageFactory: () => sendMessageFactory
177
- });
178
- __reExport(src_exports, require("fluoro"));
179
-
180
- // src/service/elements.ts
181
- var import_tools2 = require("@kotori-bot/tools");
182
- var Elements = class _Elements {
183
- default(...args) {
184
- (0, import_tools2.none)(this, args);
185
- return "";
186
- }
187
- at(target, ...extra) {
188
- return this.default(target, extra);
189
- }
190
- image(url, ...extra) {
191
- return this.default(url, extra);
192
- }
193
- voice(url, ...extra) {
194
- return this.default(url, extra);
195
- }
196
- video(url, ...extra) {
197
- return this.default(url, extra);
198
- }
199
- face(id, ...extra) {
200
- return this.default(id, extra);
201
- }
202
- file(data, ...extra) {
203
- return this.default(data, extra);
204
- }
205
- supports() {
206
- const supports = [];
207
- const keys = ["at", "image", "voice", "video", "face", "file"];
208
- keys.forEach((key) => {
209
- if (this[key] !== new _Elements()[key]) supports.push(key);
210
- });
211
- return supports;
212
- }
213
- };
214
- var elements_default = Elements;
215
-
216
- // src/utils/error.ts
217
- var KotoriError = class _KotoriError extends Error {
218
- constructor(message, extra, type = "UnknownError") {
219
- super(message);
220
- this.name = type;
221
- this.extra = extra;
222
- }
223
- extra;
224
- name;
225
- extend() {
226
- const { message: fatherMessage, name: fatherType, extra: fatherExtra } = this;
227
- return new Proxy(_KotoriError, {
228
- construct(Class, params) {
229
- const args = params;
230
- args[0] = `${fatherMessage} ${args[0]}`;
231
- args[1] = args[1] ?? fatherExtra;
232
- args[2] = args[2] ?? fatherType;
233
- return new Class(...args);
234
- }
235
- });
236
- }
237
- };
238
- var ModuleError = new KotoriError(void 0, void 0, "ModuleError").extend();
239
- var DevError = new KotoriError(void 0, void 0, "DevError").extend();
240
-
241
- // src/utils/commandError.ts
242
- var CommandError = class extends KotoriError {
243
- value;
244
- constructor(value) {
245
- super();
246
- this.value = value;
247
- }
248
- };
249
- var commandError_default = CommandError;
250
-
251
- // src/service/adapter.ts
252
- function setProxy(api, ctx) {
253
- const proxy = Object.create(api);
254
- proxy.sendPrivateMsg = new Proxy(api.sendPrivateMsg, {
255
- apply(_, __, argArray) {
256
- const [message, targetId] = argArray;
257
- const cancel = cancelFactory();
258
- ctx.emit("before_send", { api, message, messageType: 0 /* PRIVATE */, targetId, cancel: cancel.get() });
259
- if (cancel.value) return;
260
- api.sendPrivateMsg(message, targetId, argArray[2]);
261
- }
262
- });
263
- proxy.sendGroupMsg = new Proxy(api.sendGroupMsg, {
264
- apply(_, __, argArray) {
265
- const [message, targetId] = argArray;
266
- const cancel = cancelFactory();
267
- ctx.emit("before_send", { api, message, messageType: 0 /* PRIVATE */, targetId, cancel: cancel.get() });
268
- if (cancel.value) return;
269
- api.sendGroupMsg(message, targetId, argArray[2]);
270
- }
271
- });
272
- return proxy;
273
- }
274
- function error(type, data) {
275
- return new commandError_default(Object.assign(data ?? {}, { type }));
276
- }
277
- var Adapter = class {
278
- constructor(ctx, config, identity, Api2, el = new elements_default()) {
279
- this.ctx = ctx;
280
- this.config = config;
281
- this.identity = identity;
282
- this.platform = config.extends;
283
- this.api = setProxy(new Api2(this), this.ctx);
284
- this.elements = el;
285
- if (!this.ctx[Symbols.bot].get(this.platform)) this.ctx[Symbols.bot].set(this.platform, /* @__PURE__ */ new Set());
286
- this.ctx[Symbols.bot].get(this.platform).add(this.api);
287
- }
288
- online() {
289
- if (this.status.value !== "offline") return;
290
- this.status.value = "online";
291
- this.ctx.emit("status", { adapter: this, status: "online" });
292
- }
293
- offline() {
294
- if (this.status.value !== "online") return;
295
- this.status.value = "offline";
296
- this.status.offlineTimes += 1;
297
- this.ctx.emit("status", { adapter: this, status: "offline" });
298
- }
299
- session(type, data) {
300
- const i18n = this.ctx.i18n.extends(this.config.lang);
301
- const send = sendMessageFactory(this, type, data);
302
- const format = formatFactory(i18n);
303
- const quick = quickFactory(send, i18n);
304
- const prompt = promptFactory(quick, this, data);
305
- const confirm = confirmFactory(quick, this, data);
306
- const { api, elements: el } = this;
307
- this.ctx.emit(
308
- type,
309
- ...[{ ...data, api, el, send, i18n, format, quick, prompt, confirm, error }]
310
- );
311
- }
312
- ctx;
313
- config;
314
- identity;
315
- platform;
316
- api;
317
- elements;
318
- status = {
319
- value: "offline",
320
- createTime: /* @__PURE__ */ new Date(),
321
- lastMsgTime: null,
322
- receivedMsg: 0,
323
- sentMsg: 0,
324
- offlineTimes: 0
325
- };
326
- selfId = -1;
327
- };
328
-
329
- // src/service/api.ts
330
- var import_tools3 = require("@kotori-bot/tools");
331
- var Api = class {
332
- adapter;
333
- constructor(adapter) {
334
- this.adapter = adapter;
335
- }
336
- sendPrivateMsg(message, userId, ...extra) {
337
- (0, import_tools3.none)(this, message, userId, extra);
338
- }
339
- sendGroupMsg(message, groupId, ...extra) {
340
- (0, import_tools3.none)(this, message, groupId, extra, extra);
341
- }
342
- deleteMsg(messageId, ...extra) {
343
- (0, import_tools3.none)(this, messageId, extra);
344
- }
345
- setGroupName(groupId, groupName, ...extra) {
346
- (0, import_tools3.none)(this, groupId, groupName, extra);
347
- }
348
- setGroupAvatar(groupId, image, ...extra) {
349
- (0, import_tools3.none)(this, groupId, image, extra);
350
- }
351
- setGroupAdmin(groupId, userId, enable, ...extra) {
352
- (0, import_tools3.none)(this, groupId, userId, enable, extra);
353
- }
354
- setGroupCard(groupId, userId, card, ...extra) {
355
- (0, import_tools3.none)(this, groupId, userId, card, extra);
356
- }
357
- setGroupBan(groupId, userId, time, ...extra) {
358
- (0, import_tools3.none)(this, groupId, userId, time, extra);
359
- }
360
- sendGroupNotice(groupId, content, image, ...extra) {
361
- (0, import_tools3.none)(this, groupId, content, image, extra);
362
- }
363
- setGroupKick(groupId, userId, ...extra) {
364
- (0, import_tools3.none)(this, groupId, userId, extra);
365
- }
366
- setGroupLeave(groupId, ...extra) {
367
- (0, import_tools3.none)(this, groupId, groupId, extra);
368
- }
369
- };
370
-
371
- // src/service/cache.ts
47
+ var import_i18n = __toESM(require("@kotori-bot/i18n"));
372
48
  var import_fluoro = require("fluoro");
373
- var Cache = class extends import_fluoro.Service {
374
- cache;
375
- constructor(ctx) {
376
- super(ctx, {}, "cache");
377
- }
378
- start() {
379
- if (this.cache) return;
380
- this.cache = /* @__PURE__ */ new Map();
381
- }
382
- stop() {
383
- this.cache?.forEach((el) => el.clear());
384
- this.cache?.clear();
385
- delete this.cache;
386
- }
387
- getContainer() {
388
- const key = this.ctx.identity ?? "root";
389
- if (!this.cache.has(key)) this.cache.set(key, /* @__PURE__ */ new Map());
390
- return this.cache.get(key);
391
- }
392
- get(prop) {
393
- return this.getContainer().get(prop);
394
- }
395
- set(prop, value) {
396
- this.getContainer().set(prop, value);
397
- }
398
- };
399
-
400
- // src/utils/command.ts
401
- var import_tools4 = require("@kotori-bot/tools");
402
- var import_minimist = __toESM(require("minimist"));
403
- var requiredParamMatch = /<(\.\.\.)?(.*?)(:(.*?))?(=(.*?))?>/;
404
- var optionalParamMatch = /\[(\.\.\.)?(.*?)(:(.*?))?(=(.*?))?\]/;
405
- var defaultType = "string";
406
- function handleDefaultValue(value, type) {
407
- if (type === "boolean") return value !== "false" && !!value;
408
- if (type === "number") {
409
- if (typeof value === "number") return value;
410
- if (value === true) return 1;
411
- if (value === false) return 0;
412
- const float = parseFloat(value);
413
- const int = parseInt(value, 10);
414
- return float === int ? int : float;
415
- }
416
- return value.toString();
417
- }
418
- var Command = class {
419
- static run(input, data) {
420
- let starts = "";
421
- [data.root, ...data.alias].forEach((el) => {
422
- if (starts) return;
423
- if (input.startsWith(`${el} `) || input === el) starts = el;
424
- });
425
- if (!starts) return new CommandError({ type: "unknown", input });
426
- const opts = {
427
- string: [],
428
- boolean: [],
429
- alias: {}
430
- };
431
- data.options.forEach((option) => {
432
- if (option.type === "string") {
433
- opts.string.push(option.realname);
434
- } else if (option.type === "boolean") {
435
- opts.boolean.push(option.realname);
436
- }
437
- opts.alias[option.realname] = option.name;
438
- });
439
- const arr = (0, import_tools4.parseArgs)(input.slice(starts.length).trim());
440
- if (!Array.isArray(arr)) return new CommandError({ type: "syntax", ...arr });
441
- const result = (0, import_minimist.default)(arr, opts);
442
- const args = result._;
443
- const count = {
444
- expected: data.args.filter((el) => !el.optional).length,
445
- reality: args.length
446
- };
447
- if (count.reality < count.expected) return new CommandError({ type: "arg_few", ...count });
448
- count.expected = data.args.length;
449
- if ((data.args.length <= 0 || !data.args[data.args.length - 1].rest) && count.reality > count.expected)
450
- return new CommandError({ type: "arg_many", ...count });
451
- let error2;
452
- data.args.forEach((val, index) => {
453
- if (error2 || index > 0 && !args[index - 1]) return;
454
- if (!args[index] && val.default) {
455
- args[index] = val.default;
456
- return;
457
- }
458
- if (val.rest || !args[index]) return;
459
- args[index] = handleDefaultValue(args[index], val.type);
460
- if (!Number.isNaN(args[index])) return;
461
- error2 = new CommandError({ type: "arg_error", expected: "number", reality: "string", index });
462
- });
463
- if (error2) return error2;
464
- const options = {};
465
- data.options.forEach((val) => {
466
- if (!(val.realname in result)) return;
467
- options[val.realname] = Array.isArray(result[val.realname]) ? result[val.realname][0] : result[val.realname];
468
- options[val.realname] = handleDefaultValue(options[val.realname], val.type);
469
- if (Number.isNaN(options[val.realname]))
470
- error2 = new CommandError({ type: "option_error", expected: "number", reality: "string", target: val.realname });
471
- });
472
- if (error2) return error2;
473
- return {
474
- args: data.args.length > 0 && data.args[data.args.length - 1].rest ? args : args.slice(0, data.args.length),
475
- options
476
- };
477
- }
478
- template;
479
- meta = {
480
- root: "",
481
- alias: [],
482
- scope: "all",
483
- access: 0 /* MEMBER */,
484
- args: [],
485
- options: []
486
- };
487
- constructor(template, config) {
488
- this.template = template;
489
- this.meta = Object.assign(this.meta, config);
490
- this.parse();
491
- }
492
- parse() {
493
- const [str, description] = this.template.trim().split(" - ");
494
- this.meta.description = description;
495
- const requiredIndex = str.indexOf(" <");
496
- const optionalIndex = str.indexOf(" [");
497
- if (requiredIndex === -1 && optionalIndex === -1) {
498
- this.meta.root = str.trim();
499
- return;
500
- }
501
- if (requiredIndex !== -1 && (optionalIndex === -1 || requiredIndex < optionalIndex)) {
502
- this.meta.root = str.substring(0, requiredIndex).trim();
503
- } else {
504
- this.meta.root = str.substring(0, optionalIndex).trim();
505
- }
506
- const args = (0, import_minimist.default)(str.split(" "))._;
507
- args.forEach((arg) => {
508
- const current = this.meta.args[this.meta.args.length - 1];
509
- if (current && current.rest) return;
510
- let result = optionalParamMatch.exec(arg);
511
- if (result) {
512
- if (!result[2]) return;
513
- const type = commandArgTypeSignSchema.parseSafe(result[4]).value ? result[4] : defaultType;
514
- this.meta.args.push({
515
- name: result[2],
516
- type,
517
- rest: !!result[1],
518
- optional: true,
519
- default: result[6] ? handleDefaultValue(result[6], type) : void 0
520
- });
521
- }
522
- result = requiredParamMatch.exec(arg);
523
- if (!result || !result[2]) return;
524
- if (!result[6] && current && current.optional) return;
525
- this.meta.args.push({
526
- name: result[2],
527
- type: commandArgTypeSignSchema.parseSafe(result[4]).value ? result[4] : defaultType,
528
- rest: !!result[1],
529
- optional: false
530
- });
531
- });
532
- }
533
- alias(alias) {
534
- if (typeof alias === "string") this.meta.alias.push(alias);
535
- else this.meta.alias.push(...alias);
536
- return this;
537
- }
538
- scope(scope) {
539
- this.meta.scope = scope;
540
- return this;
541
- }
542
- access(access) {
543
- this.meta.access = access;
544
- return this;
545
- }
546
- option(name, template) {
547
- const [str, description] = template.trim().split(" ");
548
- const [realname, type] = str.split(":");
549
- this.meta.options.push({
550
- realname,
551
- description,
552
- type: commandArgTypeSignSchema.parseSafe(type).value ? type : defaultType,
553
- name: name.charAt(0)
554
- });
555
- return this;
556
- }
557
- action(callback) {
558
- this.meta.action = callback;
559
- return this;
560
- }
561
- help(text) {
562
- this.meta.help = text;
563
- return this;
564
- }
565
- };
566
-
567
- // src/utils/container.ts
568
- var import_tools5 = require("@kotori-bot/tools");
569
- var Container = class _Container {
570
- constructor() {
571
- (0, import_tools5.none)();
572
- }
573
- static instance = {};
574
- static setInstance(ctx) {
575
- this.instance = ctx;
576
- }
577
- static getInstance() {
578
- return this.instance;
579
- }
580
- static getMixin() {
581
- return Object.assign(
582
- _Container.getInstance()
583
- /* , Context */
584
- );
585
- }
586
- };
587
-
588
- // src/index.ts
589
- __reExport(src_exports, require("@kotori-bot/tools"));
590
- __reExport(src_exports, require("@kotori-bot/i18n"));
591
- __reExport(src_exports, require("tsukiko"));
592
-
593
- // src/utils/factory.ts
594
- function disposeFactory(ctx, dispose) {
595
- ctx.once("dispose_module", (data) => {
596
- if ((typeof data.instance === "object" ? data.instance.name : data.instance) !== ctx.identity) {
597
- disposeFactory(ctx, dispose);
598
- return;
599
- }
600
- dispose();
601
- });
602
- }
603
- function cancelFactory() {
604
- return {
605
- get() {
606
- return () => this.fn();
607
- },
608
- fn() {
609
- this.value = true;
610
- },
611
- value: false
612
- };
613
- }
614
- function formatFactory(i18n) {
615
- return (template, data) => {
616
- const params = data;
617
- if (Array.isArray(params)) {
618
- let str = i18n.locale(template);
619
- params.forEach((value, index) => {
620
- str = str.replaceAll(`{${index}}`, i18n.locale(typeof value === "string" ? value : String(value)));
621
- });
622
- return str;
623
- }
624
- Object.keys(params).forEach((key) => {
625
- if (typeof params[key] !== "string") params[key] = String(params[key]);
626
- params[key] = i18n.locale(params[key]);
627
- });
628
- return (0, import_tools6.stringTemp)(i18n.locale(template), params);
629
- };
630
- }
631
- function sendMessageFactory(adapter, type, data) {
632
- if ((data.type === 1 /* GROUP */ || type.includes("group")) && "groupId" in data) {
633
- return (message) => {
634
- adapter.api.sendGroupMsg(message, data.groupId, data.extra);
635
- };
636
- }
637
- return (message) => {
638
- adapter.api.sendPrivateMsg(message, data.userId, data.extra);
639
- };
640
- }
641
- function quickFactory(send, i18n) {
642
- return async (message) => {
643
- const msg = await message;
644
- if (!msg || msg instanceof CommandError) return;
645
- if (typeof msg === "string") {
646
- send(i18n.locale(msg));
647
- return;
648
- }
649
- send(formatFactory(i18n)(...msg));
650
- };
651
- }
652
- function isSameSender(adapter, data, session) {
653
- return session.api.adapter.identity === adapter.identity && session.api.adapter.platform === adapter.platform && session.type === data.type && session.groupId === data.groupId && session.userId === data.userId && "messageId" in data && session.messageId !== data.messageId;
654
- }
655
- function promptFactory(quick, adapter, data) {
656
- return (message) => new Promise((resolve2) => {
657
- const handle = (session) => {
658
- if (isSameSender(adapter, data, session)) {
659
- resolve2(session.message);
660
- return;
661
- }
662
- adapter.ctx.once("on_message", handle);
663
- };
664
- quick(message ?? "corei18n.template.prompt").then(() => adapter.ctx.once("on_message", handle));
665
- });
666
- }
667
- function confirmFactory(quick, adapter, data) {
668
- return (options) => new Promise((resolve2) => {
669
- const handle = (session) => {
670
- if (isSameSender(adapter, data, session)) {
671
- resolve2(session.message === (options?.sure ?? "corei18n.template.confirm.sure"));
672
- return;
673
- }
674
- adapter.ctx.once("on_message", handle);
675
- };
676
- quick(options?.message ?? "corei18n.template.confirm").then(() => adapter.ctx.once("on_message", handle));
677
- });
678
- }
679
-
680
- // src/components/message.ts
681
- var Message = class {
682
- [Symbols.midware] = /* @__PURE__ */ new Set();
683
- [Symbols.command] = /* @__PURE__ */ new Set();
684
- [Symbols.regexp] = /* @__PURE__ */ new Set();
685
- handleMidware(session) {
686
- const { api } = session;
687
- let isPass = true;
688
- let midwares = [];
689
- api.adapter.status.receivedMsg += 1;
690
- this[Symbols.midware].forEach((val) => midwares.push(val));
691
- midwares = midwares.sort((first, second) => first.priority - second.priority);
692
- let lastMidwareNum = -1;
693
- while (midwares.length > 0) {
694
- if (lastMidwareNum === midwares.length) {
695
- isPass = false;
696
- break;
697
- }
698
- lastMidwareNum = midwares.length;
699
- session.quick(midwares[0].callback(() => midwares.shift(), session));
700
- }
701
- this.ctx.emit("midwares", { isPass, session });
702
- }
703
- async handleRegexp(data) {
704
- const { session } = data;
705
- if (!data.isPass) return;
706
- this[Symbols.regexp].forEach((data2) => {
707
- const result = session.message.match(data2.match);
708
- if (!result) return;
709
- session.quick(data2.callback(result, session));
710
- this.ctx.emit("regexp", { result, session, regexp: data2.match, raw: session.message });
711
- });
712
- }
713
- handleCommand(data) {
714
- const { session } = data;
715
- const prefix = session.api.adapter.config["command-prefix"] ?? this.ctx.config.global["command-prefix"];
716
- if (!session.message.startsWith(prefix)) return;
717
- const params = {
718
- session,
719
- raw: (0, import_tools7.stringRightSplit)(session.message, prefix)
720
- };
721
- this.ctx.emit("before_parse", params);
722
- const cancel = cancelFactory();
723
- this.ctx.emit("before_command", { cancel: cancel.get(), ...params });
724
- if (cancel.value) return;
725
- let matched;
726
- this[Symbols.command].forEach(async (cmd) => {
727
- if (matched || !cmd.meta.action) return;
728
- const result = Command.run(params.raw, cmd.meta);
729
- if (result instanceof commandError_default && result.value.type === "unknown") return;
730
- matched = cmd;
731
- this.ctx.emit("parse", { command: cmd, result, ...params, cancel: cancel.get() });
732
- if (cancel.value || result instanceof commandError_default) return;
733
- try {
734
- const executed = await cmd.meta.action({ args: result.args, options: result.options }, session);
735
- if (executed instanceof commandError_default) {
736
- this.ctx.emit("command", { command: cmd, result: executed, ...params });
737
- return;
738
- }
739
- if (executed !== void 0) session.quick(executed);
740
- this.ctx.emit("command", {
741
- command: cmd,
742
- result: executed instanceof commandError_default ? result : executed,
743
- ...params
744
- });
745
- } catch (error2) {
746
- this.ctx.emit("command", {
747
- command: matched,
748
- result: new commandError_default({ type: "error", error: error2 }),
749
- ...params
750
- });
751
- }
752
- });
753
- if (matched) return;
754
- this.ctx.emit("parse", {
755
- command: new Command(""),
756
- result: new commandError_default({ type: "unknown", input: params.raw }),
757
- ...params,
758
- cancel: cancel.get()
759
- });
760
- }
761
- ctx;
762
- constructor(ctx) {
763
- this.ctx = ctx;
764
- this.ctx.on("on_message", (session) => this.handleMidware(session));
765
- this.ctx.on("midwares", (data) => this.handleCommand(data));
766
- this.ctx.on("midwares", (data) => this.handleRegexp(data));
767
- this.ctx.on("before_send", (data) => {
768
- const { api } = data;
769
- api.adapter.status.sentMsg += 1;
770
- });
771
- }
772
- midware(callback, priority = 100) {
773
- const data = { callback, priority };
774
- this[Symbols.midware].add(data);
775
- const dispose = () => this[Symbols.midware].delete(data);
776
- disposeFactory(this.ctx, dispose);
777
- return dispose;
778
- }
779
- command(template, config) {
780
- const command = new Command(template, config);
781
- this[Symbols.command].add(command);
782
- const dispose = () => this[Symbols.command].delete(command);
783
- disposeFactory(this.ctx, dispose);
784
- return command;
785
- }
786
- regexp(match, callback) {
787
- const data = { match, callback };
788
- this[Symbols.regexp].add(data);
789
- const dispose = () => this[Symbols.regexp].delete(data);
790
- disposeFactory(this.ctx, dispose);
791
- return dispose;
792
- }
793
- // boardcast(type: MessageScope, message: MessageRaw) {
794
- // const send =
795
- // type === 'private'
796
- // ? (api: Api) => api.send_on_message(message, 1)
797
- // : (api: Api) => api.send_on_message(message, 1);
798
- // /* this need support of database... */
799
- // Object.values(this.botStack).forEach((apis) => {
800
- // apis.forEach((api) => send(api));
801
- // });
802
- // }
803
- notify(message) {
804
- const mainAdapterIdentity = Object.keys(this.ctx.config.adapter)[0];
805
- this.ctx[Symbols.bot].forEach(
806
- (apis) => apis.forEach((api) => {
807
- if (api.adapter.identity !== mainAdapterIdentity) return;
808
- quickFactory(
809
- sendMessageFactory(api.adapter, "on_message", { userId: api.adapter.config.master }),
810
- this.ctx.i18n.extends(api.adapter.config.lang)
811
- )(message);
812
- })
813
- );
814
- }
815
- task(options, callback) {
816
- const [cron, extraOptions] = typeof options === "string" ? [options, {}] : [options.cron, options];
817
- return new import_cron.CronJob(cron, () => callback(this.ctx), null, extraOptions.start ?? true, extraOptions.timeZone);
818
- }
819
- };
820
- var message_default = Message;
821
-
822
- // src/components/core.ts
823
- var Core = class extends import_fluoro2.Context {
824
- [Symbols.adapter] = /* @__PURE__ */ new Map();
825
- [Symbols.bot] = /* @__PURE__ */ new Map();
49
+ var import_config = __toESM(require("./config"));
50
+ var import_message = __toESM(require("./message"));
51
+ var import_service = require("../service");
52
+ var import_global = require("../global");
53
+ class Core extends import_fluoro.Context {
54
+ [import_global.Symbols.adapter] = /* @__PURE__ */ new Map();
55
+ [import_global.Symbols.bot] = /* @__PURE__ */ new Map();
826
56
  constructor(config) {
827
57
  super();
828
- this.provide("config", new config_default(config));
58
+ this.provide("config", new import_config.default(config));
829
59
  this.mixin("config", ["config", "pkg"]);
830
- this.provide("message", new message_default(this));
60
+ this.provide("message", new import_message.default(this));
831
61
  this.mixin("message", ["midware", "command", "regexp", "notify", "task"]);
832
- this.provide("http", new import_tools8.Http({ validateStatus: () => true }));
62
+ this.provide("http", new import_tools.Http({ validateStatus: () => true }));
833
63
  this.inject("http");
834
- this.provide("i18n", new import_i18n2.default({ lang: this.config.global.lang }));
64
+ this.provide("i18n", new import_i18n.default({ lang: this.config.global.lang }));
835
65
  this.inject("i18n");
836
- this.service("cache", new Cache(this.extends()));
66
+ this.service("cache", new import_service.Cache(this.extends()));
837
67
  }
838
- };
68
+ }
839
69
  var core_default = Core;
840
70
  // Annotate the CommonJS export names for ESM import in node:
841
71
  0 && (module.exports = {