koatty 3.11.9 → 3.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,29 +1,44 @@
1
1
  /*!
2
2
  * @Author: richen
3
- * @Date: 2025-01-14 16:20:07
3
+ * @Date: 2025-04-19 23:06:49
4
4
  * @License: BSD (3-Clause)
5
5
  * @Copyright (c) - <richenlin(at)gmail.com>
6
6
  * @HomePage: https://koatty.org/
7
7
  */
8
- import { LoadConfigs } from 'koatty_config';
9
- export { Config } from 'koatty_config';
10
- import { IOC, TAGGED_CLS } from 'koatty_container';
11
- export * from 'koatty_container';
12
- import { AppEventArr, implementsMiddlewareInterface, implementsControllerInterface, implementsServiceInterface, implementsPluginInterface, implementsAspectInterface, Koatty } from 'koatty_core';
13
- export * from 'koatty_core';
14
- export * from 'koatty_exception';
15
- import { Helper } from 'koatty_lib';
16
- export { Helper } from 'koatty_lib';
17
- import { NewRouter } from 'koatty_router';
18
- export * from 'koatty_router';
19
- import { DefaultLogger } from 'koatty_logger';
20
- import { Load } from 'koatty_loader';
21
- import { NewServe } from 'koatty_serve';
22
- import * as path from 'path';
23
-
24
- var version = "3.11.9";
25
- var engines = {
26
- node: ">12.0.0"
8
+ import { LoadConfigs as t } from "koatty_config";
9
+
10
+ export { Config } from "koatty_config";
11
+
12
+ import { IOC as e, TAGGED_CLS as o } from "koatty_container";
13
+
14
+ export * from "koatty_container";
15
+
16
+ import { AppEventArr as a, implementsMiddlewareInterface as s, parseExp as r, implementsControllerInterface as i, implementsServiceInterface as n, implementsPluginInterface as l, implementsAspectInterface as c, Koatty as p, asyncEvent as d } from "koatty_core";
17
+
18
+ export * from "koatty_core";
19
+
20
+ export * from "koatty_exception";
21
+
22
+ import { Helper as f } from "koatty_lib";
23
+
24
+ export { Helper } from "koatty_lib";
25
+
26
+ import { NewRouter as g } from "koatty_router";
27
+
28
+ export * from "koatty_router";
29
+
30
+ import { DefaultLogger as u } from "koatty_logger";
31
+
32
+ import { Load as h } from "koatty_loader";
33
+
34
+ import { NewServe as m } from "koatty_serve";
35
+
36
+ import * as y from "path";
37
+
38
+ var L = "3.13.0";
39
+
40
+ var v = {
41
+ node: ">12.0.0"
27
42
  };
28
43
 
29
44
  /*
@@ -34,31 +49,16 @@ var engines = {
34
49
  * @LastEditTime: 2024-10-31 17:52:43
35
50
  * @License: BSD (3-Clause)
36
51
  * @Copyright (c): <richenlin(at)gmail.com>
37
- */
38
- // Logger
39
- const Logger = DefaultLogger;
40
- /**
41
- * SetLogger
42
- *
43
- * @export
44
- * @param {{
45
- * logLevel?: LogLevelType;
46
- * logFilePath?: string;
47
- * sensFields?: string[];
48
- * }} config
49
- */
50
- function SetLogger(app, config) {
51
- if (config.logLevel) {
52
- DefaultLogger.setLevel(config.logLevel);
53
- }
54
- if (config.logFilePath && !app.silent) {
55
- Helper.define(app, "logsPath", config.logFilePath);
56
- process.env.LOGS_PATH = config.logFilePath;
57
- DefaultLogger.setLogFilePath(config.logFilePath);
58
- }
59
- if (config.sensFields) {
60
- DefaultLogger.setSensFields(config.sensFields);
61
- }
52
+ */ const w = u;
53
+
54
+ function C(t, e) {
55
+ if (e.logLevel) u.setLevel(e.logLevel);
56
+ if (e.logFilePath && !t.silent) {
57
+ f.define(t, "logsPath", e.logFilePath);
58
+ process.env.LOGS_PATH = e.logFilePath;
59
+ u.setLogFilePath(e.logFilePath);
60
+ }
61
+ if (e.sensFields) u.setSensFields(e.sensFields);
62
62
  }
63
63
 
64
64
  /*
@@ -69,75 +69,39 @@ function SetLogger(app, config) {
69
69
  * @LastEditTime: 2025-01-14 16:14:10
70
70
  * @License: BSD (3-Clause)
71
71
  * @Copyright (c): <richenlin(at)gmail.com>
72
- */
73
- const KOATTY_VERSION = version;
74
- const ENGINES_VERSION = engines.node.slice(1) || '12.0.0';
75
- /**
76
- * Check class file
77
- * name should be always the same as class name
78
- * class must be unique
79
- *
80
- * @export
81
- * @param {string} fileName
82
- * @param {string} xpath
83
- * @param {*} target
84
- * @param {Set<unknown>} [exSet]
85
- * @returns {*}
86
- */
87
- function checkClass(fileName, xpath, target, exSet) {
88
- if (Helper.isClass(target) && target.name != fileName) { // export default class name{}
89
- throw Error(`The file(${xpath}) name should be always the same as class name.`);
90
- }
91
- if (target["__esModule"]) {
92
- if (target.name === undefined) { // export class name{}
93
- const keys = Object.keys(target);
94
- if (keys[0] != fileName && Helper.isClass(target[keys[0]])) {
95
- throw Error(`The file(${xpath}) name should be always the same as class name.`);
96
- }
97
- }
98
- else if (target.name != fileName) { // export default class {}
99
- throw Error(`The file(${xpath}) name should be always the same as class name.`);
100
- }
101
- }
102
- if (!exSet) {
103
- return;
104
- }
105
- if (exSet.has(fileName)) {
106
- throw new Error(`A same class already exists. at \`${xpath}\`.`);
107
- }
108
- exSet.add(fileName);
109
- return;
72
+ */ const E = L;
73
+
74
+ const P = v.node.slice(1) || "12.0.0";
75
+
76
+ function A(t, e, o, a) {
77
+ if (f.isClass(o) && o.name != t) throw Error(`The file(${e}) name should be always the same as class name.`);
78
+ if (o["__esModule"]) if (o.name === void 0) {
79
+ const a = Object.keys(o);
80
+ if (a[0] != t && f.isClass(o[a[0]])) throw Error(`The file(${e}) name should be always the same as class name.`);
81
+ } else if (o.name != t) throw Error(`The file(${e}) name should be always the same as class name.`);
82
+ if (!a) return;
83
+ if (a.has(t)) throw new Error(`A same class already exists. at \`${e}\`.`);
84
+ a.add(t);
85
+ return;
110
86
  }
111
- /**
112
- * check node version
113
- * @return {void} []
114
- */
115
- function checkRuntime() {
116
- let nodeEngines = ENGINES_VERSION;
117
- nodeEngines = nodeEngines.slice(0, nodeEngines.lastIndexOf('.'));
118
- let nodeVersion = process.version;
119
- if (nodeVersion[0] === 'v') {
120
- nodeVersion = nodeVersion.slice(1);
121
- }
122
- nodeVersion = nodeVersion.slice(0, nodeVersion.lastIndexOf('.'));
123
- if (Helper.toNumber(nodeEngines) > Helper.toNumber(nodeVersion)) {
124
- Logger.Error(`Koatty need node version > ${nodeEngines}, current version is ${nodeVersion}, please upgrade it.`);
125
- process.exit(-1);
126
- }
87
+
88
+ function M() {
89
+ let t = P;
90
+ t = t.slice(0, t.lastIndexOf("."));
91
+ let e = process.version;
92
+ if (e[0] === "v") e = e.slice(1);
93
+ e = e.slice(0, e.lastIndexOf("."));
94
+ if (f.toNumber(t) > f.toNumber(e)) {
95
+ w.Error(`Koatty need node version > ${t}, current version is ${e}, please upgrade it.`);
96
+ process.exit(-1);
97
+ }
127
98
  }
128
- /**
129
- * unittest running environment detection
130
- * only support jest
131
- * @returns {boolean}
132
- */
133
- const checkUTRuntime = () => {
134
- let isUTRuntime = false;
135
- // UT运行环境判断,暂时先只判断jest
136
- const argv = JSON.stringify(process.argv[1]);
137
- if (argv.indexOf('jest') > -1) {
138
- isUTRuntime = true;
139
- }
140
- return isUTRuntime;
99
+
100
+ const $ = () => {
101
+ let t = !1;
102
+ const e = JSON.stringify(process.argv[1]);
103
+ if (e.indexOf("jest") > -1) t = !0;
104
+ return t;
141
105
  };
142
106
 
143
107
  /*
@@ -148,442 +112,282 @@ const checkUTRuntime = () => {
148
112
  * @LastEditTime: 2023-12-09 23:00:13
149
113
  * @License: BSD (3-Clause)
150
114
  * @Copyright (c): <richenlin(at)gmail.com>
151
- */
152
- const COMPONENT_SCAN = 'COMPONENT_SCAN';
153
- const CONFIGURATION_SCAN = 'CONFIGURATION_SCAN';
154
- // tslint:disable: no-irregular-whitespace
155
- const LOGO = `
156
-
157
- ┬┌─┌─┐┌─┐┌┬┐┌┬┐┬ ┬
158
- ├┴┐│ │├─┤ │ │ └┬┘
159
- ┴ ┴└─┘┴ ┴ ┴ ┴ ┴
160
- -------------------------------------------
161
- https://github.com/koatty
162
- `;
115
+ */ const R = "COMPONENT_SCAN";
163
116
 
117
+ const k = "CONFIGURATION_SCAN";
118
+
119
+ const T = `\n\n┬┌─┌─┐┌─┐┌┬┐┌┬┐┬ ┬\n├┴┐│ │├─┤ │ │ └┬┘\n┴ ┴└─┘┴ ┴ ┴ ┴ ┴ \n-------------------------------------------\nhttps://github.com/koatty\n`
164
120
  /*
165
121
  * @Description: framework loader
166
122
  * @Usage:
167
123
  * @Author: richen
168
124
  * @Date: 2023-12-09 22:55:49
169
- * @LastEditTime: 2025-01-14 16:12:59
125
+ * @LastEditTime: 2025-03-13 16:44:39
170
126
  * @License: BSD (3-Clause)
171
127
  * @Copyright (c): <richenlin(at)gmail.com>
172
- */
173
- /**
174
- *
175
- */
128
+ */;
129
+
176
130
  class Loader {
177
- /**
178
- * Creates an instance of Loader.
179
- * @param {KoattyApplication} app
180
- * @memberof Loader
181
- */
182
- constructor(app) {
183
- this.app = app;
184
- }
185
- /**
186
- * initialize env
187
- *
188
- * @static
189
- * @param {KoattyApplication} app
190
- * @memberof Loader
191
- */
192
- static initialize(app) {
193
- if (app.env == 'development') {
194
- Logger.setLevel("debug");
195
- }
196
- else {
197
- Logger.setLevel("info");
198
- }
199
- // define path
200
- const rootPath = app.rootPath || process.cwd();
201
- const appPath = app.appPath || path.resolve(rootPath, app.appDebug ? 'src' : 'dist');
202
- const koattyPath = path.resolve(__dirname, '..');
203
- Helper.define(app, 'rootPath', rootPath);
204
- Helper.define(app, 'appPath', appPath);
205
- Helper.define(app, 'koattyPath', koattyPath);
206
- //
207
- if (Helper.isEmpty(app.name)) {
208
- const pkg = Helper.safeRequire(`${path.dirname(appPath)}/package.json`);
209
- if (pkg.name) {
210
- app.name = pkg.name;
211
- app.version = app.version || pkg.version;
212
- }
213
- }
214
- process.env.ROOT_PATH = rootPath;
215
- process.env.APP_PATH = appPath;
216
- process.env.KOATTY_PATH = koattyPath;
217
- // Compatible with old version, will be deprecated
218
- Helper.define(app, 'thinkPath', koattyPath);
219
- process.env.THINK_PATH = koattyPath;
220
- }
221
- /**
222
- * Get component metadata
223
- *
224
- * @static
225
- * @param {KoattyApplication} app
226
- * @param {*} target
227
- * @returns {*} {any[]}
228
- * @memberof Loader
229
- */
230
- static GetComponentMeta(app, target) {
231
- let componentMetas = [];
232
- const componentMeta = IOC.getClassMetadata(TAGGED_CLS, COMPONENT_SCAN, target);
233
- if (componentMeta) {
234
- if (Helper.isArray(componentMeta)) {
235
- componentMetas = componentMeta;
236
- }
237
- else {
238
- componentMetas.push(componentMeta);
239
- }
240
- }
241
- if (componentMetas.length < 1) {
242
- componentMetas = [app.appPath];
243
- }
244
- return componentMetas;
245
- }
246
- /**
247
- * Get configuration metadata
248
- *
249
- * @static
250
- * @param {KoattyApplication} app
251
- * @param {*} target
252
- * @returns {*} {any[]}
253
- * @memberof Loader
254
- */
255
- static GetConfigurationMeta(app, target) {
256
- const confMeta = IOC.getClassMetadata(TAGGED_CLS, CONFIGURATION_SCAN, target);
257
- let configurationMetas = [];
258
- if (confMeta) {
259
- if (Helper.isArray(confMeta)) {
260
- configurationMetas = confMeta;
261
- }
262
- else {
263
- configurationMetas.push(confMeta);
264
- }
265
- }
266
- return configurationMetas;
131
+ constructor(t) {
132
+ this.app = t;
133
+ }
134
+ static initialize(t) {
135
+ if (t.env == "development") w.setLevel("debug"); else w.setLevel("info");
136
+ const e = t.rootPath || process.cwd();
137
+ const o = t.appPath || y.resolve(e, t.appDebug ? "src" : "dist");
138
+ const a = y.resolve(__dirname, "..");
139
+ f.define(t, "rootPath", e);
140
+ f.define(t, "appPath", o);
141
+ f.define(t, "koattyPath", a);
142
+ if (f.isEmpty(t.name)) {
143
+ const e = f.safeRequire(`${y.dirname(o)}/package.json`);
144
+ if (e.name) {
145
+ t.name = e.name;
146
+ t.version = t.version || e.version;
147
+ }
267
148
  }
268
- /**
269
- * Load all bean, excepted config/*、App.ts
270
- *
271
- * @static
272
- * @param {KoattyApplication} app
273
- * @param {*} target
274
- * @memberof Loader
275
- */
276
- static CheckAllComponents(app, target) {
277
- // component metadata
278
- const componentMetas = Loader.GetComponentMeta(app, target);
279
- // configuration metadata
280
- const configurationMetas = Loader.GetConfigurationMeta(app, target);
281
- const exSet = new Set();
282
- Load(componentMetas, '', (fileName, xpath, xTarget) => {
283
- checkClass(fileName, xpath, xTarget, exSet);
284
- }, ['**/**.js', '**/**.ts', '!**/**.d.ts'], [...configurationMetas, `${target.name || '.no'}.ts`]);
285
- exSet.clear();
149
+ process.env.ROOT_PATH = e;
150
+ process.env.APP_PATH = o;
151
+ process.env.KOATTY_PATH = a;
152
+ f.define(t, "thinkPath", a);
153
+ process.env.THINK_PATH = a;
154
+ }
155
+ static GetComponentMeta(t, a) {
156
+ let s = [];
157
+ const r = e.getClassMetadata(o, R, a);
158
+ if (r) if (f.isArray(r)) s = r; else s.push(r);
159
+ if (s.length < 1) s = [ t.appPath ];
160
+ return s;
161
+ }
162
+ static GetConfigurationMeta(t, a) {
163
+ const s = e.getClassMetadata(o, k, a);
164
+ let r = [];
165
+ if (s) if (f.isArray(s)) r = s; else r.push(s);
166
+ return r;
167
+ }
168
+ static CheckAllComponents(t, e) {
169
+ const o = Loader.GetComponentMeta(t, e);
170
+ const a = Loader.GetConfigurationMeta(t, e);
171
+ const s = new Set;
172
+ h(o, "", ((t, e, o) => {
173
+ A(t, e, o, s);
174
+ }), [ "**/**.js", "**/**.ts", "!**/**.d.ts" ], [ ...a, `${e.name || ".no"}.ts` ]);
175
+ s.clear();
176
+ }
177
+ static SetLogger(t) {
178
+ const e = t.getMetaData("_configs") || [];
179
+ const o = e[0] || {};
180
+ if (o.config) {
181
+ const e = o.config;
182
+ let a = "debug", s = "", r = [];
183
+ if (t.env === "production") a = "info";
184
+ if (e.logsLevel) a = e.logsLevel.toLowerCase();
185
+ if (e.logsPath) s = e.logsPath;
186
+ if (e.sensFields) r = e.sensFields;
187
+ C(t, {
188
+ logLevel: a,
189
+ logFilePath: s,
190
+ sensFields: r
191
+ });
286
192
  }
287
- /**
288
- * Set Logger level
289
- *
290
- * @static
291
- * @param {KoattyApplication} app
292
- * @memberof Loader
293
- */
294
- static SetLogger(app) {
295
- const data = app.getMetaData('_configs') || [];
296
- const configs = data[0] || {};
297
- //Logger
298
- if (configs.config) {
299
- const opt = configs.config;
300
- let logLevel = "debug", logFilePath = "", sensFields = [];
301
- if (app.env === "production") {
302
- logLevel = "info";
303
- }
304
- if (opt.logs_level) {
305
- logLevel = (opt.logs_level).toLowerCase();
306
- }
307
- if (opt.logs_path) {
308
- logFilePath = opt.logs_path;
309
- }
310
- if (opt.sens_fields) {
311
- sensFields = opt.sens_fields;
312
- }
313
- SetLogger(app, { logLevel, logFilePath, sensFields });
314
- }
315
- }
316
- /**
317
- * Load app event hook funcs
318
- *
319
- * @static
320
- * @param {KoattyApplication} app
321
- * @param {*} target
322
- * @memberof Loader
323
- */
324
- static LoadAppEventHooks(app, target) {
325
- const eventFuncs = new Map();
326
- for (const event of AppEventArr) {
327
- let funcs;
328
- switch (event) {
329
- case "appBoot" /* AppEvent.appBoot */:
330
- funcs = IOC.getClassMetadata(TAGGED_CLS, "appBoot" /* AppEvent.appBoot */, target);
331
- if (Helper.isArray(funcs)) {
332
- eventFuncs.set("appBoot" /* AppEvent.appBoot */, funcs);
333
- }
334
- break;
335
- case "appReady" /* AppEvent.appReady */:
336
- funcs = IOC.getClassMetadata(TAGGED_CLS, "appReady" /* AppEvent.appReady */, target);
337
- if (Helper.isArray(funcs)) {
338
- eventFuncs.set("appReady" /* AppEvent.appReady */, funcs);
339
- }
340
- break;
341
- case "appStart" /* AppEvent.appStart */:
342
- funcs = IOC.getClassMetadata(TAGGED_CLS, "appStart" /* AppEvent.appStart */, target);
343
- if (Helper.isArray(funcs)) {
344
- eventFuncs.set("appStart" /* AppEvent.appStart */, funcs);
345
- }
346
- break;
347
- case "appStop" /* AppEvent.appStop */:
348
- funcs = IOC.getClassMetadata(TAGGED_CLS, "appStop" /* AppEvent.appStop */, target);
349
- if (Helper.isArray(funcs)) {
350
- eventFuncs.set("appStop" /* AppEvent.appStop */, funcs);
351
- }
352
- break;
353
- }
354
- }
355
- // loop event emit
356
- for (const [event, funcs] of eventFuncs) {
357
- for (const func of funcs) {
358
- app.once(event, () => func(app));
359
- }
360
- }
361
- }
362
- /**
363
- * @description: Load all components
364
- * @param {KoattyApplication} app
365
- * @param {any} target
366
- * @return {*}
367
- */
368
- static async LoadAllComponents(app, target) {
369
- var _a;
370
- // Load configuration
371
- Logger.Log('Koatty', '', 'Load Configurations ...');
372
- // configuration metadata
373
- const configurationMeta = Loader.GetConfigurationMeta(app, target);
374
- const loader = new Loader(app);
375
- loader.LoadConfigs(configurationMeta);
376
- // Create Server
377
- const serveOpts = {
378
- hostname: app.config('app_host'),
379
- port: app.config('app_port'),
380
- protocol: app.config('protocol'),
381
- };
382
- Helper.define(app, "server", NewServe(app, serveOpts));
383
- // Create router
384
- const routerOpts = (_a = app.config(undefined, 'router')) !== null && _a !== void 0 ? _a : {};
385
- Helper.define(app, "router", NewRouter(app, routerOpts));
386
- // Load Components
387
- Logger.Log('Koatty', '', 'Load Components ...');
388
- await loader.LoadComponents();
389
- // Load Middleware
390
- Logger.Log('Koatty', '', 'Load Middlewares ...');
391
- await loader.LoadMiddlewares();
392
- // Load Services
393
- Logger.Log('Koatty', '', 'Load Services ...');
394
- await loader.LoadServices();
395
- // Load Controllers
396
- Logger.Log('Koatty', '', 'Load Controllers ...');
397
- const controllers = await loader.LoadControllers();
398
- // Load Routers
399
- Logger.Log('Koatty', '', 'Load Routers ...');
400
- loader.LoadRouter(controllers);
193
+ }
194
+ static LoadAppEventHooks(t, s) {
195
+ const r = new Map;
196
+ for (const t of a) {
197
+ let a;
198
+ switch (t) {
199
+ case "appBoot":
200
+ a = e.getClassMetadata(o, "appBoot", s);
201
+ if (f.isArray(a)) r.set("appBoot", a);
202
+ break;
203
+
204
+ case "appReady":
205
+ a = e.getClassMetadata(o, "appReady", s);
206
+ if (f.isArray(a)) r.set("appReady", a);
207
+ break;
208
+
209
+ case "appStart":
210
+ a = e.getClassMetadata(o, "appStart", s);
211
+ if (f.isArray(a)) r.set("appStart", a);
212
+ break;
213
+
214
+ case "appStop":
215
+ a = e.getClassMetadata(o, "appStop", s);
216
+ if (f.isArray(a)) r.set("appStop", a);
217
+ break;
218
+ }
401
219
  }
402
- /**
403
- * Load configuration
404
- *
405
- * @param {string[]} [loadPath]
406
- * @memberof Loader
407
- */
408
- LoadConfigs(loadPath) {
409
- const frameConfig = {};
410
- // Logger.Debug(`Load configuration path: ${app.thinkPath}/config`);
411
- Load(["./config"], this.app.koattyPath, function (name, path, exp) {
412
- frameConfig[name] = exp;
220
+ for (const [e, o] of r) for (const a of o) t.once(e, (() => a(t)));
221
+ }
222
+ static async LoadAllComponents(t, e) {
223
+ var o, a, s;
224
+ w.Log("Koatty", "", "Load Configurations ...");
225
+ const r = Loader.GetConfigurationMeta(t, e);
226
+ const i = new Loader(t);
227
+ i.LoadConfigs(r);
228
+ const n = (o = t.config("server")) !== null && o !== void 0 ? o : {
229
+ protocol: "http"
230
+ };
231
+ const l = (a = n.protocol) !== null && a !== void 0 ? a : "http";
232
+ f.define(t, "server", m(t, n));
233
+ const c = (s = t.config(void 0, "router")) !== null && s !== void 0 ? s : {};
234
+ f.define(t, "router", g(t, {
235
+ protocol: l,
236
+ ...c
237
+ }));
238
+ w.Log("Koatty", "", "Load Components ...");
239
+ await i.LoadComponents();
240
+ w.Log("Koatty", "", "Load Middlewares ...");
241
+ await i.LoadMiddlewares();
242
+ w.Log("Koatty", "", "Load Services ...");
243
+ await i.LoadServices();
244
+ w.Log("Koatty", "", "Load Controllers ...");
245
+ const p = await i.LoadControllers();
246
+ w.Log("Koatty", "", "Load Routers ...");
247
+ i.LoadRouter(p);
248
+ }
249
+ LoadConfigs(e) {
250
+ const o = {};
251
+ h([ "./config" ], this.app.koattyPath, (function(t, e, a) {
252
+ o[t] = a;
253
+ }));
254
+ if (f.isArray(e)) e = e.length > 0 ? e : [ "./config" ];
255
+ let a = t(e, this.app.appPath);
256
+ a = f.extend(o, a, !0);
257
+ this.app.setMetaData("_configs", a);
258
+ }
259
+ async LoadMiddlewares() {
260
+ var t;
261
+ let o = this.app.config(void 0, "middleware");
262
+ if (f.isEmpty(o)) o = {
263
+ config: {},
264
+ list: [],
265
+ routeList: []
266
+ };
267
+ const a = (t = e.listClass("MIDDLEWARE")) !== null && t !== void 0 ? t : [];
268
+ a.forEach((t => {
269
+ var o;
270
+ t.id = ((o = t.id) !== null && o !== void 0 ? o : "").replace("MIDDLEWARE:", "");
271
+ if (t.id && f.isClass(t.target)) {
272
+ e.reg(t.id, t.target, {
273
+ scope: "Prototype",
274
+ type: "MIDDLEWARE",
275
+ args: []
413
276
  });
414
- if (Helper.isArray(loadPath)) {
415
- loadPath = loadPath.length > 0 ? loadPath : ["./config"];
416
- }
417
- let appConfig = LoadConfigs(loadPath, this.app.appPath);
418
- appConfig = Helper.extend(frameConfig, appConfig, true);
419
- this.app.setMetaData("_configs", appConfig);
277
+ const o = e.getInsByClass(t.target);
278
+ if (!s(o)) throw Error(`The middleware ${t.id} must implements interface 'IMiddleware'.`);
279
+ }
280
+ }));
281
+ const i = o.list || [];
282
+ const n = new Set([]);
283
+ i.forEach((t => {
284
+ n.add(t);
285
+ }));
286
+ const l = o.routeList || [];
287
+ const c = new Set([]);
288
+ l.forEach((t => {
289
+ c.add(t);
290
+ }));
291
+ const p = o.config || {};
292
+ for (const t of n) {
293
+ const o = e.get(t, "MIDDLEWARE");
294
+ if (!o) throw Error(`Middleware ${t} load error.`);
295
+ if (!f.isFunction(o.run)) throw Error(`The middleware ${t} must implements interface 'IMiddleware'.`);
296
+ w.Debug(`Load middleware: ${t}`);
297
+ const a = p[t] || {};
298
+ const s = await o.run(a, this.app);
299
+ if (f.isFunction(s)) if (s.length < 3) this.app.use(s); else this.app.useExp(s);
420
300
  }
421
- /**
422
- * Load middlewares
423
- * [async]
424
- * @memberof Loader
425
- */
426
- async LoadMiddlewares() {
427
- var _a;
428
- let middlewareConf = this.app.config(undefined, "middleware");
429
- if (Helper.isEmpty(middlewareConf)) {
430
- middlewareConf = { config: {}, list: [] };
431
- }
432
- //Mount default middleware
433
- // Load(loadPath || ["./middleware"], app.koattyPath);
434
- //Mount application middleware
435
- // const middleware: any = {};
436
- const appMiddleware = (_a = IOC.listClass("MIDDLEWARE")) !== null && _a !== void 0 ? _a : [];
437
- appMiddleware.forEach((item) => {
438
- var _a;
439
- item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("MIDDLEWARE:", "");
440
- if (item.id && Helper.isClass(item.target)) {
441
- IOC.reg(item.id, item.target, { scope: "Prototype", type: "MIDDLEWARE", args: [] });
442
- const ctl = IOC.getInsByClass(item.target);
443
- if (!implementsMiddlewareInterface(ctl)) {
444
- throw Error(`The middleware ${item.id} must implements interface 'IMiddleware'.`);
445
- }
446
- }
447
- });
448
- const middlewareConfList = middlewareConf.list || [];
449
- //de-duplication
450
- const appMList = new Set([]);
451
- middlewareConfList.forEach((item) => {
452
- appMList.add(item);
453
- });
454
- //Automatically call middleware
455
- const middlewareConfig = middlewareConf.config || {};
456
- for (const key of appMList) {
457
- const handle = IOC.get(key, "MIDDLEWARE");
458
- if (!handle) {
459
- throw Error(`Middleware ${key} load error.`);
460
- }
461
- if (!Helper.isFunction(handle.run)) {
462
- throw Error(`The middleware ${key} must implements interface 'IMiddleware'.`);
463
- }
464
- if (middlewareConfig[key] === false) {
465
- Logger.Warn(`The middleware ${key} has been loaded but not executed.`);
466
- continue;
467
- }
468
- Logger.Debug(`Load middleware: ${key}`);
469
- const result = await handle.run(middlewareConfig[key] || {}, this.app);
470
- if (Helper.isFunction(result)) {
471
- if (result.length < 3) {
472
- this.app.use(result);
473
- }
474
- else {
475
- this.app.useExp(result);
476
- }
477
- }
478
- }
301
+ for (const t of c) {
302
+ const o = e.get(t, "MIDDLEWARE");
303
+ if (!o) throw Error(`Router middleware ${t} load error.`);
304
+ if (!f.isFunction(o.run)) throw Error(`The router middleware ${t} must implements interface 'IMiddleware'.`);
305
+ w.Debug(`Load router middleware: ${t}`);
306
+ const a = await o.run(p[t] || {}, this.app);
307
+ if (f.isFunction(a)) this.app.setMetaData(`routerMiddleware_${t}`, a.length > 2 ? r(a) : a);
479
308
  }
480
- /**
481
- * Load controllers
482
- *
483
- * @memberof Loader
484
- */
485
- async LoadControllers() {
486
- const controllerList = IOC.listClass("CONTROLLER");
487
- const controllers = [];
488
- controllerList.forEach((item) => {
489
- var _a;
490
- item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("CONTROLLER:", "");
491
- if (item.id && Helper.isClass(item.target)) {
492
- Logger.Debug(`Load controller: ${item.id}`);
493
- // registering to IOC
494
- IOC.reg(item.id, item.target, { scope: "Prototype", type: "CONTROLLER", args: [] });
495
- const ctl = IOC.getInsByClass(item.target);
496
- if (!implementsControllerInterface(ctl)) {
497
- throw Error(`The controller ${item.id} must implements interface 'IController'.`);
498
- }
499
- controllers.push(item.id);
500
- }
309
+ }
310
+ async LoadControllers() {
311
+ const t = e.listClass("CONTROLLER");
312
+ const o = [];
313
+ t.forEach((t => {
314
+ var a;
315
+ t.id = ((a = t.id) !== null && a !== void 0 ? a : "").replace("CONTROLLER:", "");
316
+ if (t.id && f.isClass(t.target)) {
317
+ w.Debug(`Load controller: ${t.id}`);
318
+ e.reg(t.id, t.target, {
319
+ scope: "Prototype",
320
+ type: "CONTROLLER",
321
+ args: []
501
322
  });
502
- return controllers;
503
- }
504
- /**
505
- * Load services
506
- *
507
- * @memberof Loader
508
- */
509
- async LoadServices() {
510
- const serviceList = IOC.listClass("SERVICE");
511
- serviceList.forEach((item) => {
512
- var _a;
513
- item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("SERVICE:", "");
514
- if (item.id && Helper.isClass(item.target)) {
515
- Logger.Debug(`Load service: ${item.id}`);
516
- // registering to IOC
517
- IOC.reg(item.id, item.target, { scope: "Singleton", type: "SERVICE", args: [] });
518
- const ctl = IOC.getInsByClass(item.target);
519
- if (!implementsServiceInterface(ctl)) {
520
- throw Error(`The service ${item.id} must implements interface 'IService'.`);
521
- }
522
- }
323
+ const a = e.getInsByClass(t.target);
324
+ if (!i(a)) throw Error(`The controller ${t.id} must implements interface 'IController'.`);
325
+ o.push(t.id);
326
+ }
327
+ }));
328
+ return o;
329
+ }
330
+ async LoadServices() {
331
+ const t = e.listClass("SERVICE");
332
+ t.forEach((t => {
333
+ var o;
334
+ t.id = ((o = t.id) !== null && o !== void 0 ? o : "").replace("SERVICE:", "");
335
+ if (t.id && f.isClass(t.target)) {
336
+ w.Debug(`Load service: ${t.id}`);
337
+ e.reg(t.id, t.target, {
338
+ scope: "Singleton",
339
+ type: "SERVICE",
340
+ args: []
523
341
  });
524
- }
525
- /**
526
- * Load components
527
- *
528
- * @memberof Loader
529
- */
530
- async LoadComponents() {
531
- var _a, _b;
532
- const componentList = IOC.listClass("COMPONENT");
533
- const pluginList = [];
534
- componentList.forEach(async (item) => {
535
- var _a;
536
- item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("COMPONENT:", "");
537
- if (Helper.isClass(item.target)) {
538
- // registering to IOC
539
- IOC.reg(item.id, item.target, { scope: "Singleton", type: "COMPONENT", args: [] });
540
- if (item.id && (item.id).endsWith("Plugin")) {
541
- const ctl = IOC.getInsByClass(item.target);
542
- if (!implementsPluginInterface(ctl)) {
543
- throw Error(`The plugin ${item.id} must implements interface 'IPlugin'.`);
544
- }
545
- pluginList.push(item.id);
546
- }
547
- if (item.id && (item.id).endsWith("Aspect")) {
548
- const ctl = IOC.getInsByClass(item.target);
549
- if (!implementsAspectInterface(ctl)) {
550
- throw Error(`The aspect ${item.id} must implements interface 'IAspect'.`);
551
- }
552
- }
553
- }
342
+ const o = e.getInsByClass(t.target);
343
+ if (!n(o)) throw Error(`The service ${t.id} must implements interface 'IService'.`);
344
+ }
345
+ }));
346
+ }
347
+ async LoadComponents() {
348
+ var t, o;
349
+ const a = e.listClass("COMPONENT");
350
+ const s = [];
351
+ a.forEach((async t => {
352
+ var o;
353
+ t.id = ((o = t.id) !== null && o !== void 0 ? o : "").replace("COMPONENT:", "");
354
+ if (f.isClass(t.target)) {
355
+ e.reg(t.id, t.target, {
356
+ scope: "Singleton",
357
+ type: "COMPONENT",
358
+ args: []
554
359
  });
555
- // load plugin config
556
- let pluginsConf = this.app.config(undefined, "plugin");
557
- if (Helper.isEmpty(pluginsConf)) {
558
- pluginsConf = { config: {}, list: [] };
360
+ if (t.id && t.id.endsWith("Plugin")) {
361
+ const o = e.getInsByClass(t.target);
362
+ if (!l(o)) throw Error(`The plugin ${t.id} must implements interface 'IPlugin'.`);
363
+ s.push(t.id);
559
364
  }
560
- const pluginConfList = (_a = pluginsConf.list) !== null && _a !== void 0 ? _a : [];
561
- // load plugin list
562
- for (const key of pluginConfList) {
563
- const handle = IOC.get(key, "COMPONENT");
564
- if (!handle) {
565
- throw Error(`Plugin ${key} load error.`);
566
- }
567
- if (!Helper.isFunction(handle.run)) {
568
- throw Error(`Plugin ${key} must implements interface 'IPlugin'.`);
569
- }
570
- if (pluginsConf.config[key] === false) {
571
- Logger.Warn(`Plugin ${key} already loaded but not effective.`);
572
- continue;
573
- }
574
- // sync exec
575
- await handle.run((_b = pluginsConf.config[key]) !== null && _b !== void 0 ? _b : {}, this.app);
365
+ if (t.id && t.id.endsWith("Aspect")) {
366
+ const o = e.getInsByClass(t.target);
367
+ if (!c(o)) throw Error(`The aspect ${t.id} must implements interface 'IAspect'.`);
576
368
  }
369
+ }
370
+ }));
371
+ let r = this.app.config(void 0, "plugin");
372
+ if (f.isEmpty(r)) r = {
373
+ config: {},
374
+ list: []
375
+ };
376
+ const i = (t = r.list) !== null && t !== void 0 ? t : [];
377
+ for (const t of i) {
378
+ const a = e.get(t, "COMPONENT");
379
+ if (!a) throw Error(`Plugin ${t} load error.`);
380
+ if (!f.isFunction(a.run)) throw Error(`Plugin ${t} must implements interface 'IPlugin'.`);
381
+ if (r.config[t] === !1) {
382
+ w.Warn(`Plugin ${t} already loaded but not effective.`);
383
+ continue;
384
+ }
385
+ await a.run((o = r.config[t]) !== null && o !== void 0 ? o : {}, this.app);
577
386
  }
578
- /**
579
- * @description: load router
580
- * @param {string} ctls
581
- * @return {*}
582
- */
583
- async LoadRouter(ctls) {
584
- // load router
585
- await this.app.router.LoadRouter(this.app, ctls);
586
- }
387
+ }
388
+ async LoadRouter(t) {
389
+ await this.app.router.LoadRouter(this.app, t);
390
+ }
587
391
  }
588
392
 
589
393
  /*
@@ -594,192 +398,87 @@ class Loader {
594
398
  * @LastEditTime: 2025-01-14 16:11:21
595
399
  * @License: BSD (3-Clause)
596
400
  * @Copyright (c): <richenlin(at)gmail.com>
597
- */
598
- /**
599
- * Bootstrap application decorator
600
- *
601
- * @export
602
- * @param {Function} [bootFunc]
603
- * @returns {ClassDecorator}
604
- */
605
- function Bootstrap(bootFunc) {
606
- return function (target) {
607
- if (!(target.prototype instanceof Koatty)) {
608
- throw new Error(`class does not inherit from Koatty`);
609
- }
610
- executeBootstrap(target, bootFunc);
611
- };
401
+ */ function _(t) {
402
+ return function(e) {
403
+ if (!(e.prototype instanceof p)) throw new Error(`class does not inherit from Koatty`);
404
+ b(e, t);
405
+ };
612
406
  }
613
- /**
614
- * Actively perform dependency injection
615
- * Parse the decorator, return the instantiated app.
616
- * @export ExecBootStrap
617
- * @param {Function} [bootFunc] callback function
618
- * @returns
619
- */
620
- function ExecBootStrap(bootFunc) {
621
- return async (target) => {
622
- if (!(target.prototype instanceof Koatty)) {
623
- throw new Error(`class ${target.name} does not inherit from Koatty`);
624
- }
625
- return await executeBootstrap(target, bootFunc, true);
626
- };
407
+
408
+ function O(t) {
409
+ return async e => {
410
+ if (!(e.prototype instanceof p)) throw new Error(`class ${e.name} does not inherit from Koatty`);
411
+ return await b(e, t, !0);
412
+ };
627
413
  }
628
- /**
629
- * Define project scan path
630
- *
631
- * @export
632
- * @param {(string | string[])} [scanPath]
633
- * @returns {ClassDecorator}
634
- */
635
- function ComponentScan(scanPath) {
636
- return (target) => {
637
- if (!(target.prototype instanceof Koatty)) {
638
- throw new Error(`class does not inherit from Koatty`);
639
- }
640
- scanPath = scanPath !== null && scanPath !== void 0 ? scanPath : '';
641
- IOC.saveClassMetadata(TAGGED_CLS, COMPONENT_SCAN, scanPath, target);
642
- };
414
+
415
+ function S(t) {
416
+ return a => {
417
+ if (!(a.prototype instanceof p)) throw new Error(`class does not inherit from Koatty`);
418
+ t = t !== null && t !== void 0 ? t : "";
419
+ e.saveClassMetadata(o, R, t, a);
420
+ };
643
421
  }
644
- /**
645
- * Define project configuration scan path
646
- *
647
- * @export
648
- * @param {(string | string[])} [scanPath]
649
- * @returns {ClassDecorator}
650
- */
651
- function ConfigurationScan(scanPath) {
652
- return (target) => {
653
- if (!(target.prototype instanceof Koatty)) {
654
- throw new Error(`class does not inherit from Koatty`);
655
- }
656
- scanPath = scanPath !== null && scanPath !== void 0 ? scanPath : '';
657
- IOC.saveClassMetadata(TAGGED_CLS, CONFIGURATION_SCAN, scanPath, target);
658
- };
422
+
423
+ function I(t) {
424
+ return a => {
425
+ if (!(a.prototype instanceof p)) throw new Error(`class does not inherit from Koatty`);
426
+ t = t !== null && t !== void 0 ? t : "";
427
+ e.saveClassMetadata(o, k, t, a);
428
+ };
659
429
  }
660
- /**
661
- * @description: bind App event hook func
662
- * example:
663
- * export function TestDecorator(): ClassDecorator {
664
- * return (target: Function) => {
665
- * BindEventHook(AppEvent.appBoot, (app: KoattyApplication) => {
666
- * // todo
667
- * return Promise.resolve();
668
- * }, target)
669
- * }
670
- * }
671
- * @param {AppEvent} eventName
672
- * @param {EventHookFunc} eventFunc
673
- * @param {any} target
674
- * @return {*}
675
- */
676
- function BindEventHook(eventName, eventFunc, target) {
677
- IOC.attachClassMetadata(TAGGED_CLS, eventName, eventFunc, target);
430
+
431
+ function K(t, a, s) {
432
+ e.attachClassMetadata(o, t, a, s);
678
433
  }
679
- /**
680
- * execute bootstrap
681
- *
682
- * @param {*} target
683
- * @param {Function} bootFunc
684
- * @param {boolean} [isInitiative=false] Whether to actively execute app instantiation,
685
- * mainly for unittest scenarios, you need to actively obtain app instances
686
- * @returns {Promise<void>}
687
- */
688
- const executeBootstrap = async function (target, bootFunc, isInitiative = false) {
689
- // checked runtime
690
- checkRuntime();
691
- // unittest running environment
692
- const isUTRuntime = checkUTRuntime();
693
- if (!isInitiative && isUTRuntime) {
694
- return;
695
- }
696
- const app = Reflect.construct(target, []);
697
- // unittest does not print startup logs
698
- if (isUTRuntime) {
699
- app.silent = true;
700
- Logger.enable(false);
701
- }
702
- try {
703
- if (!app.silent)
704
- Logger.Log("Koatty", LOGO);
705
- if (!(app instanceof Koatty)) {
706
- throw new Error(`class ${target.name} does not inherit from Koatty`);
707
- }
708
- // Initialize env
709
- Loader.initialize(app);
710
- // exec bootFunc
711
- if (Helper.isFunction(bootFunc)) {
712
- Logger.Log('Koatty', '', 'Execute bootFunc ...');
713
- await bootFunc(app);
714
- }
715
- // Set IOC.app
716
- IOC.setApp(app);
717
- // Check all bean
718
- Logger.Log('Koatty', '', 'ComponentScan ...');
719
- Loader.CheckAllComponents(app, target);
720
- // Load App event hooks
721
- Loader.LoadAppEventHooks(app, target);
722
- Logger.Log('Koatty', '', 'Emit App Boot ...');
723
- await asyncEvent(app, "appBoot" /* AppEvent.appBoot */);
724
- // Load All components
725
- await Loader.LoadAllComponents(app, target);
726
- // Emit app ready event
727
- Logger.Log('Koatty', '', 'Emit App Ready ...');
728
- await asyncEvent(app, "appReady" /* AppEvent.appReady */);
729
- if (!isUTRuntime) {
730
- // Start Server
731
- app.listen(listenCallback);
732
- }
733
- return app;
734
- }
735
- catch (err) {
736
- Logger.Error(err);
737
- process.exit();
738
- }
739
- };
740
- /**
741
- * Listening callback function
742
- *
743
- * @param {Koatty} app
744
- * @returns {*}
745
- */
746
- const listenCallback = (app) => {
747
- let servers = [];
748
- if (!Array.isArray(app.server)) {
749
- servers = [app.server];
750
- }
751
- else {
752
- servers = app.server;
434
+
435
+ const b = async function(t, o, a = !1) {
436
+ M();
437
+ const s = $();
438
+ if (!a && s) return;
439
+ const r = Reflect.construct(t, []);
440
+ if (s) {
441
+ r.silent = !0;
442
+ w.enable(!1);
443
+ }
444
+ try {
445
+ if (!r.silent) w.Log("Koatty", T);
446
+ if (!(r instanceof p)) throw new Error(`class ${t.name} does not inherit from Koatty`);
447
+ Loader.initialize(r);
448
+ if (f.isFunction(o)) {
449
+ w.Log("Koatty", "", "Execute bootFunc ...");
450
+ await o(r);
753
451
  }
754
- Logger.Log('Koatty', '', '====================================');
755
- Logger.Log("Koatty", "", `Nodejs Version: ${process.version}`);
756
- Logger.Log("Koatty", "", `Koatty Version: v${KOATTY_VERSION}`);
757
- Logger.Log("Koatty", "", `App Environment: ${app.env}`);
758
- servers.forEach(s => {
759
- Logger.Log('Koatty', '', `Server: ${(s.options.protocol).toUpperCase()} running at ${s.options.protocol === "http2" ?
760
- "https" : s.options.protocol}://${s.options.hostname || '127.0.0.1'}:${s.options.port}/`);
761
- });
762
- Logger.Log("Koatty", "", "====================================");
763
- if (app.appDebug)
764
- Logger.Warn(`Running in debug mode.`);
765
- // Set Logger
766
- Loader.SetLogger(app);
452
+ e.setApp(r);
453
+ w.Log("Koatty", "", "ComponentScan ...");
454
+ Loader.CheckAllComponents(r, t);
455
+ Loader.LoadAppEventHooks(r, t);
456
+ w.Log("Koatty", "", "Emit App Boot ...");
457
+ await d(r, "appBoot");
458
+ await Loader.LoadAllComponents(r, t);
459
+ w.Log("Koatty", "", "Emit App Ready ...");
460
+ await d(r, "appReady");
461
+ if (!s) r.listen(N);
462
+ return r;
463
+ } catch (t) {
464
+ w.Error(t);
465
+ process.exit();
466
+ }
767
467
  };
768
- /**
769
- * Execute event as async
770
- *
771
- * @param {Koatty} event
772
- * @param {string} eventName
773
- */
774
- const asyncEvent = async function (event, eventName) {
775
- const ls = event.listeners(eventName);
776
- // eslint-disable-next-line no-restricted-syntax
777
- for await (const func of ls) {
778
- if (Helper.isFunction(func)) {
779
- func();
780
- }
781
- }
782
- return event.removeAllListeners(eventName);
468
+
469
+ const N = t => {
470
+ let e = [];
471
+ if (!Array.isArray(t.server)) e = [ t.server ]; else e = t.server;
472
+ w.Log("Koatty", "", "====================================");
473
+ w.Log("Koatty", "", `Nodejs Version: ${process.version}`);
474
+ w.Log("Koatty", "", `Koatty Version: v${E}`);
475
+ w.Log("Koatty", "", `App Environment: ${t.env}`);
476
+ e.forEach((t => {
477
+ w.Log("Koatty", "", `Server: ${t.options.protocol.toUpperCase()} running at ${t.options.protocol === "http2" ? "https" : t.options.protocol}://${t.options.hostname || "127.0.0.1"}:${t.options.port}/`);
478
+ }));
479
+ w.Log("Koatty", "", "====================================");
480
+ if (t.appDebug) w.Warn(`Running in debug mode.`);
481
+ Loader.SetLogger(t);
783
482
  };
784
483
 
785
- export { BindEventHook, Bootstrap, ComponentScan, ConfigurationScan, ExecBootStrap, Logger };
484
+ export { K as BindEventHook, _ as Bootstrap, S as ComponentScan, I as ConfigurationScan, O as ExecBootStrap, w as Logger };