@kotori-bot/core 1.4.1 → 1.5.0

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