koatty 3.12.0 → 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-03-15 23:04:17
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.12.0";
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,19 +112,11 @@ 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:
@@ -169,423 +125,269 @@ https://github.com/koatty
169
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 protocol = app.config('protocol');
378
- const serveOpts = {
379
- hostname: app.config('app_host'),
380
- port: app.config('app_port'),
381
- protocol: protocol,
382
- };
383
- Helper.define(app, "server", NewServe(app, serveOpts));
384
- // Create router
385
- const routerOpts = (_a = app.config(undefined, 'router')) !== null && _a !== void 0 ? _a : {};
386
- Helper.define(app, "router", NewRouter(app, { protocol, ...routerOpts }));
387
- // Load Components
388
- Logger.Log('Koatty', '', 'Load Components ...');
389
- await loader.LoadComponents();
390
- // Load Middleware
391
- Logger.Log('Koatty', '', 'Load Middlewares ...');
392
- await loader.LoadMiddlewares();
393
- // Load Services
394
- Logger.Log('Koatty', '', 'Load Services ...');
395
- await loader.LoadServices();
396
- // Load Controllers
397
- Logger.Log('Koatty', '', 'Load Controllers ...');
398
- const controllers = await loader.LoadControllers();
399
- // Load Routers
400
- Logger.Log('Koatty', '', 'Load Routers ...');
401
- 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
+ }
402
219
  }
403
- /**
404
- * Load configuration
405
- *
406
- * @param {string[]} [loadPath]
407
- * @memberof Loader
408
- */
409
- LoadConfigs(loadPath) {
410
- const frameConfig = {};
411
- // Logger.Debug(`Load configuration path: ${app.thinkPath}/config`);
412
- Load(["./config"], this.app.koattyPath, function (name, path, exp) {
413
- 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: []
414
276
  });
415
- if (Helper.isArray(loadPath)) {
416
- loadPath = loadPath.length > 0 ? loadPath : ["./config"];
417
- }
418
- let appConfig = LoadConfigs(loadPath, this.app.appPath);
419
- appConfig = Helper.extend(frameConfig, appConfig, true);
420
- 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);
421
300
  }
422
- /**
423
- * Load middlewares
424
- * [async]
425
- * @memberof Loader
426
- */
427
- async LoadMiddlewares() {
428
- var _a;
429
- let middlewareConf = this.app.config(undefined, "middleware");
430
- if (Helper.isEmpty(middlewareConf)) {
431
- middlewareConf = { config: {}, list: [] };
432
- }
433
- //Mount default middleware
434
- // Load(loadPath || ["./middleware"], app.koattyPath);
435
- //Mount application middleware
436
- // const middleware: any = {};
437
- const appMiddleware = (_a = IOC.listClass("MIDDLEWARE")) !== null && _a !== void 0 ? _a : [];
438
- appMiddleware.forEach((item) => {
439
- var _a;
440
- item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("MIDDLEWARE:", "");
441
- if (item.id && Helper.isClass(item.target)) {
442
- IOC.reg(item.id, item.target, { scope: "Prototype", type: "MIDDLEWARE", args: [] });
443
- const ctl = IOC.getInsByClass(item.target);
444
- if (!implementsMiddlewareInterface(ctl)) {
445
- throw Error(`The middleware ${item.id} must implements interface 'IMiddleware'.`);
446
- }
447
- }
448
- });
449
- const middlewareConfList = middlewareConf.list || [];
450
- //de-duplication
451
- const appMList = new Set([]);
452
- middlewareConfList.forEach((item) => {
453
- appMList.add(item);
454
- });
455
- //Automatically call middleware
456
- const middlewareConfig = middlewareConf.config || {};
457
- for (const key of appMList) {
458
- const handle = IOC.get(key, "MIDDLEWARE");
459
- if (!handle) {
460
- throw Error(`Middleware ${key} load error.`);
461
- }
462
- if (!Helper.isFunction(handle.run)) {
463
- throw Error(`The middleware ${key} must implements interface 'IMiddleware'.`);
464
- }
465
- // if (middlewareConfig[key] === false) {
466
- // Logger.Warn(`The middleware ${key} has been loaded but not executed.`);
467
- // continue;
468
- // }
469
- Logger.Debug(`Load middleware: ${key}`);
470
- const middlewareOpt = middlewareConfig[key] || {};
471
- const result = await handle.run(middlewareOpt, this.app);
472
- if (Helper.isFunction(result)) {
473
- if (result.length < 3) {
474
- this.app.use(result);
475
- }
476
- else {
477
- this.app.useExp(result);
478
- }
479
- }
480
- }
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);
481
308
  }
