@kotori-bot/loader 1.6.0 → 1.6.2

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/index.js CHANGED
@@ -1,25 +1,19 @@
1
1
 
2
2
  /**
3
3
  * @Package @kotori-bot/loader
4
- * @Version 1.6.0-beta.1
4
+ * @Version 1.6.2
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:54
9
+ * @Date 2024/6/7 11:53:11
10
10
  */
11
11
 
12
12
  "use strict";
13
- var __create = Object.create;
14
13
  var __defProp = Object.defineProperty;
15
14
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
16
15
  var __getOwnPropNames = Object.getOwnPropertyNames;
17
- var __getProtoOf = Object.getPrototypeOf;
18
16
  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
17
  var __copyProps = (to, from, except, desc) => {
24
18
  if (from && typeof from === "object" || typeof from === "function") {
25
19
  for (let key of __getOwnPropNames(from))
@@ -29,810 +23,19 @@ var __copyProps = (to, from, except, desc) => {
29
23
  return to;
30
24
  };
31
25
  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
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
41
-
42
- // src/index.ts
43
27
  var src_exports = {};
44
- __export(src_exports, {
45
- BUILD_CONFIG_NAME: () => BUILD_CONFIG_NAME,
46
- BUILD_FILE: () => BUILD_FILE,
47
- BUILD_MODE: () => BUILD_MODE,
48
- CONFIG_EXT: () => CONFIG_EXT,
49
- CORE_MODULES: () => CORE_MODULES,
50
- DEV_CODE_DIRS: () => DEV_CODE_DIRS,
51
- DEV_CONFIG_NAME: () => DEV_CONFIG_NAME,
52
- DEV_FILE: () => DEV_FILE,
53
- DEV_IMPORT: () => DEV_IMPORT,
54
- DEV_MODE: () => DEV_MODE,
55
- DEV_SOURCE_MODE: () => DEV_SOURCE_MODE,
56
- KotoriPlugin: () => KotoriPlugin,
57
- Loader: () => Loader,
58
- SUPPORTS_HALF_VERSION: () => SUPPORTS_HALF_VERSION,
59
- SUPPORTS_VERSION: () => SUPPORTS_VERSION,
60
- plugins: () => plugins
61
- });
62
28
  module.exports = __toCommonJS(src_exports);
63
-
64
- // src/class/loader.ts
65
- var import_core4 = require("@kotori-bot/core");
66
- var import_node_path3 = __toESM(require("path"));
67
- var import_node_fs2 = __toESM(require("fs"));
68
- var import_logger4 = __toESM(require("@kotori-bot/logger"));
69
-
70
- // src/class/runner.ts
71
- var import_node_fs = __toESM(require("fs"));
72
- var import_node_path = __toESM(require("path"));
73
- var import_core = require("@kotori-bot/core");
74
- var import_logger2 = require("@kotori-bot/logger");
75
-
76
- // src/constants.ts
77
- var DEV_FILE = ".ts";
78
- var BUILD_FILE = ".js";
79
- var DEV_CODE_DIRS = "./src/";
80
- var DEV_IMPORT = `${DEV_CODE_DIRS}index.ts`;
81
- var CONFIG_EXT = [".toml", ".yml", ".yaml", ".json"];
82
- var BUILD_CONFIG_NAME = "kotori";
83
- var DEV_CONFIG_NAME = "kotori.dev";
84
- var SUPPORTS_VERSION = /(1\.1\.0)|(1\.2\.0)|(1\.3\.(.*))|(1\.4\.(.*))/;
85
- var SUPPORTS_HALF_VERSION = /(x\.x\.(.*?))/;
86
- var BUILD_MODE = "build";
87
- var DEV_MODE = "dev";
88
- var DEV_SOURCE_MODE = "dev-source";
89
- var CORE_MODULES = [
90
- "@kotori-bot/kotori-plugin-core",
91
- "@kotori-bot/kotori-plugin-i18n-command",
92
- "@kotori-bot/kotori-plugin-filter"
93
- // '@kotori-bot/kotori-plugin-webui'
94
- ];
95
-
96
- // src/utils/logger.ts
97
- var import_logger = require("@kotori-bot/logger");
98
- var KotoriLogger = class extends import_logger.Logger {
99
- constructor(optionsSelf, ctx) {
100
- super(optionsSelf);
101
- this.optionsSelf = optionsSelf;
102
- this.ctx = ctx;
103
- }
104
- setLabel() {
105
- const origin = Object.create(this.optionsSelf.label);
106
- const label = this.ctx.identity ? [this.ctx.identity, ...this.optionsSelf.label] : this.optionsSelf.label;
107
- this[/* @__PURE__ */ (() => "options")()].label = label;
108
- return () => {
109
- this[/* @__PURE__ */ (() => "options")()].label = origin;
110
- };
111
- }
112
- fatal(...args) {
113
- const dispose = this.setLabel();
114
- super.fatal(...args);
115
- dispose();
116
- }
117
- error(...args) {
118
- const dispose = this.setLabel();
119
- super.error(...args);
120
- dispose();
121
- }
122
- warn(...args) {
123
- const dispose = this.setLabel();
124
- super.warn(...args);
125
- dispose();
126
- }
127
- info(...args) {
128
- const dispose = this.setLabel();
129
- super.info(...args);
130
- dispose();
131
- }
132
- record(...args) {
133
- const dispose = this.setLabel();
134
- super.record(...args);
135
- dispose();
136
- }
137
- debug(...args) {
138
- const dispose = this.setLabel();
139
- super.debug(...args);
140
- dispose();
141
- }
142
- trace(...args) {
143
- const dispose = this.setLabel();
144
- super.trace(...args);
145
- dispose();
146
- }
147
- };
148
- var logger_default = KotoriLogger;
149
-
150
- // src/class/runner.ts
151
- var localeTypeSchema = import_core.Tsu.Union([
152
- import_core.Tsu.Union([import_core.Tsu.Literal("en_US"), import_core.Tsu.Literal("ja_JP")]),
153
- import_core.Tsu.Union([import_core.Tsu.Literal("zh_TW"), import_core.Tsu.Any()])
154
- ]);
155
- var modulePackageSchema = import_core.Tsu.Object({
156
- name: import_core.Tsu.String().regexp(/kotori-plugin-[a-z]([a-z,0-9]{2,13})\b/),
157
- version: import_core.Tsu.String(),
158
- description: import_core.Tsu.String(),
159
- main: import_core.Tsu.String(),
160
- license: import_core.Tsu.Literal("GPL-3.0"),
161
- keywords: import_core.Tsu.Custom(
162
- (val) => Array.isArray(val) && val.includes("kotori") && val.includes("chatbot") && val.includes("kotori-plugin")
163
- ),
164
- author: import_core.Tsu.Union([import_core.Tsu.String(), import_core.Tsu.Array(import_core.Tsu.String())]),
165
- peerDependencies: import_core.Tsu.Object({
166
- "kotori-bot": import_core.Tsu.String()
167
- }),
168
- kotori: import_core.Tsu.Object({
169
- enforce: import_core.Tsu.Union([import_core.Tsu.Literal("pre"), import_core.Tsu.Literal("post")]).optional(),
170
- meta: import_core.Tsu.Object({
171
- language: import_core.Tsu.Array(localeTypeSchema).default([])
172
- }).default({ language: [] })
173
- }).default({
174
- enforce: void 0,
175
- meta: { language: [] }
176
- })
177
- });
178
- function moduleLoadOrder(pkg) {
179
- if (CORE_MODULES.includes(pkg.name)) return 1;
180
- if (pkg.name.includes(import_core.DATABASE_PREFIX)) return 2;
181
- if (pkg.name.includes(import_core.ADAPTER_PREFIX)) return 3;
182
- if (pkg.kotori.enforce === "pre") return 4;
183
- if (!pkg.kotori.enforce) return 5;
184
- return 6;
185
- }
186
- var Runner = class {
187
- baseDir;
188
- options;
189
- ctx;
190
- isDev;
191
- isSourceDev;
192
- [import_core.Symbols.modules] = /* @__PURE__ */ new Map();
193
- constructor(ctx, config) {
194
- this.ctx = ctx;
195
- this.baseDir = config.baseDir;
196
- this.options = config.options;
197
- this.isDev = this.options.mode.startsWith(DEV_MODE);
198
- this.isSourceDev = this.options.mode === DEV_SOURCE_MODE;
199
- const loggerOptions = {
200
- level: this.ctx.config.global.level ?? config.level,
201
- label: [],
202
- transports: [
203
- new import_logger2.ConsoleTransport({
204
- template: "<blue>%time%</blue> %level% (<bold>%pid%</bold>) %labels%: %msg%",
205
- time: "M/D H:m:s"
206
- }),
207
- new import_logger2.FileTransport({ dir: this.baseDir.logs, filter: (data) => data.level >= import_logger2.LoggerLevel.WARN })
208
- ]
209
- };
210
- ctx.provide("logger", new logger_default(loggerOptions, this.ctx));
211
- ctx.inject("logger");
212
- }
213
- getDirFiles(rootDir) {
214
- const files = import_node_fs.default.readdirSync(rootDir);
215
- const list = [];
216
- files.forEach((fileName) => {
217
- const file = import_node_path.default.join(rootDir, fileName);
218
- if (import_node_fs.default.statSync(file).isDirectory()) {
219
- list.push(...this.getDirFiles(file));
220
- }
221
- if (import_node_path.default.parse(file).ext !== (this.isSourceDev ? DEV_FILE : BUILD_FILE)) return;
222
- list.push(import_node_path.default.resolve(file));
223
- });
224
- return list;
225
- }
226
- getModuleRootDir() {
227
- const moduleRootDir = [];
228
- [
229
- ...this.ctx.config.global.dirs.map((dir) => import_node_path.default.resolve(this.ctx.baseDir.root, dir)),
230
- this.ctx.baseDir.modules
231
- ].forEach((dir) => {
232
- if (import_node_fs.default.existsSync(dir) && import_node_fs.default.statSync(dir).isDirectory()) moduleRootDir.push(dir);
233
- });
234
- return moduleRootDir;
235
- }
236
- async checkModuleFiles(rootDir, filename) {
237
- const dir = import_node_path.default.join(rootDir, filename);
238
- if (!import_node_fs.default.statSync(dir).isDirectory()) return;
239
- if (rootDir !== this.ctx.baseDir.modules && !filename.startsWith(import_core.PLUGIN_PREFIX)) return;
240
- const packagePath = import_node_path.default.join(dir, "package.json");
241
- let pkg;
242
- if (!import_node_fs.default.existsSync(packagePath)) return;
243
- try {
244
- pkg = JSON.parse(import_node_fs.default.readFileSync(packagePath).toString());
245
- } catch {
246
- throw new import_core.DevError(this.ctx.format("error.dev.package.illegal", [packagePath]));
247
- }
248
- const result = modulePackageSchema.parseSafe(pkg);
249
- if (!result.value) {
250
- if (rootDir !== this.ctx.baseDir.modules) return;
251
- throw new import_core.DevError(this.ctx.format("error.dev.package.missing", [packagePath, result.error.message]));
252
- }
253
- pkg = result.data;
254
- const devMode = this.isSourceDev && (0, import_node_fs.existsSync)(import_node_path.default.resolve(dir, DEV_IMPORT));
255
- const main = import_node_path.default.resolve(dir, devMode ? DEV_IMPORT : pkg.main);
256
- if (!import_node_fs.default.existsSync(main)) throw new import_core.DevError(this.ctx.format("error.dev.main_file", [main]));
257
- const dirs = import_node_path.default.join(dir, devMode ? DEV_CODE_DIRS : import_node_path.default.dirname(pkg.main));
258
- const files = import_node_fs.default.statSync(dirs).isDirectory() ? this.getDirFiles(dirs) : [];
259
- this[import_core.Symbols.modules].set(pkg.name, [
260
- { pkg, files, main },
261
- this.ctx.config.plugin[(0, import_core.stringRightSplit)(pkg.name, import_core.PLUGIN_PREFIX)] || {}
262
- ]);
263
- }
264
- getModuleList(rootDir) {
265
- this.ctx.logger.trace("load dirs:", rootDir);
266
- import_node_fs.default.readdirSync(rootDir).forEach(async (filename) => {
267
- await this.checkModuleFiles(rootDir, filename);
268
- });
269
- }
270
- loadLang(lang) {
271
- if (lang) this.ctx.i18n.use((0, import_node_path.resolve)(...Array.isArray(lang) ? lang : [lang]));
272
- }
273
- loadEx(instance, origin) {
274
- this.ctx.logger.trace("module:", instance, origin);
275
- if (!instance.main) return;
276
- const parsed = (schema) => {
277
- const result = schema.parseSafe(config);
278
- if (!result.value)
279
- throw new import_core.ModuleError(this.ctx.format("error.module.config", [pkg.name, result.error.message]));
280
- return result.data;
281
- };
282
- const { main, pkg } = instance;
283
- let obj = require(main);
284
- let config = origin;
285
- const adapterName = pkg.name.split(import_core.ADAPTER_PREFIX)[1];
286
- if (this.ctx.get("decorators")?.registers.includes(pkg.name)) {
287
- this.ctx.emit("ready_module_decorators", pkg.name);
288
- return;
289
- }
290
- if (import_core.Adapter.isPrototypeOf.call(import_core.Adapter, obj.default) && adapterName && (!obj.config || obj.config instanceof import_core.Parser)) {
291
- this.ctx[import_core.Symbols.adapter].set(adapterName, [obj.default, obj.config]);
292
- obj = {};
293
- } else if (import_core.Service.isPrototypeOf.call(import_core.Service, obj.default)) {
294
- obj = {};
295
- } else if (obj.config instanceof import_core.Parser) {
296
- config = parsed(obj.config);
297
- }
298
- if (obj.lang) this.loadLang(obj.lang);
299
- if (obj.default) {
300
- if (obj.default.lang) this.loadLang(obj.default.lang);
301
- if (obj.default.config instanceof import_core.Parser) config = parsed(obj.default.config);
302
- } else if (obj.Main) {
303
- if (obj.Main.lang) this.loadLang(obj.Main.lang);
304
- if (obj.Main.config instanceof import_core.Parser) config = parsed(obj.Main.config);
305
- }
306
- this.ctx.load({ name: pkg.name, ...obj, config });
307
- }
308
- unloadEx(instance) {
309
- instance.files.forEach((file) => delete require.cache[require.resolve(file)]);
310
- this.ctx.load({ name: instance.pkg.name });
311
- }
312
- loadAll() {
313
- this.getModuleRootDir().forEach((dir) => this.getModuleList(dir));
314
- const modules = [];
315
- this[import_core.Symbols.modules].forEach((val) => modules.push(val));
316
- modules.sort(([{ pkg: pkg1 }], [{ pkg: pkg2 }]) => moduleLoadOrder(pkg1) - moduleLoadOrder(pkg2)).forEach((el) => this.loadEx(...el));
317
- if (this.isDev) this.watcher();
318
- }
319
- watcher() {
320
- this[import_core.Symbols.modules].forEach(
321
- (data) => data[0].files.forEach(
322
- (file) => import_node_fs.default.watchFile(file, async () => {
323
- this.ctx.logger.debug(this.ctx.format("loader.debug.reload", [data[0].pkg.name]));
324
- this.unloadEx(data[0]);
325
- this.loadEx(...data);
326
- })
327
- )
328
- );
329
- }
330
- };
331
- var runner_default = Runner;
332
-
333
- // src/utils/log.ts
334
- function loadInfo(info, ctx) {
335
- process.stdout.write("Kotori Bot is loading...");
336
- process.stdout.write(`
337
- \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557
338
- \u2588\u2588\u2551 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551
339
- \u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551
340
- \u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551
341
- \u2588\u2588\u2551 \u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551
342
- \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D
343
- `);
344
- ctx.logger.record("loader base dir:", ctx.baseDir.root);
345
- ctx.logger.info(`Kotori Bot Version: ${info.version} License: ${info.license}`);
346
- ctx.logger.info(`Kotori Bot By ${info.author}`);
347
- ctx.logger.info(`Copyright \xA9 2023 - 2024 ${info.author} All rights reserved`);
348
- }
349
- var log_default = loadInfo;
350
-
351
- // src/service/server.ts
352
- var import_core2 = require("@kotori-bot/core");
353
- var import_node_http = require("http");
354
- var import_path_to_regexp = require("path-to-regexp");
355
- var import_express = __toESM(require("express"));
356
- var import_ws = __toESM(require("ws"));
357
- var Server = class extends import_core2.Service {
358
- app;
359
- server;
360
- wsServer;
361
- wsRoutes = /* @__PURE__ */ new Map();
362
- constructor(ctx, config) {
363
- super(ctx, config, "server");
364
- this.app = (0, import_express.default)();
365
- this.app.use(import_express.default.json());
366
- this.app.use("/", (req, res, next) => {
367
- let isWebui = false;
368
- ctx[import_core2.Symbols.modules].forEach((module2) => {
369
- if (isWebui) return;
370
- if (module2[0].pkg.name === "@kotori-bot/kotori-plugin-webui") isWebui = true;
371
- });
372
- if (isWebui || req.url !== "/") {
373
- next();
374
- return;
375
- }
376
- res.setHeader("Content-type", "text/html");
377
- res.send(
378
- /* html */
379
- `<h1>Welcome to kotori!</h1>`
380
- );
381
- });
382
- this.server = (0, import_node_http.createServer)(this.app);
383
- this.wsServer = new import_ws.default.Server({ noServer: true });
384
- this.server.on("upgrade", (req, socket, head) => {
385
- this.wsServer.handleUpgrade(req, socket, head, (ws) => {
386
- this.wsServer.emit("connection", ws, req);
387
- });
388
- });
389
- this.wsServer.on("connection", (ws, req) => {
390
- let triggered = false;
391
- for (const [template, list] of this.wsRoutes.entries()) {
392
- if (!req.url) continue;
393
- const result = (0, import_path_to_regexp.match)(template, { decode: decodeURIComponent })(req.url);
394
- if (!result) continue;
395
- if (!triggered) triggered = true;
396
- list.forEach((callback) => {
397
- callback(ws, Object.assign(req, { params: result.params }));
398
- });
399
- }
400
- if (!triggered) ws.close(1002);
401
- });
402
- }
403
- start() {
404
- this.server.listen(this.config.port, () => {
405
- this.ctx.logger.label("server").info(`http server start at http://127.0.0.1:${this.config.port}`);
406
- this.ctx.logger.label("server").info(`websocket server start at ws://127.0.0.1:${this.config.port}`);
407
- });
408
- }
409
- stop() {
410
- this.wsServer.close();
411
- this.server.close();
412
- }
413
- get(path3, ...callback) {
414
- this.app.get(path3, ...callback);
415
- }
416
- post(path3, ...callback) {
417
- this.app.post(path3, ...callback);
418
- }
419
- patch(path3, ...callback) {
420
- this.app.patch(path3, ...callback);
421
- }
422
- put(path3, ...callback) {
423
- this.app.put(path3, ...callback);
424
- }
425
- delete(path3, ...callback) {
426
- this.app.delete(path3, ...callback);
427
- }
428
- all(path3, ...callback) {
429
- this.app.all(path3, ...callback);
430
- }
431
- use(path3, ...callback) {
432
- if (typeof path3 === "string") this.app.use(path3, ...callback);
433
- else this.app.use("/", path3, ...callback);
434
- }
435
- router = import_express.default.Router;
436
- json = import_express.default.json;
437
- static = import_express.default.static;
438
- urlencoded = import_express.default.urlencoded;
439
- wss(path3, callback) {
440
- const list = this.wsRoutes.get(path3) || /* @__PURE__ */ new Set();
441
- list.add(callback);
442
- this.wsRoutes.set(path3, list);
443
- return () => list.delete(callback);
444
- }
445
- };
446
- var server_default = Server;
447
-
448
- // src/service/file.ts
449
- var import_core3 = require("@kotori-bot/core");
450
- var import_node_path2 = require("path");
451
- var File = class extends import_core3.Service {
452
- constructor(ctx) {
453
- super(ctx, {}, "file");
454
- }
455
- getDir() {
456
- return (0, import_node_path2.join)(this.ctx.baseDir.data, ...this.ctx.identity ? this.ctx.identity.split("/") : []);
457
- }
458
- getFile(filename) {
459
- return (0, import_node_path2.join)(this.getDir(), filename);
460
- }
461
- /* eslint-disable @typescript-eslint/no-explicit-any */
462
- load(filename, type, init) {
463
- return (0, import_core3.loadConfig)(this.getFile(filename), type, init);
464
- }
465
- /* eslint-enable @typescript-eslint/no-explicit-any */
466
- save(filename, data, type) {
467
- (0, import_core3.saveConfig)(this.getFile(filename), data, type);
468
- }
469
- create(filename, data, type) {
470
- (0, import_core3.createConfig)(this.getFile(filename), data, type);
471
- }
472
- };
473
- var file_default = File;
474
-
475
- // src/class/loader.ts
476
- function getBaseDir(filename, dir) {
477
- let root = dir ? import_node_path3.default.resolve(dir) : import_node_path3.default.resolve(__dirname, "..").replace("loader", "kotori");
478
- let filenameFull;
479
- let count = 0;
480
- let index = 0;
481
- while (!filenameFull) {
482
- if (count > 5) {
483
- import_logger4.default.fatal(`cannot find file ${filename} `);
484
- process.exit();
485
- }
486
- const fullName = `${filename}${CONFIG_EXT[index]}`;
487
- if (import_node_fs2.default.existsSync(import_node_path3.default.join(root, fullName))) {
488
- filenameFull = fullName;
489
- break;
490
- }
491
- if (index === CONFIG_EXT.length - 1) {
492
- root = import_node_path3.default.join(root, "..");
493
- index = 0;
494
- count += 1;
495
- } else {
496
- index += 1;
497
- }
498
- }
499
- const baseDir = {
500
- root,
501
- modules: import_node_path3.default.join(root, "modules"),
502
- data: import_node_path3.default.join(root, "data"),
503
- logs: import_node_path3.default.join(root, "logs"),
504
- config: filenameFull
505
- };
506
- Object.entries(baseDir).filter(([key]) => !["modules", "config"].includes(key)).forEach(([, val]) => {
507
- if (!import_node_fs2.default.existsSync(val)) import_node_fs2.default.mkdirSync(val);
508
- });
509
- return baseDir;
510
- }
511
- function getCoreConfig(baseDir) {
512
- try {
513
- const result1 = import_core4.Tsu.Object({
514
- global: import_core4.Tsu.Object({
515
- dirs: import_core4.Tsu.Array(import_core4.Tsu.String()).default([]),
516
- port: import_core4.Tsu.Number().default(import_core4.DEFAULT_PORT),
517
- lang: localeTypeSchema.default(import_core4.DEFAULT_CORE_CONFIG.global.lang),
518
- "command-prefix": import_core4.Tsu.String().default(import_core4.DEFAULT_CORE_CONFIG.global["command-prefix"])
519
- }),
520
- plugin: import_core4.Tsu.Object({}).index(
521
- import_core4.Tsu.Object({
522
- filter: import_core4.Tsu.Object({}).default({})
523
- }).default({ filter: {} })
524
- ).default(import_core4.DEFAULT_CORE_CONFIG.plugin)
525
- }).default({ global: Object.assign(import_core4.DEFAULT_CORE_CONFIG.global), plugin: import_core4.DEFAULT_CORE_CONFIG.plugin }).parse((0, import_core4.loadConfig)(import_node_path3.default.join(baseDir.root, baseDir.config), baseDir.config.split(".").pop()));
526
- return import_core4.Tsu.Object({
527
- adapter: import_core4.Tsu.Object({}).index(
528
- import_core4.Tsu.Object({
529
- extends: import_core4.Tsu.String(),
530
- master: import_core4.Tsu.Union([import_core4.Tsu.Number(), import_core4.Tsu.String()]),
531
- lang: localeTypeSchema.default(result1.global.lang),
532
- "command-prefix": import_core4.Tsu.String().default(result1.global["command-prefix"])
533
- })
534
- ).default(import_core4.DEFAULT_CORE_CONFIG.adapter)
535
- }).parse(result1);
536
- } catch (err) {
537
- if (!(err instanceof import_core4.TsuError)) throw err;
538
- import_logger4.default.fatal(`file ${baseDir.config} format error: ${err.message}`);
539
- process.exit();
540
- }
541
- }
542
- var Loader = class extends import_core4.Container {
543
- ctx;
544
- loadCount = 0;
545
- constructor(options) {
546
- super();
547
- const filename = options && options.mode?.startsWith(DEV_MODE) ? DEV_CONFIG_NAME : BUILD_CONFIG_NAME;
548
- const runnerConfig = {
549
- baseDir: getBaseDir(filename, options?.dir),
550
- options: { mode: options?.mode || BUILD_MODE },
551
- level: options?.level || options?.mode?.startsWith(DEV_MODE) ? import_logger4.LoggerLevel.DEBUG : import_logger4.LoggerLevel.INFO
552
- };
553
- const ctx = new import_core4.Core(getCoreConfig(runnerConfig.baseDir));
554
- ctx.provide("runner", new runner_default(ctx, runnerConfig));
555
- ctx.mixin("runner", ["baseDir", "options"]);
556
- import_core4.Container.setInstance(ctx);
557
- ctx.provide("loader-tools", { format: (0, import_core4.formatFactory)(ctx.i18n), locale: ctx.i18n.locale.bind(ctx.i18n) });
558
- ctx.mixin("loader-tools", ["locale", "format"]);
559
- ctx.i18n.use(import_node_path3.default.resolve(__dirname, "../../locales"));
560
- this.ctx = import_core4.Container.getInstance();
561
- this.ctx.logger.trace(`options:`, options);
562
- this.ctx.logger.trace(`runnerConfig:`, runnerConfig);
563
- this.ctx.logger.trace(`baseDir:`, this.ctx.baseDir);
564
- this.ctx.logger.trace(`options:`, this.ctx.options);
565
- this.ctx.logger.trace(`config:`, this.ctx.config);
566
- this.ctx.logger.trace(`where:`, __dirname, __filename);
567
- this.ctx.logger.trace(`running:`, process.cwd());
568
- }
569
- run() {
570
- log_default(this.ctx.pkg, this.ctx);
571
- this.catchError();
572
- this.listenMessage();
573
- this.setPreService();
574
- this.loadAllModules();
575
- this.checkUpdate();
576
- }
577
- handleError(err, prefix) {
578
- if (!(err instanceof import_core4.KotoriError)) {
579
- if (err instanceof Error) {
580
- this.ctx.logger.label(prefix).error(err.message, err.stack);
581
- } else {
582
- this.ctx.logger.label(prefix).error(err);
583
- }
584
- return;
585
- }
586
- const list = {
587
- ServiceError: () => this.ctx.logger.label("service").warn,
588
- ModuleError: () => this.ctx.logger.label("module").error,
589
- UnknownError: () => this.ctx.logger.error,
590
- DevError: () => this.ctx.logger.label("error").debug
591
- };
592
- list[err.name]().bind(this.ctx.logger)(err.message, err.stack);
593
- }
594
- catchError() {
595
- process.on("uncaughtExceptionMonitor", (err) => this.handleError(err, "sync"));
596
- process.on("unhandledRejection", (err) => this.handleError(err, "async"));
597
- process.on("SIGINT", () => process.exit());
598
- this.ctx.logger.debug(this.ctx.locale("loader.debug.info"));
599
- }
600
- listenMessage() {
601
- this.ctx.on("connect", (data) => {
602
- const { type, mode, normal, address: addr, adapter } = data;
603
- let msg;
604
- if (type === "connect") {
605
- switch (mode) {
606
- case "ws":
607
- msg = this.ctx.format(`loader.bots.${normal ? "connect" : "reconnect"}`, [addr]);
608
- break;
609
- case "ws-reverse":
610
- msg = this.ctx.format(`loader.bots.${normal ? "start" : "restart"}`, [addr]);
611
- break;
612
- default:
613
- msg = this.ctx.format("loader.bots.ready", [addr]);
614
- }
615
- } else {
616
- switch (mode) {
617
- case "ws":
618
- msg = this.ctx.format(`loader.bots.disconnect${normal ? "" : ".error"}`, [addr]);
619
- break;
620
- case "ws-reverse":
621
- msg = this.ctx.format(`loader.bots.stop${normal ? "" : ".error"}`, [addr]);
622
- break;
623
- default:
624
- msg = this.ctx.format("loader.bots.dispose", [addr]);
625
- }
626
- }
627
- adapter.ctx.logger[normal ? "info" : "warn"](msg);
628
- });
629
- this.ctx.on("status", ({ status, adapter }) => adapter.ctx.logger.info(status));
630
- this.ctx.on("ready_module", (data) => {
631
- if (typeof data.instance !== "object") return;
632
- const pkg = data.instance.name ? this.ctx.get("runner")[import_core4.Symbols.modules].get(data.instance.name) : void 0;
633
- if (!pkg) return;
634
- this.loadCount += 1;
635
- const { name, version, author, peerDependencies } = pkg[0].pkg;
636
- this.ctx.logger.info(
637
- this.ctx.format("loader.modules.load", [name, version, Array.isArray(author) ? author.join(",") : author])
638
- );
639
- const requiredVersion = peerDependencies["kotori-bot"];
640
- if (requiredVersion.includes("workspace") || SUPPORTS_VERSION.exec(requiredVersion) || requiredVersion.includes(this.ctx.pkg.version))
641
- return;
642
- if (SUPPORTS_HALF_VERSION.exec(requiredVersion)) {
643
- this.ctx.logger.warn(this.ctx.format("loader.modules.incomplete", [requiredVersion]));
644
- } else {
645
- this.ctx.logger.error(this.ctx.format("loader.modules.unsupported", [requiredVersion]));
646
- }
647
- });
648
- }
649
- setPreService() {
650
- this.ctx.service("server", new server_default(this.ctx.extends(), { port: this.ctx.config.global.port }));
651
- this.ctx.service("file", new file_default(this.ctx.extends()));
652
- }
653
- loadAllModules() {
654
- this.ctx.get("runner").loadAll();
655
- const failLoadCount = this.ctx.get("runner")[import_core4.Symbols.modules].size - this.loadCount;
656
- this.ctx.logger.info(
657
- this.ctx.format(`loader.modules.all${failLoadCount > 0 ? ".failed" : ""}`, [this.loadCount, failLoadCount])
658
- );
659
- this.loadAllAdapter();
660
- this.ctx.emit("ready");
661
- }
662
- loadAllAdapter() {
663
- const adapters = this.ctx[import_core4.Symbols.adapter];
664
- Object.keys(this.ctx.config.adapter).forEach((botName) => {
665
- const botConfig = this.ctx.config.adapter[botName];
666
- const array = adapters.get(botConfig.extends);
667
- if (!array)
668
- return this.ctx.logger.warn(this.ctx.format("loader.adapters.notfound", [botConfig.extends, botName]));
669
- const result = array[1]?.parseSafe(botConfig);
670
- if (result && !result.value)
671
- throw new import_core4.ModuleError(this.ctx.format("error.module.config_bot", [botName, result.error.message]));
672
- const bot = new array[0](
673
- this.ctx.extends({}, `${botConfig.extends}/${botName}`),
674
- result ? result.data : botConfig,
675
- botName
676
- );
677
- this.ctx.on("ready", () => bot.start());
678
- this.ctx.on("dispose", () => bot.stop());
679
- });
680
- }
681
- async checkUpdate() {
682
- const { version } = this.ctx.pkg;
683
- const res = await this.ctx.http.get("https://hotaru.icu/api/agent/?url=https://raw.githubusercontent.com/kotorijs/kotori/master/packages/core/package.json" /* UPDATE */).catch(() => this.ctx.logger.error(this.ctx.locale("loader.tips.update.failed")));
684
- if (!res || !import_core4.Tsu.Object({ version: import_core4.Tsu.String() }).check(res)) {
685
- this.ctx.logger.warn(this.ctx.locale("loader.tips.update.failed"));
686
- } else if (version === res.version) {
687
- this.ctx.logger.info(this.ctx.locale("loader.tips.update.latest"));
688
- } else {
689
- this.ctx.logger.warn(this.ctx.format("loader.tips.update.available", [version, res.version, "https://github.com/kotorijs/kotori" /* REPO */]));
690
- }
691
- }
692
- };
693
-
694
- // src/decorators/index.ts
695
- var import_node_fs3 = require("fs");
696
- var import_node_path5 = require("path");
697
- var import_core6 = require("@kotori-bot/core");
698
-
699
- // src/decorators/utils.ts
700
- var import_node_path4 = require("path");
701
- var import_core5 = require("@kotori-bot/core");
702
- var Decorators = class {
703
- ctx;
704
- isCreated = false;
705
- object;
706
- /* eslint-disable @typescript-eslint/no-explicit-any */
707
- register(callback) {
708
- return (...args) => this.ctx.root.once("ready_module_decorators", (pkgName) => {
709
- if (pkgName === this.ctx.identity) {
710
- callback(...args);
711
- return;
712
- }
713
- this.register(callback);
714
- });
715
- }
716
- /* eslint-enable @typescript-eslint/no-explicit-any */
717
- constructor(ctx) {
718
- this.ctx = ctx;
719
- if (!this.ctx.root.get("decorators")) this.ctx.root.provide("decorators", { registers: [] });
720
- if (this.ctx.identity) this.ctx.root.get("decorators").registers.push(this.ctx.identity);
721
- }
722
- import = (Target) => {
723
- this.register(() => {
724
- if (!this.isCreated) this.schema(Target, void 0);
725
- })();
726
- };
727
- lang = (target, property) => {
728
- this.register(() => {
729
- const lang = target[property];
730
- this.ctx.parent.i18n.use((0, import_node_path4.resolve)(...Array.isArray(lang) ? lang : [lang]));
731
- })();
732
- };
733
- inject = (target, property) => {
734
- this.register(() => {
735
- const inject = target[property];
736
- inject.forEach(
737
- (identity) => this.ctx[import_core5.Tokens.container].forEach((service, name) => {
738
- if (!(service instanceof import_core5.Service) || service.identity !== identity) return;
739
- this.ctx.inject(name);
740
- })
741
- );
742
- })();
743
- };
744
- schema = (Target, property) => {
745
- this.register(() => {
746
- let config = (this.ctx[import_core5.Symbols.modules].get(this.ctx.identity) ?? [])[1];
747
- if (Target[property]) {
748
- const result = Target[property].parseSafe(config);
749
- if (!result.value)
750
- throw new import_core5.ModuleError(`Config format of module ${this.ctx.identity} is error: ${result.error.message}`);
751
- config = result.data;
752
- }
753
- if (this.isCreated) return;
754
- this.isCreated = true;
755
- this.object = new Target(this.ctx, config);
756
- this.ctx.root.emit("ready_module", { instance: { name: this.ctx.identity, config } });
757
- })();
758
- };
759
- on(meta) {
760
- return this.register(
761
- (target, property) => this.ctx.on(meta.type, (...args) => target[property].bind(this.object)(...args))
762
- );
763
- }
764
- once(meta) {
765
- return this.register(
766
- (target, property) => this.ctx.once(meta.type, (...args) => target[property].bind(this.object)(...args))
767
- );
768
- }
769
- midware(meta) {
770
- return this.register(
771
- (target, property) => this.ctx.midware((next, session) => target[property].bind(this.object)(next, session), meta?.priority)
772
- );
773
- }
774
- command(meta) {
775
- return this.register((target, property) => {
776
- const command = this.ctx.command(meta.template, meta).action((data, session) => target[property].bind(this.object)(data, session));
777
- meta.options?.forEach(([name, template]) => command.option(name, template));
778
- });
779
- }
780
- regexp(meta) {
781
- return this.register(
782
- (target, property) => this.ctx.regexp(meta.match, (match2, session) => target[property].bind(this.object)(match2, session))
783
- );
784
- }
785
- task(meta) {
786
- return this.register(
787
- (target, property) => this.ctx.task(meta, (ctx) => target[property].bind(this.object)(ctx))
788
- );
789
- }
790
- };
791
- var utils_default = Decorators;
792
-
793
- // src/decorators/plugin.ts
794
- var KotoriPlugin = class {
795
- ctx;
796
- config;
797
- constructor(ctx, config) {
798
- this.ctx = ctx;
799
- this.config = config;
800
- }
801
- };
802
-
803
- // src/decorators/index.ts
804
- function plugins(plugin) {
805
- let pkgName;
806
- if (!Array.isArray(plugin) && typeof plugin === "object") {
807
- pkgName = plugin.name;
808
- } else {
809
- pkgName = JSON.parse(
810
- (0, import_node_fs3.readFileSync)((0, import_node_path5.resolve)(...Array.isArray(plugin) ? plugin : [plugin], "package.json")).toString()
811
- ).name;
812
- }
813
- const ctx = import_core6.Container.getInstance().extends(void 0, pkgName);
814
- return new utils_default(ctx);
815
- }
816
-
817
- // src/index.ts
29
+ __reExport(src_exports, require("./class/loader"), module.exports);
30
+ __reExport(src_exports, require("./constants"), module.exports);
31
+ __reExport(src_exports, require("./decorators"), module.exports);
32
+ __reExport(src_exports, require("./types"), module.exports);
818
33
  __reExport(src_exports, require("@kotori-bot/logger"), module.exports);
819
34
  // Annotate the CommonJS export names for ESM import in node:
820
35
  0 && (module.exports = {
821
- BUILD_CONFIG_NAME,
822
- BUILD_FILE,
823
- BUILD_MODE,
824
- CONFIG_EXT,
825
- CORE_MODULES,
826
- DEV_CODE_DIRS,
827
- DEV_CONFIG_NAME,
828
- DEV_FILE,
829
- DEV_IMPORT,
830
- DEV_MODE,
831
- DEV_SOURCE_MODE,
832
- KotoriPlugin,
833
- Loader,
834
- SUPPORTS_HALF_VERSION,
835
- SUPPORTS_VERSION,
836
- plugins,
36
+ ...require("./class/loader"),
37
+ ...require("./constants"),
38
+ ...require("./decorators"),
39
+ ...require("./types"),
837
40
  ...require("@kotori-bot/logger")
838
41
  });