koatty 4.1.6 → 4.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,591 +1,866 @@
1
+ 'use strict';
2
+
3
+ var koatty_config = require('koatty_config');
4
+ var koatty_container = require('koatty_container');
5
+ var koatty_core = require('koatty_core');
6
+ var koatty_exception = require('koatty_exception');
7
+ var koatty_lib = require('koatty_lib');
8
+ var koatty_router = require('koatty_router');
9
+ var koatty_serve = require('koatty_serve');
10
+ var koatty_logger = require('koatty_logger');
11
+ var koatty_loader = require('koatty_loader');
12
+ var koatty_trace = require('koatty_trace');
13
+ var path = require('path');
14
+
15
+ function _interopNamespace(e) {
16
+ if (e && e.__esModule) return e;
17
+ var n = Object.create(null);
18
+ if (e) {
19
+ Object.keys(e).forEach(function (k) {
20
+ if (k !== 'default') {
21
+ var d = Object.getOwnPropertyDescriptor(e, k);
22
+ Object.defineProperty(n, k, d.get ? d : {
23
+ enumerable: true,
24
+ get: function () { return e[k]; }
25
+ });
26
+ }
27
+ });
28
+ }
29
+ n.default = e;
30
+ return Object.freeze(n);
31
+ }
32
+
33
+ var path__namespace = /*#__PURE__*/_interopNamespace(path);
34
+
1
35
  /*!
2
36
  * @Author: richen
3
- * @Date: 2026-02-04 10:57:35
37
+ * @Date: 2026-02-10 09:13:30
4
38
  * @License: BSD (3-Clause)
5
39
  * @Copyright (c) - <richenlin(at)gmail.com>
6
40
  * @HomePage: https://koatty.org/
7
41
  */
8
- "use strict";
9
-
10
- var e = require("koatty_config");
11
-
12
- var t = require("koatty_container");
13
-
14
- var o = require("koatty_core");
15
-
16
- var a = require("koatty_exception");
17
-
18
- var r = require("koatty_lib");
19
-
20
- var n = require("koatty_router");
21
-
22
- var s = require("koatty_serve");
23
-
24
- var i = require("koatty_logger");
25
-
26
- var l = require("koatty_loader");
27
-
28
- var c = require("koatty_trace");
29
-
30
- var p = require("path");
42
+ var __defProp = Object.defineProperty;
43
+ var __getOwnPropNames = Object.getOwnPropertyNames;
44
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
45
+ var __commonJS = (cb, mod) => function __require2() {
46
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
47
+ };
31
48
 