482
- /**
483
- * Load controllers
484
- *
485
- * @memberof Loader
486
- */
487
- async LoadControllers() {
488
- const controllerList = IOC.listClass("CONTROLLER");
489
- const controllers = [];
490
- controllerList.forEach((item) => {
491
- var _a;
492
- item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("CONTROLLER:", "");
493
- if (item.id && Helper.isClass(item.target)) {
494
- Logger.Debug(`Load controller: ${item.id}`);
495
- // registering to IOC
496
- IOC.reg(item.id, item.target, { scope: "Prototype", type: "CONTROLLER", args: [] });
497
- const ctl = IOC.getInsByClass(item.target);
498
- if (!implementsControllerInterface(ctl)) {
499
- throw Error(`The controller ${item.id} must implements interface 'IController'.`);
500
- }
501
- controllers.push(item.id);
502
- }
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: []
503
322
  });
504
- return controllers;
505
- }
506
- /**
507
- * Load services
508
- *
509
- * @memberof Loader
510
- */
511
- async LoadServices() {
512
- const serviceList = IOC.listClass("SERVICE");
513
- serviceList.forEach((item) => {
514
- var _a;
515
- item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("SERVICE:", "");
516
- if (item.id && Helper.isClass(item.target)) {
517
- Logger.Debug(`Load service: ${item.id}`);
518
- // registering to IOC
519
- IOC.reg(item.id, item.target, { scope: "Singleton", type: "SERVICE", args: [] });
520
- const ctl = IOC.getInsByClass(item.target);
521
- if (!implementsServiceInterface(ctl)) {
522
- throw Error(`The service ${item.id} must implements interface 'IService'.`);
523
- }
524
- }
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: []
525
341
  });
526
- }
527
- /**
528
- * Load components
529
- *
530
- * @memberof Loader
531
- */
532
- async LoadComponents() {
533
- var _a, _b;
534
- const componentList = IOC.listClass("COMPONENT");
535
- const pluginList = [];
536
- componentList.forEach(async (item) => {
537
- var _a;
538
- item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("COMPONENT:", "");
539
- if (Helper.isClass(item.target)) {
540
- // registering to IOC
541
- IOC.reg(item.id, item.target, { scope: "Singleton", type: "COMPONENT", args: [] });
542
- if (item.id && (item.id).endsWith("Plugin")) {
543
- const ctl = IOC.getInsByClass(item.target);
544
- if (!implementsPluginInterface(ctl)) {
545
- throw Error(`The plugin ${item.id} must implements interface 'IPlugin'.`);
546
- }
547
- pluginList.push(item.id);
548
- }
549
- if (item.id && (item.id).endsWith("Aspect")) {
550
- const ctl = IOC.getInsByClass(item.target);
551
- if (!implementsAspectInterface(ctl)) {
552
- throw Error(`The aspect ${item.id} must implements interface 'IAspect'.`);
553
- }
554
- }
555
- }
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: []
556
359
  });
557
- // load plugin config
558
- let pluginsConf = this.app.config(undefined, "plugin");
559
- if (Helper.isEmpty(pluginsConf)) {
560
- 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);
561
364
  }
562
- const pluginConfList = (_a = pluginsConf.list) !== null && _a !== void 0 ? _a : [];
563
- // load plugin list
564
- for (const key of pluginConfList) {
565
- const handle = IOC.get(key, "COMPONENT");
566
- if (!handle) {
567
- throw Error(`Plugin ${key} load error.`);
568
- }
569
- if (!Helper.isFunction(handle.run)) {
570
- throw Error(`Plugin ${key} must implements interface 'IPlugin'.`);
571
- }
572
- if (pluginsConf.config[key] === false) {
573
- Logger.Warn(`Plugin ${key} already loaded but not effective.`);
574
- continue;
575
- }
576
- // sync exec
577
- 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'.`);
578
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);
579
386
  }
580
- /**
581
- * @description: load router
582
- * @param {string} ctls
583
- * @return {*}
584
- */
585
- async LoadRouter(ctls) {
586
- // load router
587
- await this.app.router.LoadRouter(this.app, ctls);
588
- }
387
+ }
388
+ async LoadRouter(t) {
389
+ await this.app.router.LoadRouter(this.app, t);
390
+ }
589
391
  }
590
392
 
591
393
  /*
@@ -596,192 +398,87 @@ class Loader {
596
398
  * @LastEditTime: 2025-01-14 16:11:21
597
399
  * @License: BSD (3-Clause)
598
400
  * @Copyright (c): <richenlin(at)gmail.com>
599
- */
600
- /**
601
- * Bootstrap application decorator
602
- *
603
- * @export
604
- * @param {Function} [bootFunc]
605
- * @returns {ClassDecorator}
606
- */
607
- function Bootstrap(bootFunc) {
608
- return function (target) {
609
- if (!(target.prototype instanceof Koatty)) {
610
- throw new Error(`class does not inherit from Koatty`);
611
- }
612
- executeBootstrap(target, bootFunc);
613
- };
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
+ };
614
406
  }
615
- /**
616
- * Actively perform dependency injection
617
- * Parse the decorator, return the instantiated app.
618
- * @export ExecBootStrap
619
- * @param {Function} [bootFunc] callback function
620
- * @returns
621
- */
622
- function ExecBootStrap(bootFunc) {
623
- return async (target) => {
624
- if (!(target.prototype instanceof Koatty)) {
625
- throw new Error(`class ${target.name} does not inherit from Koatty`);
626
- }
627
- return await executeBootstrap(target, bootFunc, true);
628
- };
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
+ };
629
413
  }
630
- /**
631
- * Define project scan path
632
- *
633
- * @export
634
- * @param {(string | string[])} [scanPath]
635
- * @returns {ClassDecorator}
636
- */
637
- function ComponentScan(scanPath) {
638
- return (target) => {
639
- if (!(target.prototype instanceof Koatty)) {
640
- throw new Error(`class does not inherit from Koatty`);
641
- }
642
- scanPath = scanPath !== null && scanPath !== void 0 ? scanPath : '';
643
- IOC.saveClassMetadata(TAGGED_CLS, COMPONENT_SCAN, scanPath, target);
644
- };
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
+ };
645
421
  }
646
- /**
647
- * Define project configuration scan path
648
- *
649
- * @export
650
- * @param {(string | string[])} [scanPath]
651
- * @returns {ClassDecorator}
652
- */
653
- function ConfigurationScan(scanPath) {
654
- return (target) => {
655
- if (!(target.prototype instanceof Koatty)) {
656
- throw new Error(`class does not inherit from Koatty`);
657
- }
658
- scanPath = scanPath !== null && scanPath !== void 0 ? scanPath : '';
659
- IOC.saveClassMetadata(TAGGED_CLS, CONFIGURATION_SCAN, scanPath, target);
660
- };
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
+ };
661
429
  }