32
- function f(e) {
33
- var t = Object.create(null);
34
- if (e) Object.keys(e).forEach(function(o) {
35
- if (o !== "default") {
36
- var a = Object.getOwnPropertyDescriptor(e, o);
37
- Object.defineProperty(t, o, a.get ? a : {
38
- enumerable: !0,
39
- get: function() {
40
- return e[o];
49
+ // package.json
50
+ var require_package = __commonJS({
51
+ "package.json"(exports$1, module) {
52
+ module.exports = {
53
+ name: "koatty",
54
+ version: "4.1.8",
55
+ description: "Koa + Typescript = koatty. Use Typescript's decorator implement auto injection.",
56
+ scripts: {
57
+ build: "pnpm run build:js && pnpm run build:dts && pnpm run build:doc && pnpm run build:cp",
58
+ "build:js": "tsup",
59
+ "build:dts": "bash scripts/build-dts.sh",
60
+ "build:doc": "api-documenter markdown --input temp --output docs/api",
61
+ "build:cp": "node scripts/copyFiles && node ../../scripts/postBuild.js",
62
+ clean: "rimraf dist temp docs/api",
63
+ lint: "eslint --ext .ts,.js ./src",
64
+ test: "pnpm run lint && jest --passWithNoTests",
65
+ "test:cov": "jest --collectCoverage --detectOpenHandles"
66
+ },
67
+ main: "./dist/index.js",
68
+ exports: {
69
+ ".": {
70
+ types: "./dist/index.d.ts",
71
+ import: "./dist/index.mjs",
72
+ require: "./dist/index.js"
41
73
  }
42
- });
74
+ },
75
+ keywords: [
76
+ "koatty",
77
+ "koa",
78
+ "typescript",
79
+ "framework",
80
+ "mvc",
81
+ "http",
82
+ "https",
83
+ "websocket",
84
+ "grpc",
85
+ "quic",
86
+ "http2",
87
+ "http3",
88
+ "di",
89
+ "aop",
90
+ "ioc",
91
+ "inversion of control",
92
+ "dependency injection",
93
+ "aspect-oriented programming",
94
+ "decorator",
95
+ "decorator pattern",
96
+ "decorator factory"
97
+ ],
98
+ directories: {
99
+ doc: "docs"
100
+ },
101
+ repository: {
102
+ type: "git",
103
+ url: "git+https://github.com/koatty/koatty.git"
104
+ },
105
+ engines: {
106
+ node: ">=18.0.0"
107
+ },
108
+ author: {
109
+ name: "richenlin",
110
+ email: "richenlin@gmail.com"
111
+ },
112
+ license: "BSD-3-Clause",
113
+ bugs: {
114
+ url: "https://github.com/koatty/koatty/issues"
115
+ },
116
+ homepage: "https://github.com/koatty/koatty",
117
+ maintainers: [
118
+ {
119
+ name: "richenlin",
120
+ email: "richenlin@gmail.com"
121
+ }
122
+ ],
123
+ devDependencies: {
124
+ "@grpc/grpc-js": "^1.12.2",
125
+ "@microsoft/api-documenter": "^7.26.x",
126
+ "@microsoft/api-extractor": "^7.52.x",
127
+ "@types/formidable": "^3.x.x",
128
+ "@types/jest": "^29.5.x",
129
+ "@types/koa": "^2.x.x",
130
+ "@types/koa-compose": "^3.x.x",
131
+ "@types/lodash": "^4.x.x",
132
+ "@types/node": "^22.x.x",
133
+ "@types/on-finished": "^2.x.x",
134
+ "@types/supertest": "^6.x.x",
135
+ "@types/ws": "^8.x.x",
136
+ "@typescript-eslint/eslint-plugin": "^8.x.x",
137
+ "@typescript-eslint/parser": "^8.x.x",
138
+ eslint: "^8.x.x",
139
+ "eslint-plugin-jest": "^28.x.x",
140
+ jest: "^29.x.x",
141
+ "jest-html-reporters": "^3.x.x",
142
+ koatty_validation: "workspace:*",
143
+ "reflect-metadata": "^0.2.2",
144
+ supertest: "^7.x.x",
145
+ "ts-jest": "^29.x.x",
146
+ tslib: "^2.x.x"
147
+ },
148
+ dependencies: {
149
+ koa: "^3.1.1",
150
+ koatty_config: "workspace:*",
151
+ koatty_container: "workspace:*",
152
+ koatty_core: "workspace:*",
153
+ koatty_exception: "workspace:*",
154
+ koatty_lib: "workspace:*",
155
+ koatty_loader: "workspace:*",
156
+ koatty_logger: "workspace:*",
157
+ koatty_router: "workspace:*",
158
+ koatty_serve: "workspace:*",
159
+ koatty_trace: "workspace:*",
160
+ "ts-morph": "^27.0.2"
161
+ },
162
+ types: "./dist/index.d.ts"
163
+ };
164
+ }
165
+ });
166
+ var pkg = require_package();
167
+ var { engines, version } = pkg;
168
+ var KOATTY_VERSION = version;
169
+ var ENGINES_VERSION = engines.node.slice(1) || "12.0.0";
170
+ function checkClass(fileName, xpath, target, exSet) {
171
+ if (koatty_lib.Helper.isClass(target) && target.name != fileName) {
172
+ throw Error(`The file(${xpath}) name should be always the same as class name.`);
173
+ }
174
+ if (target["__esModule"]) {
175
+ if (target.name === void 0) {
176
+ const keys = Object.keys(target);
177
+ if (keys[0] != fileName && koatty_lib.Helper.isClass(target[keys[0]])) {
178
+ throw Error(`The file(${xpath}) name should be always the same as class name.`);
179
+ }
180
+ } else if (target.name != fileName) {
181
+ throw Error(`The file(${xpath}) name should be always the same as class name.`);
43
182
  }
44
- });
45
- t.default = e;
46
- return Object.freeze(t);
47
- }
48
-
49
- var g = f(p);
50
-
51
- /*
52
- * @Description: framework helper
53
- * @Usage:
54
- * @Author: richen
55
- * @Date: 2023-12-09 21:56:32
56
- * @LastEditTime: 2025-01-14 16:14:10
57
- * @License: BSD (3-Clause)
58
- * @Copyright (c): <richenlin(at)gmail.com>
59
- */ const d = require("../../package.json");
60
-
61
- const {engines: u, version: y} = d;
62
-
63
- const L = y;
64
-
65
- const v = u.node.slice(1) || "12.0.0";
66
-
67
- function m(e, t, o, a) {
68
- if (r.Helper.isClass(o) && o.name != e) throw Error(`The file(${t}) name should be always the same as class name.`);
69
- if (o["__esModule"]) if (o.name === void 0) {
70
- const a = Object.keys(o);
71
- if (a[0] != e && r.Helper.isClass(o[a[0]])) throw Error(`The file(${t}) name should be always the same as class name.`);
72
- } else if (o.name != e) throw Error(`The file(${t}) name should be always the same as class name.`);
73
- if (!a) return;
74
- if (a.has(e)) throw new Error(`A same class already exists. at \`${t}\`.`);
75
- a.add(e);
183
+ }
184
+ if (!exSet) {
185
+ return;
186
+ }
187
+ if (exSet.has(fileName)) {
188
+ throw new Error(`A same class already exists. at \`${xpath}\`.`);
189
+ }
190
+ exSet.add(fileName);
76
191
  return;
77
192
  }
78
-
79
- function h() {
80
- let e = v;
81
- e = e.slice(0, e.lastIndexOf("."));
82
- let t = process.version;
83
- if (t[0] === "v") t = t.slice(1);
84
- t = t.slice(0, t.lastIndexOf("."));
85
- if (r.Helper.toNumber(e) > r.Helper.toNumber(t)) i.DefaultLogger.Fatal(`Koatty need node version > ${e}, current version is ${t}, please upgrade it.`);
193
+ __name(checkClass, "checkClass");
194
+ function checkRuntime() {
195
+ let nodeEngines = ENGINES_VERSION;
196
+ nodeEngines = nodeEngines.slice(0, nodeEngines.lastIndexOf("."));
197
+ let nodeVersion = process.version;
198
+ if (nodeVersion[0] === "v") {
199
+ nodeVersion = nodeVersion.slice(1);
200
+ }
201
+ nodeVersion = nodeVersion.slice(0, nodeVersion.lastIndexOf("."));
202
+ if (koatty_lib.Helper.toNumber(nodeEngines) > koatty_lib.Helper.toNumber(nodeVersion)) {
203
+ koatty_logger.DefaultLogger.Fatal(`Koatty need node version > ${nodeEngines}, current version is ${nodeVersion}, please upgrade it.`);
204
+ }
86
205
  }
87
-
88
- const C = () => {
89
- let e = !1;
90
- const t = JSON.stringify(process.argv[1]);
91
- if (t.indexOf("jest") > -1) e = !0;
92
- return e;
93
- };
94
-
95
- /*
96
- * @Description: framework constants
97
- * @Usage:
98
- * @Author: richen
99
- * @Date: 2023-12-09 21:56:32
100
- * @LastEditTime: 2023-12-09 23:00:13
101
- * @License: BSD (3-Clause)
102
- * @Copyright (c): <richenlin(at)gmail.com>
103
- */ const E = "COMPONENT_SCAN";
104
-
105
- const O = "CONFIGURATION_SCAN";
106
-
107
- const w = `\n\n┬┌─┌─┐┌─┐┌┬┐┌┬┐┬ ┬\n├┴┐│ │├─┤ │ │ └┬┘\n┴ ┴└─┘┴ ┴ ┴ ┴ ┴ \n-------------------------------------------\nhttps://github.com/koatty\n`
108
- /*
109
- * @Description: framework loader
110
- * @Usage:
111
- * @Author: richen
112
- * @Date: 2023-12-09 22:55:49
113
- * @LastEditTime: 2025-03-13 16:44:39
114
- * @License: BSD (3-Clause)
115
- * @Copyright (c): <richenlin(at)gmail.com>
116
- */;
117
-
118
- class Loader {
119
- constructor(e) {
120
- this.app = e;
206
+ __name(checkRuntime, "checkRuntime");
207
+ var checkUTRuntime = /* @__PURE__ */ __name(() => {
208
+ let isUTRuntime = false;
209
+ const argv = JSON.stringify(process.argv[1]);
210
+ if (argv.indexOf("jest") > -1) {
211
+ isUTRuntime = true;
212
+ }
213
+ return isUTRuntime;
214
+ }, "checkUTRuntime");
215
+
216
+ // src/core/Constants.ts
217
+ var COMPONENT_SCAN = "COMPONENT_SCAN";
218
+ var CONFIGURATION_SCAN = "CONFIGURATION_SCAN";
219
+ var LOGO = `
220
+
221
+ \u252C\u250C\u2500\u250C\u2500\u2510\u250C\u2500\u2510\u250C\u252C\u2510\u250C\u252C\u2510\u252C \u252C
222
+ \u251C\u2534\u2510\u2502 \u2502\u251C\u2500\u2524 \u2502 \u2502 \u2514\u252C\u2518
223
+ \u2534 \u2534\u2514\u2500\u2518\u2534 \u2534 \u2534 \u2534 \u2534
224
+ -------------------------------------------
225
+ https://github.com/koatty
226
+ `;
227
+ var Loader = class _Loader {
228
+ static {
229
+ __name(this, "Loader");
121
230
  }
122
- static initialize(e) {
123
- if (e.env == "development") i.DefaultLogger.setLevel("debug"); else i.DefaultLogger.setLevel("info");
124
- const t = e.rootPath || process.cwd();
125
- const o = e.appPath || g.resolve(t, e.appDebug ? "src" : "dist");
126
- const a = g.resolve(__dirname, "..");
127
- r.Helper.define(e, "rootPath", t);
128
- r.Helper.define(e, "appPath", o);
129
- r.Helper.define(e, "koattyPath", a);
130
- if (r.Helper.isEmpty(e.name)) {
131
- const t = r.Helper.safeRequire(`${g.dirname(o)}/package.json`);
132
- if (t.name) {
133
- e.name = t.name;
134
- e.version = e.version || t.version;
231
+ app;
232
+ /**
233
+ * Creates an instance of Loader.
234
+ * @param {KoattyApplication} app
235
+ * @memberof Loader
236
+ */
237
+ constructor(app) {
238
+ this.app = app;
239
+ }
240
+ /**
241
+ * Initialize application configuration and environment settings.
242
+ * Sets up logging levels, defines essential paths, and loads application metadata.
243
+ *
244
+ * @param {KoattyApplication} app - The Koatty application instance
245
+ * - Sets logging level based on environment
246
+ * - Defines root, app and framework paths on app object
247
+ * - Loads application name and version from package.json
248
+ * - Sets environment variables for paths
249
+ * - Maintains backward compatibility with legacy path variables
250
+ */
251
+ static initialize(app) {
252
+ if (app.env == "development") {
253
+ koatty_logger.DefaultLogger.setLevel("debug");
254
+ } else {
255
+ koatty_logger.DefaultLogger.setLevel("info");
256
+ }
257
+ const rootPath = app.rootPath || process.cwd();
258
+ const appPath = app.appPath || path__namespace.resolve(rootPath, app.appDebug ? "src" : "dist");
259
+ const koattyPath = path__namespace.resolve(__dirname, "..");
260
+ koatty_lib.Helper.define(app, "rootPath", rootPath);
261
+ koatty_lib.Helper.define(app, "appPath", appPath);
262
+ koatty_lib.Helper.define(app, "koattyPath", koattyPath);
263
+ if (koatty_lib.Helper.isEmpty(app.name)) {
264
+ const pkg2 = koatty_lib.Helper.safeRequire(`${path__namespace.dirname(appPath)}/package.json`);
265
+ if (pkg2.name) {
266
+ app.name = pkg2.name;
267
+ app.version = app.version || pkg2.version;
135
268
  }
136
269
  }
137
- process.env.ROOT_PATH = t;
138
- process.env.APP_PATH = o;
139
- process.env.KOATTY_PATH = a;
140
- process.env.THINK_PATH = a;
141
- r.Helper.define(e, "thinkPath", a);
270
+ process.env.ROOT_PATH = rootPath;
271
+ process.env.APP_PATH = appPath;
272
+ process.env.KOATTY_PATH = koattyPath;
273
+ process.env.THINK_PATH = koattyPath;
274
+ koatty_lib.Helper.define(app, "thinkPath", koattyPath);
142
275
  }
143
- static GetComponentMeta(e, o) {
144
- let a = [];
145
- const n = t.IOC.getClassMetadata(t.TAGGED_CLS, E, o);
146
- if (n) if (r.Helper.isArray(n)) a = n; else a.push(n);
147
- if (a.length < 1) a = [ e.appPath ];
148
- return a;
276
+ /**
277
+ * Get component metadata from target class.
278
+ *
279
+ * @param {KoattyApplication} app - The Koatty application instance
280
+ * @param {any} target - The target class to get metadata from
281
+ * @returns {any[]} Array of component metadata paths
282
+ *
283
+ * @static
284
+ * @public
285
+ */
286
+ static GetComponentMeta(app, target) {
287
+ let componentMetas = [];
288
+ const componentMeta = koatty_container.IOC.getClassMetadata(koatty_container.TAGGED_CLS, COMPONENT_SCAN, target);
289
+ if (componentMeta) {
290
+ if (koatty_lib.Helper.isArray(componentMeta)) {
291
+ componentMetas = componentMeta;
292
+ } else {
293
+ componentMetas.push(componentMeta);
294
+ }
295
+ }
296
+ if (componentMetas.length < 1) {
297
+ componentMetas = [
298
+ app.appPath
299
+ ];
300
+ }
301
+ return componentMetas;
149
302
  }
150
- static GetConfigurationMeta(e, o) {
151
- const a = t.IOC.getClassMetadata(t.TAGGED_CLS, O, o);
152
- let n = [];
153
- if (a) if (r.Helper.isArray(a)) n = a; else n.push(a);
154
- return n;
303
+ /**
304
+ * Get configuration metadata from target class.
305
+ *
306
+ * @param {KoattyApplication} app Application instance
307
+ * @param {any} target Target class
308
+ * @returns {any[]} Array of configuration metadata
309
+ */
310
+ static GetConfigurationMeta(app, target) {
311
+ const confMeta = koatty_container.IOC.getClassMetadata(koatty_container.TAGGED_CLS, CONFIGURATION_SCAN, target);
312
+ let configurationMetas = [];
313
+ if (confMeta) {
314
+ if (koatty_lib.Helper.isArray(confMeta)) {
315
+ configurationMetas = confMeta;
316
+ } else {
317
+ configurationMetas.push(confMeta);
318
+ }
319
+ }
320
+ return configurationMetas;
155
321
  }
156
- static CheckAllComponents(e, t) {
157
- const o = Loader.GetComponentMeta(e, t);
158
- const a = Loader.GetConfigurationMeta(e, t);
159
- const r = new Set;
160
- l.Load(o, "", (e, t, o) => {
161
- m(e, t, o, r);
162
- }, [ "**/**.js", "**/**.ts", "!**/**.d.ts" ], [ ...a, `${t.name || ".no"}.ts` ]);
163
- r.clear();
322
+ /**
323
+ * Check and load all components(excepted config/*、App.ts) in the application.
324
+ *
325
+ * @param {KoattyApplication} app - The Koatty application instance
326
+ * @param {any} target - The target class or object to check components from
327
+ * @static
328
+ * @public
329
+ */
330
+ static CheckAllComponents(app, target) {
331
+ const componentMetas = _Loader.GetComponentMeta(app, target);
332
+ const configurationMetas = _Loader.GetConfigurationMeta(app, target);
333
+ const exSet = /* @__PURE__ */ new Set();
334
+ koatty_loader.Load(componentMetas, "", (fileName, xpath, xTarget) => {
335
+ checkClass(fileName, xpath, xTarget, exSet);
336
+ }, [
337
+ "**/**.js",
338
+ "**/**.ts",
339
+ "!**/**.d.ts"
340
+ ], [
341
+ ...configurationMetas,
342
+ `${target.name || ".no"}.ts`
343
+ ]);
344
+ exSet.clear();
164
345
  }
165
- static SetLogger(e) {
166
- const t = e.getMetaData("_configs") || [];
167
- const a = t[0] || {};
168
- if (a.config) {
169
- const t = a.config;
170
- let n = "debug", s = "", l = [];
171
- if (e.env === "production") n = "info";
172
- if (t.logsLevel) n = t.logsLevel.toLowerCase();
173
- if (t.logsPath) s = t.logsPath;
174
- if (t.sensFields) l = t.sensFields;
175
- if (!e.appDebug) {
176
- i.DefaultLogger.enableBatch(!0);
177
- i.DefaultLogger.setBatchConfig({
346
+ /**
347
+ * Set logger configuration for the Koatty application.
348
+ *
349
+ * @param {KoattyApplication} app - The Koatty application instance
350
+ * @description Configures logging settings based on application environment and config options.
351
+ * Handles log level, log file path, and sensitive fields configuration.
352
+ * In production environment, default log level is 'info', otherwise 'debug'.
353
+ */
354
+ static SetLogger(app) {
355
+ const data = app.getMetaData("_configs") || [];
356
+ const configs = data[0] || {};
357
+ if (configs.config) {
358
+ const opt = configs.config;
359
+ let logLevel = "debug", logFilePath = "", sensFields = [];
360
+ if (app.env === "production") {
361
+ logLevel = "info";
362
+ }
363
+ if (opt.logsLevel) {
364
+ logLevel = opt.logsLevel.toLowerCase();
365
+ }
366
+ if (opt.logsPath) {
367
+ logFilePath = opt.logsPath;
368
+ }
369
+ if (opt.sensFields) {
370
+ sensFields = opt.sensFields;
371
+ }
372
+ if (!app.appDebug) {
373
+ koatty_logger.DefaultLogger.enableBatch(true);
374
+ koatty_logger.DefaultLogger.setBatchConfig({
178
375
  maxSize: 200,
179
376
  flushInterval: 500
180
377
  });
181
378
  }
182
- if (n) i.DefaultLogger.setLevel(n);
183
- if (s && !e.silent) {
184
- r.Helper.define(e, "logsPath", s);
185
- process.env.LOGS_PATH = s;
186
- i.DefaultLogger.setLogFilePath(s);
379
+ if (logLevel) {
380
+ koatty_logger.DefaultLogger.setLevel(logLevel);
381
+ }
382
+ if (logFilePath && !app.silent) {
383
+ koatty_lib.Helper.define(app, "logsPath", logFilePath);
384
+ process.env.LOGS_PATH = logFilePath;
385
+ koatty_logger.DefaultLogger.setLogFilePath(logFilePath);
187
386
  }
188
- if (l) i.DefaultLogger.setSensFields(l);
189
- e.once(o.AppEvent.appStop, async () => {
190
- await i.DefaultLogger.flushBatch();
191
- await i.DefaultLogger.destroy();
387
+ if (sensFields) {
388
+ koatty_logger.DefaultLogger.setSensFields(sensFields);
389
+ }
390
+ app.once(koatty_core.AppEvent.appStop, async () => {
391
+ await koatty_logger.DefaultLogger.flushBatch();
392
+ await koatty_logger.DefaultLogger.destroy();
192
393
  });
193
394
  }
194
395
  }
195
- static async LoadAllComponents(e, a) {
396
+ /**
397
+ * Load all components and initialize the application.
398
+ *
399
+ * @param app - The KoattyApplication instance
400
+ * @param target - The target class or object containing configuration metadata
401
+ *
402
+ * This method performs the following initialization steps:
403
+ * 1. Loads configurations
404
+ * 2. Creates server and router instances
405
+ * 3. Loads components, middlewares, services and controllers
406
+ * 4. Sets up routing
407
+ *
408
+ * @static
409
+ * @async
410
+ */
411
+ static async LoadAllComponents(app, target) {
196
412
  try {
197
- if (r.Helper.isFunction(t.IOC.preloadMetadata)) t.IOC.preloadMetadata();
413
+ if (koatty_lib.Helper.isFunction(koatty_container.IOC.preloadMetadata)) {
414
+ koatty_container.IOC.preloadMetadata();
415
+ }
198
416
  } catch {
199
- i.DefaultLogger.Warn("[Loader] preloadMetadata is optional, ignore if not available");
417
+ koatty_logger.DefaultLogger.Warn("[Loader] preloadMetadata is optional, ignore if not available");
200
418
  }
201
- const n = Loader.GetConfigurationMeta(e, a);
202
- const s = new Loader(e);
203
- for (const t of o.AppEventArr) switch (t) {
204
- case o.AppEvent.appBoot:
205
- i.DefaultLogger.Log("Koatty", "", "Load Configurations ...");
206
- s.LoadConfigs(n);
207
- Loader.SetLogger(e);
208
- await o.asyncEvent(e, t);
209
- break;
210
-
211
- case o.AppEvent.loadConfigure:
212
- i.DefaultLogger.Log("Koatty", "", "Emit loadConfigure ...");
213
- await o.asyncEvent(e, t);
214
- break;
215
-
216
- case o.AppEvent.loadComponent:
217
- i.DefaultLogger.Log("Koatty", "", "Initializing Component Manager ...");
218
- const l = new o.ComponentManager(e);
219
- r.Helper.define(e, "componentManager", l);
220
- l.discoverComponents();
221
- const c = l.getStats();
222
- i.DefaultLogger.Log("Koatty", "", `Discovered ${c.coreComponents} core components, ${c.userComponents} user components`);
223
- i.DefaultLogger.Log("Koatty", "", "Load Components ...");
224
- await s.LoadComponents(l);
225
- l.registerAppEvents(a);
226
- l.registerCoreComponentHooks();
227
- await o.asyncEvent(e, t);
228
- break;
229
-
230
- case o.AppEvent.loadPlugin:
231
- i.DefaultLogger.Log("Koatty", "", "Emit loadPlugin ...");
232
- await o.asyncEvent(e, t);
233
- break;
234
-
235
- case o.AppEvent.loadMiddleware:
236
- i.DefaultLogger.Log("Koatty", "", "Load Middlewares ...");
237
- await s.LoadMiddlewares();
238
- await o.asyncEvent(e, t);
239
- break;
240
-
241
- case o.AppEvent.loadService:
242
- i.DefaultLogger.Log("Koatty", "", "Load Services ...");
243
- await s.LoadServices();
244
- await o.asyncEvent(e, t);
245
- break;
246
-
247
- case o.AppEvent.loadController:
248
- i.DefaultLogger.Log("Koatty", "", "Load Controllers ...");
249
- await s.LoadControllers();
250
- await o.asyncEvent(e, t);
251
- break;
252
-
253
- case o.AppEvent.loadRouter:
254
- i.DefaultLogger.Log("Koatty", "", "Initialize Router and Load Routes ...");
255
- await o.asyncEvent(e, t);
256
- break;
257
-
258
- case o.AppEvent.loadServe:
259
- i.DefaultLogger.Log("Koatty", "", "Emit loadServe ...");
260
- await o.asyncEvent(e, t);
261
- break;
262
-
263
- case o.AppEvent.appReady:
264
- i.DefaultLogger.Log("Koatty", "", "Emit appReady ...");
265
- await o.asyncEvent(e, t);
266
- break;
267
-
268
- default:
269
- await o.asyncEvent(e, t);
270
- break;
419
+ const configurationMeta = _Loader.GetConfigurationMeta(app, target);
420
+ const loader = new _Loader(app);
421
+ for (const event of koatty_core.AppEventArr) {
422
+ switch (event) {
423
+ case koatty_core.AppEvent.appBoot:
424
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Load Configurations ...");
425
+ loader.LoadConfigs(configurationMeta);
426
+ _Loader.SetLogger(app);
427
+ await koatty_core.asyncEvent(app, event);
428
+ break;
429
+ case koatty_core.AppEvent.loadConfigure:
430
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Emit loadConfigure ...");
431
+ await koatty_core.asyncEvent(app, event);
432
+ break;
433
+ case koatty_core.AppEvent.loadComponent:
434
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Initializing Component Manager ...");
435
+ const componentManager = new koatty_core.ComponentManager(app);
436
+ koatty_lib.Helper.define(app, "componentManager", componentManager);
437
+ componentManager.discoverComponents();
438
+ const stats = componentManager.getStats();
439
+ koatty_logger.DefaultLogger.Log("Koatty", "", `Discovered ${stats.coreComponents} core components, ${stats.userComponents} user components`);
440
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Load Components ...");
441
+ await loader.LoadComponents(componentManager);
442
+ componentManager.registerAppEvents(target);
443
+ componentManager.registerCoreComponentHooks();
444
+ await koatty_core.asyncEvent(app, event);
445
+ break;
446
+ case koatty_core.AppEvent.loadPlugin:
447
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Emit loadPlugin ...");
448
+ await koatty_core.asyncEvent(app, event);
449
+ break;
450
+ case koatty_core.AppEvent.loadMiddleware:
451
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Load Middlewares ...");
452
+ await loader.LoadMiddlewares();
453
+ await koatty_core.asyncEvent(app, event);
454
+ break;
455
+ case koatty_core.AppEvent.loadService:
456
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Load Services ...");
457
+ await loader.LoadServices();
458
+ await koatty_core.asyncEvent(app, event);
459
+ break;
460
+ case koatty_core.AppEvent.loadController:
461
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Load Controllers ...");
462
+ await loader.LoadControllers();
463
+ await koatty_core.asyncEvent(app, event);
464
+ break;
465
+ case koatty_core.AppEvent.loadRouter:
466
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Initialize Router and Load Routes ...");
467
+ await koatty_core.asyncEvent(app, event);
468
+ break;
469
+ case koatty_core.AppEvent.loadServe:
470
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Emit loadServe ...");
471
+ await koatty_core.asyncEvent(app, event);
472
+ break;
473
+ case koatty_core.AppEvent.appReady:
474
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Emit appReady ...");
475
+ await koatty_core.asyncEvent(app, event);
476
+ break;
477
+ default:
478
+ await koatty_core.asyncEvent(app, event);
479
+ break;
480
+ }
271
481
  }
272
482
  }
273
- LoadConfigs(t) {
274
- const o = {};
275
- l.Load([ "./config" ], this.app.koattyPath, function(e, t, a) {
276
- o[e] = a;
483
+ /**
484
+ * Load configuration files from specified paths.
485
+ * First loads framework configurations from './config' directory,
486
+ * then loads application configurations from custom paths.
487
+ * Finally merges both configurations with framework configs as lower priority.
488
+ *
489
+ * @protected
490
+ * @param {string[]} [loadPath] - Optional array of paths to load application configs from
491
+ */
492
+ LoadConfigs(loadPath) {
493
+ const frameConfig = {};
494
+ koatty_loader.Load([
495
+ "./config"
496
+ ], this.app.koattyPath, function(name, path2, exp) {
497
+ frameConfig[name] = exp;
277
498
  });
278
- if (r.Helper.isArray(t)) t = t.length > 0 ? t : [ "./config" ];
279
- let a = e.LoadConfigs(t, this.app.appPath);
280
- a = r.Helper.extend(o, a, !0);
281
- this.app.setMetaData("_configs", a);
499
+ if (koatty_lib.Helper.isArray(loadPath)) {
500
+ loadPath = loadPath.length > 0 ? loadPath : [
501
+ "./config"
502
+ ];
503
+ }
504
+ let appConfig = koatty_config.LoadConfigs(loadPath, this.app.appPath);
505
+ appConfig = koatty_lib.Helper.extend(frameConfig, appConfig, true);
506
+ this.app.setMetaData("_configs", appConfig);
282
507
  }
508
+ /**
509
+ * Load and register middleware components.
510
+ * Processes middleware configuration, registers middleware classes with IOC container,
511
+ * and mounts middleware to the application.
512
+ * Supports protocol-specific middleware mounting via @Middleware({ protocol }) option.
513
+ *
514
+ * @protected
515
+ * @returns {Promise<void>}
516
+ * @throws {Error} When middleware doesn't implement IMiddleware interface
517
+ * @throws {Error} When middleware loading fails
518
+ */
283
519
  async LoadMiddlewares() {
284
- var e, a, n, s;
285
- let l = this.app.config(void 0, "middleware");
286
- if (r.Helper.isEmpty(l)) l = {
287
- config: {},
288
- list: []
289
- };
520
+ let middlewareConf = this.app.config(void 0, "middleware");
521
+ if (koatty_lib.Helper.isEmpty(middlewareConf)) {
522
+ middlewareConf = {
523
+ config: {},
524
+ list: []
525
+ };
526
+ }
290
527
  try {
291
- const t = (a = (e = l.config) === null || e === void 0 ? void 0 : e.trace) !== null && a !== void 0 ? a : {};
292
- const o = c.Trace(t, this.app);
293
- r.Helper.define(this.app, "tracer", o);
294
- this.app.use(o);
295
- i.DefaultLogger.Debug(`Trace middleware registered`);
296
- } catch (e) {
297
- i.DefaultLogger.Warn(`Trace middleware failed to load: ${e.message}`);
528
+ const traceOptions = middlewareConf.config?.trace ?? {};
529
+ const tracer = koatty_trace.Trace(traceOptions, this.app);
530
+ koatty_lib.Helper.define(this.app, "tracer", tracer);
531
+ this.app.use(tracer);
532
+ koatty_logger.DefaultLogger.Debug(`Trace middleware registered`);
533
+ } catch (error) {
534
+ koatty_logger.DefaultLogger.Warn(`Trace middleware failed to load: ${error.message}`);
298
535
  }
299
- const p = (n = t.IOC.listClass("MIDDLEWARE")) !== null && n !== void 0 ? n : [];
300
- p.forEach(e => {
301
- var a;
302
- e.id = ((a = e.id) !== null && a !== void 0 ? a : "").replace("MIDDLEWARE:", "");
303
- if (e.id && r.Helper.isClass(e.target)) {
304
- t.IOC.reg(e.id, e.target, {
536
+ const appMiddleware = koatty_container.IOC.listClass("MIDDLEWARE") ?? [];
537
+ appMiddleware.forEach((item) => {
538
+ item.id = (item.id ?? "").replace("MIDDLEWARE:", "");
539
+ if (item.id && koatty_lib.Helper.isClass(item.target)) {
540
+ koatty_container.IOC.reg(item.id, item.target, {
305
541
  scope: "Prototype",
306
542
  type: "MIDDLEWARE",
307
543
  args: []
308
544
  });
309
- const a = t.IOC.getInsByClass(e.target);
310
- if (!o.implementsMiddlewareInterface(a)) throw Error(`The middleware ${e.id} must implements interface 'IMiddleware'.`);
545
+ const ctl = koatty_container.IOC.getInsByClass(item.target);
546
+ if (!koatty_core.implementsMiddlewareInterface(ctl)) {
547
+ throw Error(`The middleware ${item.id} must implements interface 'IMiddleware'.`);
548
+ }
311
549
  }
312
550
  });
313
- const f = l.list || [];
314
- const g = new Set([]);
315
- f.forEach(e => {
316
- g.add(e);
551
+ const middlewareList = middlewareConf.list || [];
552
+ const appMList = /* @__PURE__ */ new Set([]);
553
+ middlewareList.forEach((item) => {
554
+ appMList.add(item);
317
555
  });
318
- const d = l.config || {};
319
- for (const e of Array.from(g)) {
320
- const a = t.IOC.get(e, "MIDDLEWARE");
321
- if (!a) throw Error(`Middleware ${e} load error.`);
322
- if (!r.Helper.isFunction(a.run)) throw Error(`The middleware ${e} must implements interface 'IMiddleware'.`);
323
- i.DefaultLogger.Debug(`Load middleware: ${e}`);
324
- const n = d[e] || {};
325
- const l = (s = p.find(t => t.id === e)) === null || s === void 0 ? void 0 : s.target;
326
- let c = {};
327
- if (l) try {
328
- c = t.IOC.getPropertyData(o.MIDDLEWARE_OPTIONS, l, e) || {};
329
- } catch {
330
- c = {};
556
+ const middlewareConfig = middlewareConf.config || {};
557
+ for (const key of Array.from(appMList)) {
558
+ const handle = koatty_container.IOC.get(key, "MIDDLEWARE");
559
+ if (!handle) {
560
+ throw Error(`Middleware ${key} load error.`);
561
+ }
562
+ if (!koatty_lib.Helper.isFunction(handle.run)) {
563
+ throw Error(`The middleware ${key} must implements interface 'IMiddleware'.`);
564
+ }
565
+ koatty_logger.DefaultLogger.Debug(`Load middleware: ${key}`);
566
+ const middlewareOpt = middlewareConfig[key] || {};
567
+ const middlewareClass = appMiddleware.find((m) => m.id === key)?.target;
568
+ let decoratorOptions = {};
569
+ if (middlewareClass) {
570
+ try {
571
+ decoratorOptions = koatty_container.IOC.getPropertyData(koatty_core.MIDDLEWARE_OPTIONS, middlewareClass, key) || {};
572
+ } catch {
573
+ decoratorOptions = {};
574
+ }
331
575
  }
332
- const f = {
333
- ...c,
334
- ...n
576
+ const mergedOptions = {
577
+ ...decoratorOptions,
578
+ ...middlewareOpt
335
579
  };
336
- if (f.enabled === !1) {
337
- i.DefaultLogger.Warn(`The middleware ${e} has been loaded but is disabled.`);
580
+ if (mergedOptions.enabled === false) {
581
+ koatty_logger.DefaultLogger.Warn(`The middleware ${key} has been loaded but is disabled.`);
338
582
  continue;
339
583
  }
340
- const g = await a.run(f, this.app);
341
- if (r.Helper.isFunction(g)) {
342
- let t = g;
343
- if (f.protocol) {
344
- const a = r.Helper.isArray(f.protocol) ? f.protocol : [ f.protocol ];
345
- i.DefaultLogger.Log("Koatty", "", `Middleware ${e} limited to protocols: ${a.join(", ")}`);
346
- t = o.protocolMiddleware(a, g);
584
+ const result = await handle.run(mergedOptions, this.app);
585
+ if (koatty_lib.Helper.isFunction(result)) {
586
+ let middleware = result;
587
+ if (mergedOptions.protocol) {
588
+ const protocols = koatty_lib.Helper.isArray(mergedOptions.protocol) ? mergedOptions.protocol : [
589
+ mergedOptions.protocol
590
+ ];
591
+ koatty_logger.DefaultLogger.Log("Koatty", "", `Middleware ${key} limited to protocols: ${protocols.join(", ")}`);
592
+ middleware = koatty_core.protocolMiddleware(protocols, result);
593
+ }
594
+ if (middleware.length < 3) {
595
+ this.app.use(middleware);
596
+ } else {
597
+ this.app.useExp(middleware);
347
598
  }
348
- if (t.length < 3) this.app.use(t); else this.app.useExp(t);
349
599
  }
350
600
  }
351
601
  }
602
+ /**
603
+ * Load and register controller classes from IOC container.
604
+ * Each controller must implement the IController interface.
605
+ *
606
+ * @returns {Promise<string[]>} A promise that resolves to an array of controller IDs.
607
+ * @protected
608
+ * @throws {Error} If a controller does not implement the IController interface.
609
+ */
352
610
  async LoadControllers() {
353
- const e = t.IOC.listClass("CONTROLLER");
354
- const a = [];
355
- e.forEach(e => {
356
- var n;
357
- e.id = ((n = e.id) !== null && n !== void 0 ? n : "").replace("CONTROLLER:", "");
358
- if (e.id && r.Helper.isClass(e.target)) {
359
- i.DefaultLogger.Debug(`Load controller: ${e.id}`);
360
- t.IOC.reg(e.id, e.target, {
611
+ const controllerList = koatty_container.IOC.listClass("CONTROLLER");
612
+ const controllers = [];
613
+ controllerList.forEach((item) => {
614
+ item.id = (item.id ?? "").replace("CONTROLLER:", "");
615
+ if (item.id && koatty_lib.Helper.isClass(item.target)) {
616
+ koatty_logger.DefaultLogger.Debug(`Load controller: ${item.id}`);
617
+ koatty_container.IOC.reg(item.id, item.target, {
361
618
  scope: "Prototype",
362
619
  type: "CONTROLLER",
363
620
  args: []
364
621
  });
365
- const r = t.IOC.getInsByClass(e.target);
366
- if (!o.implementsControllerInterface(r)) throw Error(`The controller ${e.id} must implements interface 'IController'.`);
367
- a.push(e.id);
622
+ const ctl = koatty_container.IOC.getInsByClass(item.target);
623
+ if (!koatty_core.implementsControllerInterface(ctl)) {
624
+ throw Error(`The controller ${item.id} must implements interface 'IController'.`);
625
+ }
626
+ controllers.push(item.id);
368
627
  }
369
628
  });
370
- this.app.setMetaData("_controllers", a);
371
- return a;
629
+ this.app.setMetaData("_controllers", controllers);
630
+ return controllers;
372
631
  }
632
+ /**
633
+ * Load and register service components into IOC container.
634
+ * Each service must implement the IService interface.
635
+ * Services are registered with singleton scope.
636
+ *
637
+ * @protected
638
+ * @returns {Promise<void>}
639
+ * @throws {Error} When service does not implement IService interface
640
+ */
373
641
  async LoadServices() {
374
- var e;
375
- const a = t.IOC.listClass("SERVICE");
376
- for (const n of a) {
377
- n.id = ((e = n.id) !== null && e !== void 0 ? e : "").replace("SERVICE:", "");
378
- if (n.id && r.Helper.isClass(n.target)) {
379
- i.DefaultLogger.Debug(`Load service: ${n.id}`);
380
- t.IOC.reg(n.id, n.target, {
642
+ const serviceList = koatty_container.IOC.listClass("SERVICE");
643
+ for (const item of serviceList) {
644
+ item.id = (item.id ?? "").replace("SERVICE:", "");
645
+ if (item.id && koatty_lib.Helper.isClass(item.target)) {
646
+ koatty_logger.DefaultLogger.Debug(`Load service: ${item.id}`);
647
+ koatty_container.IOC.reg(item.id, item.target, {
381
648
  scope: "Singleton",
382
649
  type: "SERVICE",
383
650
  args: []
384
651
  });
385
- const e = t.IOC.getInsByClass(n.target);
386
- if (!o.implementsServiceInterface(e)) throw Error(`The service ${n.id} must implements interface 'IService'.`);
652
+ const ctl = koatty_container.IOC.getInsByClass(item.target);
653
+ if (!koatty_core.implementsServiceInterface(ctl)) {
654
+ throw Error(`The service ${item.id} must implements interface 'IService'.`);
655
+ }
387
656
  }
388
657
  }
389
658
  }
390
- async LoadComponents(e) {
391
- var a, n;
392
- const s = t.IOC.listClass("COMPONENT");
393
- s.forEach(e => {
394
- var a;
395
- e.id = ((a = e.id) !== null && a !== void 0 ? a : "").replace("COMPONENT:", "");
396
- if (r.Helper.isClass(e.target)) {
397
- t.IOC.reg(e.id, e.target, {
659
+ /**
660
+ * Load and initialize components, plugins and aspects.
661
+ * Components with suffix 'Plugin' must implement IPlugin interface.
662
+ * Components with suffix 'Aspect' must implement IAspect interface.
663
+ * Plugins are loaded based on configuration and executed synchronously.
664
+ *
665
+ * @protected
666
+ * @returns {Promise<void>}
667
+ * @throws {Error} When plugin/aspect doesn't implement required interface
668
+ * @throws {Error} When plugin loading fails
669
+ */
670
+ async LoadComponents(componentManager) {
671
+ const componentList = koatty_container.IOC.listClass("COMPONENT");
672
+ componentList.forEach((item) => {
673
+ item.id = (item.id ?? "").replace("COMPONENT:", "");
674
+ if (koatty_lib.Helper.isClass(item.target)) {
675
+ koatty_container.IOC.reg(item.id, item.target, {
398
676
  scope: "Singleton",
399
677
  type: "COMPONENT",
400
678
  args: []
401
679
  });
402
- if (e.id && e.id.endsWith("Aspect")) {
403
- const a = t.IOC.getInsByClass(e.target);
404
- if (!o.implementsAspectInterface(a)) throw Error(`The aspect ${e.id} must implements interface 'IAspect'.`);
680
+ if (item.id && item.id.endsWith("Aspect")) {
681
+ const ctl = koatty_container.IOC.getInsByClass(item.target);
682
+ if (!koatty_core.implementsAspectInterface(ctl)) {
683
+ throw Error(`The aspect ${item.id} must implements interface 'IAspect'.`);
684
+ }
405
685
  }
406
686
  }
407
687
  });
408
- if (e) await e.loadUserComponents(); else {
409
- i.DefaultLogger.Warn("Loading plugins in legacy mode");
410
- let e = this.app.config(void 0, "plugin");
411
- if (r.Helper.isEmpty(e)) e = {
412
- config: {},
413
- list: []
414
- };
415
- const o = (a = e.list) !== null && a !== void 0 ? a : [];
416
- for (const a of o) {
417
- const o = t.IOC.get(a, "COMPONENT");
418
- if (!o) throw Error(`Plugin ${a} load error.`);
419
- if (!r.Helper.isFunction(o.run)) throw Error(`Plugin ${a} must implements interface 'IPlugin'.`);
420
- if (e.config[a] === !1) {
421
- i.DefaultLogger.Warn(`Plugin ${a} already loaded but not effective.`);
688
+ if (componentManager) {
689
+ await componentManager.loadUserComponents();
690
+ } else {
691
+ koatty_logger.DefaultLogger.Warn("Loading plugins in legacy mode");
692
+ let pluginsConf = this.app.config(void 0, "plugin");
693
+ if (koatty_lib.Helper.isEmpty(pluginsConf)) {
694
+ pluginsConf = {
695
+ config: {},
696
+ list: []
697
+ };
698
+ }
699
+ const pluginConfList = pluginsConf.list ?? [];
700
+ for (const key of pluginConfList) {
701
+ const handle = koatty_container.IOC.get(key, "COMPONENT");
702
+ if (!handle) {
703
+ throw Error(`Plugin ${key} load error.`);
704
+ }
705
+ if (!koatty_lib.Helper.isFunction(handle.run)) {
706
+ throw Error(`Plugin ${key} must implements interface 'IPlugin'.`);
707
+ }
708
+ if (pluginsConf.config[key] === false) {
709
+ koatty_logger.DefaultLogger.Warn(`Plugin ${key} already loaded but not effective.`);
422
710
  continue;
423
711
  }
424
- await o.run((n = e.config[a]) !== null && n !== void 0 ? n : {}, this.app);
712
+ await handle.run(pluginsConf.config[key] ?? {}, this.app);
425
713
  }
426
714
  }
427
715
  }
428
- }
429
-
430
- /*
431
- * @Description: framework bootstrap
432
- * @Usage:
433
- * @Author: richen
434
- * @Date: 2021-12-09 21:56:32
435
- * @LastEditTime: 2025-01-14 16:11:21
436
- * @License: BSD (3-Clause)
437
- * @Copyright (c): <richenlin(at)gmail.com>
438
- */ function D(e) {
439
- return async t => {
440
- if (!(t.prototype instanceof o.Koatty)) throw new Error(`class ${t.name} does not inherit from Koatty`);
441
- return await b(t, e, !0);
716
+ };
717
+ function ExecBootStrap(bootFunc) {
718
+ return async (target) => {
719
+ if (!(target.prototype instanceof koatty_core.Koatty)) {
720
+ throw new Error(`class ${target.name} does not inherit from Koatty`);
721
+ }
722
+ return await executeBootstrap(target, bootFunc, true);
442
723
  };
443
724
  }
444
-
445
- const b = async function(e, a, n = !1) {
725
+ __name(ExecBootStrap, "ExecBootStrap");
726
+ var executeBootstrap = /* @__PURE__ */ __name(async function(target, bootFunc, isInitiative = false) {
446
727
  if (process.env.NODE_DEBUG) {
447
- const e = process.env.NODE_DEBUG.split(",").filter(e => !e.includes("winston")).join(",");
448
- process.env.NODE_DEBUG = e;
728
+ const debugModules = process.env.NODE_DEBUG.split(",").filter((m) => !m.includes("winston")).join(",");
729
+ process.env.NODE_DEBUG = debugModules;
449
730
  }
450
- h();
451
- const s = C();
452
- if (!n && s) return;
453
- const l = Reflect.construct(e, []);
454
- if (s) {
455
- l.silent = !0;
456
- i.DefaultLogger.enable(!1);
731
+ checkRuntime();
732
+ const isUTRuntime = checkUTRuntime();
733
+ if (!isInitiative && isUTRuntime) {
734
+ return;
735
+ }
736
+ const app = Reflect.construct(target, []);
737
+ if (isUTRuntime) {
738
+ app.silent = true;
739
+ koatty_logger.DefaultLogger.enable(false);
457
740
  }
458
741
  try {
459
- if (!l.silent) console.log(w);
460
- if (!(l instanceof o.Koatty)) throw new Error(`class ${e.name} does not inherit from Koatty`);
461
- Loader.initialize(l);
462
- if (r.Helper.isFunction(a)) {
463
- i.DefaultLogger.Log("Koatty", "", "Execute bootFunc ...");
464
- await a(l);
742
+ if (!app.silent) console.log(LOGO);
743
+ if (!(app instanceof koatty_core.Koatty)) {
744
+ throw new Error(`class ${target.name} does not inherit from Koatty`);
745
+ }
746
+ Loader.initialize(app);
747
+ if (koatty_lib.Helper.isFunction(bootFunc)) {
748
+ koatty_logger.DefaultLogger.Log("Koatty", "", "Execute bootFunc ...");
749
+ await bootFunc(app);
465
750
  }
466
- t.IOC.setApp(l);
467
- i.DefaultLogger.Log("Koatty", "", "ComponentScan ...");
468
- Loader.CheckAllComponents(l, e);
469
- await Loader.LoadAllComponents(l, e);
470
- if (!s) l.listen(I);
471
- return l;
472
- } catch (e) {
473
- i.DefaultLogger.Fatal(e);
751
+ koatty_container.IOC.setApp(app);
752
+ koatty_logger.DefaultLogger.Log("Koatty", "", "ComponentScan ...");
753
+ Loader.CheckAllComponents(app, target);
754
+ await Loader.LoadAllComponents(app, target);
755
+ if (!isUTRuntime) {
756
+ app.listen(listenCallback);
757
+ }
758
+ return app;
759
+ } catch (err) {
760
+ koatty_logger.DefaultLogger.Fatal(err);
474
761
  }
475
- };
476
-
477
- const I = e => {
478
- i.DefaultLogger.Log("Koatty", "", "====================================");
479
- i.DefaultLogger.Log("Koatty", "", `Nodejs Version: ${process.version}`);
480
- i.DefaultLogger.Log("Koatty", "", `Koatty Version: v${L}`);
481
- i.DefaultLogger.Log("Koatty", "", `App Environment: ${e.env}`);
482
- if (e.appDebug) i.DefaultLogger.Warn(`Running in debug mode.`);
483
- i.DefaultLogger.Log("Koatty", "", "====================================");
484
- o.asyncEvent(e, o.AppEvent.appStart);
485
- };
486
-
487
- function P(e) {
488
- return function(a) {
489
- if (!(a.prototype instanceof o.Koatty)) throw new Error(`class does not inherit from Koatty`);
490
- t.IOC.saveClass("COMPONENT", a, "KOATTY_APP");
491
- D(e)(a);
492
- return a;
762
+ }, "executeBootstrap");
763
+ var listenCallback = /* @__PURE__ */ __name((app) => {
764
+ koatty_logger.DefaultLogger.Log("Koatty", "", "====================================");
765
+ koatty_logger.DefaultLogger.Log("Koatty", "", `Nodejs Version: ${process.version}`);
766
+ koatty_logger.DefaultLogger.Log("Koatty", "", `Koatty Version: v${KOATTY_VERSION}`);
767
+ koatty_logger.DefaultLogger.Log("Koatty", "", `App Environment: ${app.env}`);
768
+ if (app.appDebug) koatty_logger.DefaultLogger.Warn(`Running in debug mode.`);
769
+ koatty_logger.DefaultLogger.Log("Koatty", "", "====================================");
770
+ koatty_core.asyncEvent(app, koatty_core.AppEvent.appStart);
771
+ }, "listenCallback");
772
+ function Bootstrap(bootFunc) {
773
+ return function(target) {
774
+ if (!(target.prototype instanceof koatty_core.Koatty)) {
775
+ throw new Error(`class does not inherit from Koatty`);
776
+ }
777
+ koatty_container.IOC.saveClass("COMPONENT", target, "KOATTY_APP");
778
+ ExecBootStrap(bootFunc)(target);
779
+ return target;
493
780
  };
494
781
  }
495
-
496
- function A(e) {
497
- return a => {
498
- if (!(a.prototype instanceof o.Koatty)) throw new Error(`class does not inherit from Koatty`);
499
- e = e !== null && e !== void 0 ? e : "";
500
- t.IOC.saveClassMetadata(t.TAGGED_CLS, E, e, a);
782
+ __name(Bootstrap, "Bootstrap");
783
+ function ComponentScan(scanPath) {
784
+ return (target) => {
785
+ if (!(target.prototype instanceof koatty_core.Koatty)) {
786
+ throw new Error(`class does not inherit from Koatty`);
787
+ }
788
+ scanPath = scanPath ?? "";
789
+ koatty_container.IOC.saveClassMetadata(koatty_container.TAGGED_CLS, COMPONENT_SCAN, scanPath, target);
501
790
  };
502
791
  }
503
-
504
- function M(e) {
505
- return a => {
506
- if (!(a.prototype instanceof o.Koatty)) throw new Error(`class does not inherit from Koatty`);
507
- e = e !== null && e !== void 0 ? e : "";
508
- t.IOC.saveClassMetadata(t.TAGGED_CLS, O, e, a);
792
+ __name(ComponentScan, "ComponentScan");
793
+ function ConfigurationScan(scanPath) {
794
+ return (target) => {
795
+ if (!(target.prototype instanceof koatty_core.Koatty)) {
796
+ throw new Error(`class does not inherit from Koatty`);
797
+ }
798
+ scanPath = scanPath ?? "";
799
+ koatty_container.IOC.saveClassMetadata(koatty_container.TAGGED_CLS, CONFIGURATION_SCAN, scanPath, target);
509
800
  };
510
801
  }
802
+ __name(ConfigurationScan, "ConfigurationScan");
803
+ /**
804
+ * Decorator for Koatty framework
805
+ * @author richen
806
+ * @copyright Copyright (c) - <richenlin(at)gmail.com>
807
+ * @license BSD (3-Clause)
808
+ * @version 2026-02-03 10:00:00
809
+ */
511
810
 
512
811
  Object.defineProperty(exports, "Config", {
513
- enumerable: !0,
514
- get: function() {
515
- return e.Config;
516
- }
812
+ enumerable: true,
813
+ get: function () { return koatty_config.Config; }
517
814
  });
518
-
519
815
  Object.defineProperty(exports, "Helper", {
520
- enumerable: !0,
521
- get: function() {
522
- return r.Helper;
523
- }
816
+ enumerable: true,
817
+ get: function () { return koatty_lib.Helper; }
524
818
  });
525
-
526
819
  Object.defineProperty(exports, "Log", {
527
- enumerable: !0,
528
- get: function() {
529
- return i.Log;
530
- }
820
+ enumerable: true,
821
+ get: function () { return koatty_logger.Log; }
822
+ });
823
+ Object.defineProperty(exports, "LogLevelType", {
824
+ enumerable: true,
825
+ get: function () { return koatty_logger.LogLevelType; }
531
826
  });
532
-
533
827
  Object.defineProperty(exports, "Logger", {
534
- enumerable: !0,
535
- get: function() {
536
- return i.DefaultLogger;
537
- }
828
+ enumerable: true,
829
+ get: function () { return koatty_logger.DefaultLogger; }
538
830
  });
539
-
540
- exports.Bootstrap = P;
541
-
542
- exports.ComponentScan = A;
543
-
544
- exports.ConfigurationScan = M;
545
-
546
- exports.ExecBootStrap = D;
547
-
548
- Object.keys(t).forEach(function(e) {
549
- if (e !== "default" && !Object.prototype.hasOwnProperty.call(exports, e)) Object.defineProperty(exports, e, {
550
- enumerable: !0,
551
- get: function() {
552
- return t[e];
553
- }
831
+ exports.Bootstrap = Bootstrap;
832
+ exports.ComponentScan = ComponentScan;
833
+ exports.ConfigurationScan = ConfigurationScan;
834
+ exports.ExecBootStrap = ExecBootStrap;
835
+ Object.keys(koatty_container).forEach(function (k) {
836
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
837
+ enumerable: true,
838
+ get: function () { return koatty_container[k]; }
554
839
  });
555
840
  });
556
-
557
- Object.keys(o).forEach(function(e) {
558
- if (e !== "default" && !Object.prototype.hasOwnProperty.call(exports, e)) Object.defineProperty(exports, e, {
559
- enumerable: !0,
560
- get: function() {
561
- return o[e];
562
- }
841
+ Object.keys(koatty_core).forEach(function (k) {
842
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
843
+ enumerable: true,
844
+ get: function () { return koatty_core[k]; }
563
845
  });
564
846
  });
565
-
566
- Object.keys(a).forEach(function(e) {
567
- if (e !== "default" && !Object.prototype.hasOwnProperty.call(exports, e)) Object.defineProperty(exports, e, {
568
- enumerable: !0,
569
- get: function() {
570
- return a[e];
571
- }
847
+ Object.keys(koatty_exception).forEach(function (k) {
848
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
849
+ enumerable: true,
850
+ get: function () { return koatty_exception[k]; }
572
851
  });
573
852
  });
574
-
575
- Object.keys(n).forEach(function(e) {
576
- if (e !== "default" && !Object.prototype.hasOwnProperty.call(exports, e)) Object.defineProperty(exports, e, {
577
- enumerable: !0,
578
- get: function() {
579
- return n[e];
580
- }
853
+ Object.keys(koatty_router).forEach(function (k) {
854
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
855
+ enumerable: true,
856
+ get: function () { return koatty_router[k]; }
581
857
  });
582
858
  });
583
-
584
- Object.keys(s).forEach(function(e) {
585
- if (e !== "default" && !Object.prototype.hasOwnProperty.call(exports, e)) Object.defineProperty(exports, e, {
586
- enumerable: !0,
587
- get: function() {
588
- return s[e];
589
- }
859
+ Object.keys(koatty_serve).forEach(function (k) {
860
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
861
+ enumerable: true,
862
+ get: function () { return koatty_serve[k]; }
590
863
  });
591
864
  });
865
+ //# sourceMappingURL=index.js.map
866
+ //# sourceMappingURL=index.js.map