662
- /**
663
- * @description: bind App event hook func
664
- * example:
665
- * export function TestDecorator(): ClassDecorator {
666
- * return (target: Function) => {
667
- * BindEventHook(AppEvent.appBoot, (app: KoattyApplication) => {
668
- * // todo
669
- * return Promise.resolve();
670
- * }, target)
671
- * }
672
- * }
673
- * @param {AppEvent} eventName
674
- * @param {EventHookFunc} eventFunc
675
- * @param {any} target
676
- * @return {*}
677
- */
678
- function BindEventHook(eventName, eventFunc, target) {
679
- IOC.attachClassMetadata(TAGGED_CLS, eventName, eventFunc, target);
430
+
431
+ function K(t, a, s) {
432
+ e.attachClassMetadata(o, t, a, s);
680
433
  }
681
- /**
682
- * execute bootstrap
683
- *
684
- * @param {*} target
685
- * @param {Function} bootFunc
686
- * @param {boolean} [isInitiative=false] Whether to actively execute app instantiation,
687
- * mainly for unittest scenarios, you need to actively obtain app instances
688
- * @returns {Promise<void>}
689
- */
690
- const executeBootstrap = async function (target, bootFunc, isInitiative = false) {
691
- // checked runtime
692
- checkRuntime();
693
- // unittest running environment
694
- const isUTRuntime = checkUTRuntime();
695
- if (!isInitiative && isUTRuntime) {
696
- return;
697
- }
698
- const app = Reflect.construct(target, []);
699
- // unittest does not print startup logs
700
- if (isUTRuntime) {
701
- app.silent = true;
702
- Logger.enable(false);
703
- }
704
- try {
705
- if (!app.silent)
706
- Logger.Log("Koatty", LOGO);
707
- if (!(app instanceof Koatty)) {
708
- throw new Error(`class ${target.name} does not inherit from Koatty`);
709
- }
710
- // Initialize env
711
- Loader.initialize(app);
712
- // exec bootFunc
713
- if (Helper.isFunction(bootFunc)) {
714
- Logger.Log('Koatty', '', 'Execute bootFunc ...');
715
- await bootFunc(app);
716
- }
717
- // Set IOC.app
718
- IOC.setApp(app);
719
- // Check all bean
720
- Logger.Log('Koatty', '', 'ComponentScan ...');
721
- Loader.CheckAllComponents(app, target);
722
- // Load App event hooks
723
- Loader.LoadAppEventHooks(app, target);
724
- Logger.Log('Koatty', '', 'Emit App Boot ...');
725
- await asyncEvent(app, "appBoot" /* AppEvent.appBoot */);
726
- // Load All components
727
- await Loader.LoadAllComponents(app, target);
728
- // Emit app ready event
729
- Logger.Log('Koatty', '', 'Emit App Ready ...');
730
- await asyncEvent(app, "appReady" /* AppEvent.appReady */);
731
- if (!isUTRuntime) {
732
- // Start Server
733
- app.listen(listenCallback);
734
- }
735
- return app;
736
- }
737
- catch (err) {
738
- Logger.Error(err);
739
- process.exit();
740
- }
741
- };
742
- /**
743
- * Listening callback function
744
- *
745
- * @param {Koatty} app
746
- * @returns {*}
747
- */
748
- const listenCallback = (app) => {
749
- let servers = [];
750
- if (!Array.isArray(app.server)) {
751
- servers = [app.server];
752
- }
753
- else {
754
- 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);
755
451
  }
756
- Logger.Log('Koatty', '', '====================================');
757
- Logger.Log("Koatty", "", `Nodejs Version: ${process.version}`);
758
- Logger.Log("Koatty", "", `Koatty Version: v${KOATTY_VERSION}`);
759
- Logger.Log("Koatty", "", `App Environment: ${app.env}`);
760
- servers.forEach(s => {
761
- Logger.Log('Koatty', '', `Server: ${(s.options.protocol).toUpperCase()} running at ${s.options.protocol === "http2" ?
762
- "https" : s.options.protocol}://${s.options.hostname || '127.0.0.1'}:${s.options.port}/`);
763
- });
764
- Logger.Log("Koatty", "", "====================================");
765
- if (app.appDebug)
766
- Logger.Warn(`Running in debug mode.`);
767
- // Set Logger
768
- 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
+ }
769
467
  };
770
- /**
771
- * Execute event as async
772
- *
773
- * @param {Koatty} event
774
- * @param {string} eventName
775
- */
776
- const asyncEvent = async function (event, eventName) {
777
- const ls = event.listeners(eventName);
778
- // eslint-disable-next-line no-restricted-syntax
779
- for await (const func of ls) {
780
- if (Helper.isFunction(func)) {
781
- func();
782
- }
783
- }
784
- 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);
785
482
  };
786
483
 
787
- 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 };