@eggjs/core 7.0.0-beta.18 → 7.0.0-beta.20

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.
@@ -1,1184 +0,0 @@
1
- import utils_default from "../utils/index.js";
2
- import { Timing } from "../utils/timing.js";
3
- import { CaseStyle, FULLPATH, FileLoader } from "./file_loader.js";
4
- import { ContextLoader } from "./context_loader.js";
5
- import { sequencify } from "../utils/sequencify.js";
6
- import { debuglog, inspect } from "node:util";
7
- import path from "node:path";
8
- import fs from "node:fs";
9
- import { isESM, isSupportTypeScript } from "@eggjs/utils";
10
- import assert from "node:assert";
11
- import { Application, Context, Request, Response } from "@eggjs/koa";
12
- import { isAsyncFunction, isClass, isGeneratorFunction, isObject, isPromise } from "is-type-of";
13
- import { homedir } from "node-homedir";
14
- import { exists, getParamNames, readJSON, readJSONSync } from "utility";
15
- import { extend } from "@eggjs/extend2";
16
- import { register } from "tsconfig-paths";
17
- import { pathMatching } from "egg-path-matching";
18
- import { diff, now } from "performance-ms";
19
-
20
- //#region src/loader/egg_loader.ts
21
- const debug = debuglog("egg/core/loader/egg_loader");
22
- const originalPrototypes = {
23
- request: Request.prototype,
24
- response: Response.prototype,
25
- context: Context.prototype,
26
- application: Application.prototype
27
- };
28
- var EggLoader = class {
29
- #requiredCount = 0;
30
- options;
31
- timing;
32
- pkg;
33
- eggPaths;
34
- serverEnv;
35
- serverScope;
36
- appInfo;
37
- dirs;
38
- /**
39
- * @class
40
- * @param {Object} options - options
41
- * @param {String} options.baseDir - the directory of application
42
- * @param {EggCore} options.app - Application instance
43
- * @param {Logger} options.logger - logger
44
- * @param {Object} [options.plugins] - custom plugins
45
- * @since 1.0.0
46
- */
47
- constructor(options) {
48
- this.options = options;
49
- assert(fs.existsSync(this.options.baseDir), `${this.options.baseDir} not exists`);
50
- assert(this.options.app, "options.app is required");
51
- assert(this.options.logger, "options.logger is required");
52
- this.timing = this.app.timing || new Timing();
53
- /**
54
- * @member {Object} EggLoader#pkg
55
- * @see {@link AppInfo#pkg}
56
- * @since 1.0.0
57
- */
58
- this.pkg = readJSONSync(path.join(this.options.baseDir, "package.json"));
59
- if (process.env.EGG_TYPESCRIPT === "true" || this.pkg.egg && this.pkg.egg.typescript) {
60
- const tsConfigFile = path.join(this.options.baseDir, "tsconfig.json");
61
- if (fs.existsSync(tsConfigFile)) register({ cwd: this.options.baseDir });
62
- else this.logger.info("[@eggjs/core/egg_loader] skip register \"tsconfig-paths\" because tsconfig.json not exists at %s", tsConfigFile);
63
- }
64
- /**
65
- * All framework directories.
66
- *
67
- * You can extend Application of egg, the entry point is options.app,
68
- *
69
- * loader will find all directories from the prototype of Application,
70
- * you should define `Symbol.for('egg#eggPath')` property.
71
- *
72
- * ```ts
73
- * // src/example.ts
74
- * import { Application } from 'egg';
75
- * class ExampleApplication extends Application {
76
- * get [Symbol.for('egg#eggPath')]() {
77
- * return baseDir;
78
- * }
79
- * }
80
- * ```
81
- * @member {Array} EggLoader#eggPaths
82
- * @see EggLoader#getEggPaths
83
- * @since 1.0.0
84
- */
85
- this.eggPaths = this.getEggPaths();
86
- debug("Loaded eggPaths %j", this.eggPaths);
87
- /**
88
- * @member {String} EggLoader#serverEnv
89
- * @see AppInfo#env
90
- * @since 1.0.0
91
- */
92
- this.serverEnv = this.getServerEnv();
93
- debug("Loaded serverEnv %j", this.serverEnv);
94
- /**
95
- * @member {String} EggLoader#serverScope
96
- * @see AppInfo#serverScope
97
- */
98
- this.serverScope = options.serverScope ?? this.getServerScope();
99
- /**
100
- * @member {AppInfo} EggLoader#appInfo
101
- * @since 1.0.0
102
- */
103
- this.appInfo = this.getAppInfo();
104
- }
105
- get app() {
106
- return this.options.app;
107
- }
108
- get lifecycle() {
109
- return this.app.lifecycle;
110
- }
111
- get logger() {
112
- return this.options.logger;
113
- }
114
- /**
115
- * Get {@link AppInfo#env}
116
- * @returns {String} env
117
- * @see AppInfo#env
118
- * @private
119
- * @since 1.0.0
120
- */
121
- getServerEnv() {
122
- let serverEnv = this.options.env;
123
- const envPath = path.join(this.options.baseDir, "config/env");
124
- if (!serverEnv && fs.existsSync(envPath)) serverEnv = fs.readFileSync(envPath, "utf8").trim();
125
- if (!serverEnv && process.env.EGG_SERVER_ENV) serverEnv = process.env.EGG_SERVER_ENV;
126
- if (serverEnv) serverEnv = serverEnv.trim();
127
- else if (process.env.NODE_ENV === "test") serverEnv = "unittest";
128
- else if (process.env.NODE_ENV === "production") serverEnv = "prod";
129
- else serverEnv = "local";
130
- return serverEnv;
131
- }
132
- /**
133
- * Get {@link AppInfo#scope}
134
- * @returns {String} serverScope
135
- * @private
136
- */
137
- getServerScope() {
138
- return process.env.EGG_SERVER_SCOPE ?? "";
139
- }
140
- /**
141
- * Get {@link AppInfo#name}
142
- * @returns {String} appname
143
- * @private
144
- * @since 1.0.0
145
- */
146
- getAppname() {
147
- if (this.pkg.name) {
148
- debug("Loaded appname(%s) from package.json", this.pkg.name);
149
- return this.pkg.name;
150
- }
151
- const pkg = path.join(this.options.baseDir, "package.json");
152
- throw new Error(`name is required from ${pkg}`);
153
- }
154
- /**
155
- * Get home directory
156
- * @returns {String} home directory
157
- * @since 3.4.0
158
- */
159
- getHomedir() {
160
- return process.env.EGG_HOME || homedir() || "/home/admin";
161
- }
162
- /**
163
- * Get app info
164
- * @returns {AppInfo} appInfo
165
- * @since 1.0.0
166
- */
167
- getAppInfo() {
168
- const env = this.serverEnv;
169
- const scope = this.serverScope;
170
- const home = this.getHomedir();
171
- const baseDir = this.options.baseDir;
172
- /**
173
- * Meta information of the application
174
- * @class AppInfo
175
- */
176
- return {
177
- name: this.getAppname(),
178
- baseDir,
179
- env,
180
- scope,
181
- HOME: home,
182
- pkg: this.pkg,
183
- root: env === "local" || env === "unittest" ? baseDir : home
184
- };
185
- }
186
- /**
187
- * Get {@link EggLoader#eggPaths}
188
- * @returns {Array} framework directories
189
- * @see {@link EggLoader#eggPaths}
190
- * @private
191
- * @since 1.0.0
192
- */
193
- getEggPaths() {
194
- const EggCore = this.options.EggCoreClass;
195
- const eggPaths = [];
196
- let proto = this.app;
197
- while (proto) {
198
- proto = Object.getPrototypeOf(proto);
199
- if (proto === Object.prototype || proto === EggCore?.prototype) break;
200
- const eggPath = Reflect.get(proto, Symbol.for("egg#eggPath"));
201
- if (!eggPath) continue;
202
- assert(typeof eggPath === "string", "Symbol.for('egg#eggPath') should be string");
203
- assert(fs.existsSync(eggPath), `${eggPath} not exists`);
204
- const realpath = fs.realpathSync(eggPath);
205
- if (!eggPaths.includes(realpath)) eggPaths.unshift(realpath);
206
- }
207
- return eggPaths;
208
- }
209
- /** start Plugin loader */
210
- lookupDirs;
211
- eggPlugins;
212
- appPlugins;
213
- customPlugins;
214
- allPlugins;
215
- orderPlugins;
216
- /** enable plugins */
217
- plugins;
218
- /**
219
- * Load config/plugin.js from {EggLoader#loadUnits}
220
- *
221
- * plugin.js is written below
222
- *
223
- * ```js
224
- * {
225
- * 'xxx-client': {
226
- * enable: true,
227
- * package: 'xxx-client',
228
- * dep: [],
229
- * env: [],
230
- * },
231
- * // short hand
232
- * 'rds': false,
233
- * 'depd': {
234
- * enable: true,
235
- * path: 'path/to/depd'
236
- * }
237
- * }
238
- * ```
239
- *
240
- * If the plugin has path, Loader will find the module from it.
241
- *
242
- * Otherwise Loader will lookup follow the order by packageName
243
- *
244
- * 1. $APP_BASE/node_modules/${package}
245
- * 2. $EGG_BASE/node_modules/${package}
246
- *
247
- * You can call `loader.plugins` that retrieve enabled plugins.
248
- *
249
- * ```js
250
- * loader.plugins['xxx-client'] = {
251
- * name: 'xxx-client', // the plugin name, it can be used in `dep`
252
- * package: 'xxx-client', // the package name of plugin
253
- * enable: true, // whether enabled
254
- * path: 'path/to/xxx-client', // the directory of the plugin package
255
- * dep: [], // the dependent plugins, you can use the plugin name
256
- * env: [ 'local', 'unittest' ], // specify the serverEnv that only enable the plugin in it
257
- * }
258
- * ```
259
- *
260
- * `loader.allPlugins` can be used when retrieve all plugins.
261
- * @function EggLoader#loadPlugin
262
- * @since 1.0.0
263
- */
264
- async loadPlugin() {
265
- this.timing.start("Load Plugin");
266
- this.lookupDirs = this.getLookupDirs();
267
- this.allPlugins = {};
268
- this.eggPlugins = await this.loadEggPlugins();
269
- this.appPlugins = await this.loadAppPlugins();
270
- this.customPlugins = this.loadCustomPlugins();
271
- this.#extendPlugins(this.allPlugins, this.eggPlugins);
272
- this.#extendPlugins(this.allPlugins, this.appPlugins);
273
- this.#extendPlugins(this.allPlugins, this.customPlugins);
274
- const enabledPluginNames = [];
275
- const plugins = {};
276
- const env = this.serverEnv;
277
- for (const name in this.allPlugins) {
278
- const plugin = this.allPlugins[name];
279
- plugin.path = this.getPluginPath(plugin);
280
- await this.#mergePluginConfig(plugin);
281
- if (env && plugin.env.length > 0 && !plugin.env.includes(env)) {
282
- this.logger.info("[egg/core] Plugin %o is disabled by env unmatched, require env(%o) but got env is %o", name, plugin.env, env);
283
- plugin.enable = false;
284
- continue;
285
- }
286
- plugins[name] = plugin;
287
- if (plugin.enable) enabledPluginNames.push(name);
288
- }
289
- this.orderPlugins = this.getOrderPlugins(plugins, enabledPluginNames, this.appPlugins);
290
- const enablePlugins = {};
291
- for (const plugin of this.orderPlugins) enablePlugins[plugin.name] = plugin;
292
- debug("Loaded enable plugins: %j", Object.keys(enablePlugins));
293
- /**
294
- * Retrieve enabled plugins
295
- * @member {Object} EggLoader#plugins
296
- * @since 1.0.0
297
- */
298
- this.plugins = enablePlugins;
299
- this.timing.end("Load Plugin");
300
- }
301
- async loadAppPlugins() {
302
- const appPlugins = await this.readPluginConfigs(path.join(this.options.baseDir, "config/plugin.default"));
303
- debug("Loaded app plugins: %j", Object.keys(appPlugins).map((k) => `${k}:${appPlugins[k].enable}`));
304
- return appPlugins;
305
- }
306
- async loadEggPlugins() {
307
- const eggPluginConfigPaths = this.eggPaths.map((eggPath) => path.join(eggPath, "config/plugin.default"));
308
- const eggPlugins = await this.readPluginConfigs(eggPluginConfigPaths);
309
- debug("Loaded egg plugins: %j", Object.keys(eggPlugins).map((k) => `${k}:${eggPlugins[k].enable}`));
310
- return eggPlugins;
311
- }
312
- loadCustomPlugins() {
313
- let customPlugins = {};
314
- const configPaths = [];
315
- if (process.env.EGG_PLUGINS) try {
316
- customPlugins = JSON.parse(process.env.EGG_PLUGINS);
317
- configPaths.push("<process.env.EGG_PLUGINS>");
318
- } catch (e) {
319
- debug("parse EGG_PLUGINS failed, %s", e);
320
- }
321
- if (this.options.plugins) {
322
- customPlugins = {
323
- ...customPlugins,
324
- ...this.options.plugins
325
- };
326
- configPaths.push("<options.plugins>");
327
- }
328
- if (customPlugins) {
329
- const configPath = configPaths.join(" or ");
330
- for (const name in customPlugins) this.#normalizePluginConfig(customPlugins, name, configPath);
331
- debug("Loaded custom plugins: %o", customPlugins);
332
- }
333
- return customPlugins;
334
- }
335
- async readPluginConfigs(configPaths) {
336
- if (!Array.isArray(configPaths)) configPaths = [configPaths];
337
- const newConfigPaths = [];
338
- for (const filename of this.getTypeFiles("plugin")) for (let configPath of configPaths) {
339
- configPath = path.join(path.dirname(configPath), filename);
340
- newConfigPaths.push(configPath);
341
- }
342
- const plugins = {};
343
- for (const configPath of newConfigPaths) {
344
- let filepath = this.resolveModule(configPath);
345
- if (configPath.endsWith("plugin.default") && !filepath) filepath = this.resolveModule(configPath.replace(/plugin\.default$/, "plugin"));
346
- if (!filepath) {
347
- debug("[readPluginConfigs:ignore] plugin config not found %o", configPath);
348
- continue;
349
- }
350
- const config = await utils_default.loadFile(filepath);
351
- for (const name in config) this.#normalizePluginConfig(config, name, filepath);
352
- this.#extendPlugins(plugins, config);
353
- }
354
- return plugins;
355
- }
356
- #normalizePluginConfig(plugins, name, configPath) {
357
- const plugin = plugins[name];
358
- if (typeof plugin === "boolean") {
359
- plugins[name] = {
360
- name,
361
- enable: plugin,
362
- dependencies: [],
363
- optionalDependencies: [],
364
- env: [],
365
- from: configPath
366
- };
367
- return;
368
- }
369
- if (!("enable" in plugin)) Reflect.set(plugin, "enable", true);
370
- plugin.name = name;
371
- plugin.dependencies = plugin.dependencies || [];
372
- plugin.optionalDependencies = plugin.optionalDependencies || [];
373
- plugin.env = plugin.env || [];
374
- plugin.from = plugin.from || configPath;
375
- depCompatible(plugin);
376
- }
377
- async #mergePluginConfig(plugin) {
378
- let pkg;
379
- let config;
380
- const pluginPackage = path.join(plugin.path, "package.json");
381
- if (await utils_default.existsPath(pluginPackage)) {
382
- pkg = await readJSON(pluginPackage);
383
- config = pkg.eggPlugin;
384
- if (pkg.version) plugin.version = pkg.version;
385
- plugin.path = await this.#formatPluginPathFromPackageJSON(plugin.path, pkg);
386
- }
387
- const logger = this.options.logger;
388
- if (!config) {
389
- logger.warn(`[@eggjs/core/egg_loader] pkg.eggPlugin is missing in ${pluginPackage}`);
390
- return;
391
- }
392
- if (config.name && config.strict !== false && config.name !== plugin.name) logger.warn(`[@eggjs/core/egg_loader] pluginName(${plugin.name}) is different from pluginConfigName(${config.name})`);
393
- depCompatible(config);
394
- for (const key of [
395
- "dependencies",
396
- "optionalDependencies",
397
- "env"
398
- ]) {
399
- const values = config[key];
400
- const existsValues = Reflect.get(plugin, key);
401
- if (Array.isArray(values) && !existsValues?.length) Reflect.set(plugin, key, values);
402
- }
403
- }
404
- getOrderPlugins(allPlugins, enabledPluginNames, appPlugins) {
405
- if (enabledPluginNames.length === 0) return [];
406
- const result = sequencify(allPlugins, enabledPluginNames);
407
- debug("Got plugins %j after sequencify", result);
408
- if (result.sequence.length === 0) {
409
- const err = /* @__PURE__ */ new Error(`sequencify plugins has problem, missing: [${result.missingTasks}], recursive: [${result.recursiveDependencies}]`);
410
- for (const missName of result.missingTasks) {
411
- const requires = [];
412
- for (const name in allPlugins) if (allPlugins[name].dependencies.includes(missName)) requires.push(name);
413
- err.message += `\n\t>> Plugin [${missName}] is disabled or missed, but is required by [${requires}]`;
414
- }
415
- err.name = "PluginSequencifyError";
416
- throw err;
417
- }
418
- const implicitEnabledPlugins = [];
419
- const requireMap = {};
420
- for (const name of result.sequence) {
421
- for (const depName of allPlugins[name].dependencies) {
422
- if (!requireMap[depName]) requireMap[depName] = [];
423
- requireMap[depName].push(name);
424
- }
425
- if (!allPlugins[name].enable) {
426
- implicitEnabledPlugins.push(name);
427
- allPlugins[name].enable = true;
428
- allPlugins[name].implicitEnable = true;
429
- }
430
- }
431
- for (const [name, dependents] of Object.entries(requireMap)) allPlugins[name].dependents = dependents;
432
- if (implicitEnabledPlugins.length > 0) {
433
- let message = implicitEnabledPlugins.map((name) => ` - ${name} required by [${requireMap[name]}]`).join("\n");
434
- this.options.logger.info(`Following plugins will be enabled implicitly.\n${message}`);
435
- const disabledPlugins = implicitEnabledPlugins.filter((name) => appPlugins[name] && appPlugins[name].enable === false);
436
- if (disabledPlugins.length > 0) {
437
- message = disabledPlugins.map((name) => ` - ${name} required by [${requireMap[name]}]`).join("\n");
438
- this.options.logger.warn(`Following plugins will be enabled implicitly that is disabled by application.\n${message}`);
439
- }
440
- }
441
- return result.sequence.map((name) => allPlugins[name]);
442
- }
443
- getLookupDirs() {
444
- const lookupDirs = /* @__PURE__ */ new Set();
445
- lookupDirs.add(this.options.baseDir);
446
- for (let i = this.eggPaths.length - 1; i >= 0; i--) {
447
- const eggPath = this.eggPaths[i];
448
- lookupDirs.add(eggPath);
449
- }
450
- lookupDirs.add(process.cwd());
451
- return lookupDirs;
452
- }
453
- getPluginPath(plugin) {
454
- if (plugin.path) return plugin.path;
455
- if (plugin.package) assert(isValidatePackageName(plugin.package), `plugin ${plugin.name} invalid, use 'path' instead of package: "${plugin.package}"`);
456
- return this.#resolvePluginPath(plugin);
457
- }
458
- #resolvePluginPath(plugin) {
459
- const name = plugin.package || plugin.name;
460
- try {
461
- const pluginPkgFile = utils_default.resolvePath(`${name}/package.json`, { paths: [...this.lookupDirs] });
462
- return path.dirname(pluginPkgFile);
463
- } catch (err) {
464
- debug("[resolvePluginPath] error: %o, plugin info: %o", err, plugin);
465
- throw new Error(`Can not find plugin ${name} in "${[...this.lookupDirs].join(", ")}"`, { cause: err });
466
- }
467
- }
468
- async #formatPluginPathFromPackageJSON(pluginPath, pluginPkg) {
469
- let realPluginPath = pluginPath;
470
- const exports = pluginPkg.eggPlugin?.exports;
471
- if (exports) {
472
- if (isESM) {
473
- if (exports.import) realPluginPath = path.join(pluginPath, exports.import);
474
- } else if (exports.require) realPluginPath = path.join(pluginPath, exports.require);
475
- if (exports.typescript && isSupportTypeScript() && !await exists(realPluginPath)) {
476
- realPluginPath = path.join(pluginPath, exports.typescript);
477
- debug("[formatPluginPathFromPackageJSON] use typescript path %o", realPluginPath);
478
- }
479
- } else if (pluginPkg.exports?.["."] && pluginPkg.type === "module") {
480
- let defaultExport = pluginPkg.exports["."];
481
- if (typeof defaultExport === "string") realPluginPath = path.dirname(path.join(pluginPath, defaultExport));
482
- else if (defaultExport?.import) {
483
- if (typeof defaultExport.import === "string") realPluginPath = path.dirname(path.join(pluginPath, defaultExport.import));
484
- else if (defaultExport.import.default) realPluginPath = path.dirname(path.join(pluginPath, defaultExport.import.default));
485
- }
486
- debug("[formatPluginPathFromPackageJSON] resolve plugin path from %o to %o, defaultExport: %o", pluginPath, realPluginPath, defaultExport);
487
- }
488
- return realPluginPath;
489
- }
490
- #extendPlugins(targets, plugins) {
491
- if (!plugins) return;
492
- for (const name in plugins) {
493
- const plugin = plugins[name];
494
- let targetPlugin = targets[name];
495
- if (!targetPlugin) {
496
- targetPlugin = {};
497
- targets[name] = targetPlugin;
498
- }
499
- if (targetPlugin.package && targetPlugin.package === plugin.package) this.logger.warn("[@eggjs/core] plugin %s has been defined that is %j, but you define again in %s", name, targetPlugin, plugin.from);
500
- if (plugin.path || plugin.package) {
501
- delete targetPlugin.path;
502
- delete targetPlugin.package;
503
- }
504
- for (const [prop, value] of Object.entries(plugin)) {
505
- if (value === void 0) continue;
506
- if (Reflect.get(targetPlugin, prop) && Array.isArray(value) && value.length === 0) continue;
507
- Reflect.set(targetPlugin, prop, value);
508
- }
509
- }
510
- }
511
- /** end Plugin loader */
512
- /** start Config loader */
513
- configMeta;
514
- config;
515
- /**
516
- * Load config/config.js
517
- *
518
- * Will merge config.default.js 和 config.${env}.js
519
- *
520
- * @function EggLoader#loadConfig
521
- * @since 1.0.0
522
- */
523
- async loadConfig() {
524
- this.timing.start("Load Config");
525
- this.configMeta = {};
526
- const target = {
527
- middleware: [],
528
- coreMiddleware: []
529
- };
530
- const appConfig = await this.#preloadAppConfig();
531
- for (const filename of this.getTypeFiles("config")) for (const unit of this.getLoadUnits()) {
532
- const isApp = unit.type === "app";
533
- const config = await this.#loadConfig(unit.path, filename, isApp ? void 0 : appConfig, unit.type);
534
- if (!config) continue;
535
- debug("[loadConfig] Loaded config %s/%s, %j", unit.path, filename, config);
536
- extend(true, target, config);
537
- }
538
- const envConfig = this.#loadConfigFromEnv();
539
- debug("[loadConfig] Loaded config from env, %j", envConfig);
540
- extend(true, target, envConfig);
541
- target.coreMiddleware = target.coreMiddleware || [];
542
- target.coreMiddlewares = target.coreMiddleware;
543
- target.appMiddleware = target.middleware || [];
544
- target.appMiddlewares = target.appMiddleware;
545
- this.config = target;
546
- debug("[loadConfig] all config: %o", this.config);
547
- this.timing.end("Load Config");
548
- }
549
- async #preloadAppConfig() {
550
- const names = ["config.default", `config.${this.serverEnv}`];
551
- const target = {};
552
- for (const filename of names) {
553
- const config = await this.#loadConfig(this.options.baseDir, filename, void 0, "app");
554
- if (!config) continue;
555
- extend(true, target, config);
556
- }
557
- return target;
558
- }
559
- async #loadConfig(dirpath, filename, extraInject, type) {
560
- const isPlugin = type === "plugin";
561
- const isApp = type === "app";
562
- let filepath = this.resolveModule(path.join(dirpath, "config", filename));
563
- if (filename === "config.default" && !filepath) filepath = this.resolveModule(path.join(dirpath, "config/config"));
564
- if (!filepath) return;
565
- const config = await this.loadFile(filepath, this.appInfo, extraInject);
566
- if (!config) return;
567
- if (isPlugin || isApp) assert(!config.coreMiddleware, "Can not define coreMiddleware in app or plugin");
568
- if (!isApp) assert(!config.middleware, "Can not define middleware in " + filepath);
569
- this.#setConfigMeta(config, filepath);
570
- return config;
571
- }
572
- #loadConfigFromEnv() {
573
- const envConfigStr = process.env.EGG_APP_CONFIG;
574
- if (!envConfigStr) return;
575
- try {
576
- const envConfig = JSON.parse(envConfigStr);
577
- this.#setConfigMeta(envConfig, "<process.env.EGG_APP_CONFIG>");
578
- return envConfig;
579
- } catch {
580
- this.options.logger.warn("[egg-loader] process.env.EGG_APP_CONFIG is not invalid JSON: %s", envConfigStr);
581
- }
582
- }
583
- #setConfigMeta(config, filepath) {
584
- config = extend(true, {}, config);
585
- this.#setConfig(config, filepath);
586
- extend(true, this.configMeta, config);
587
- }
588
- #setConfig(obj, filepath) {
589
- for (const key of Object.keys(obj)) {
590
- const val = obj[key];
591
- if (key === "console" && val && typeof val.Console === "function" && val.Console === console.Console) {
592
- obj[key] = filepath;
593
- continue;
594
- }
595
- if (val && Object.getPrototypeOf(val) === Object.prototype && Object.keys(val).length > 0) {
596
- this.#setConfig(val, filepath);
597
- continue;
598
- }
599
- obj[key] = filepath;
600
- }
601
- }
602
- /** end Config loader */
603
- /** start Extend loader */
604
- /**
605
- * mixin Agent.prototype
606
- * @function EggLoader#loadAgentExtend
607
- * @since 1.0.0
608
- */
609
- async loadAgentExtend() {
610
- await this.loadExtend("agent", this.app);
611
- }
612
- /**
613
- * mixin Application.prototype
614
- * @function EggLoader#loadApplicationExtend
615
- * @since 1.0.0
616
- */
617
- async loadApplicationExtend() {
618
- await this.loadExtend("application", this.app);
619
- }
620
- /**
621
- * mixin Request.prototype
622
- * @function EggLoader#loadRequestExtend
623
- * @since 1.0.0
624
- */
625
- async loadRequestExtend() {
626
- await this.loadExtend("request", this.app.request);
627
- }
628
- /**
629
- * mixin Response.prototype
630
- * @function EggLoader#loadResponseExtend
631
- * @since 1.0.0
632
- */
633
- async loadResponseExtend() {
634
- await this.loadExtend("response", this.app.response);
635
- }
636
- /**
637
- * mixin Context.prototype
638
- * @function EggLoader#loadContextExtend
639
- * @since 1.0.0
640
- */
641
- async loadContextExtend() {
642
- await this.loadExtend("context", this.app.context);
643
- }
644
- /**
645
- * mixin app.Helper.prototype
646
- * @function EggLoader#loadHelperExtend
647
- * @since 1.0.0
648
- */
649
- async loadHelperExtend() {
650
- if (this.app.Helper) await this.loadExtend("helper", this.app.Helper.prototype);
651
- }
652
- /**
653
- * Find all extend file paths by name
654
- * can be override in top level framework to support load `app/extends/{name}.js`
655
- *
656
- * @param {String} name - filename which may be `app/extend/{name}.js`
657
- * @returns {Array} filepaths extend file paths
658
- * @private
659
- */
660
- getExtendFilePaths(name) {
661
- return this.getLoadUnits().map((unit) => path.join(unit.path, "app/extend", name));
662
- }
663
- /**
664
- * Loader app/extend/xx.js to `prototype`,
665
- * @function loadExtend
666
- * @param {String} name - filename which may be `app/extend/{name}.js`
667
- * @param {Object} proto - prototype that mixed
668
- * @since 1.0.0
669
- */
670
- async loadExtend(name, proto) {
671
- this.timing.start(`Load extend/${name}.js`);
672
- const filepaths = this.getExtendFilePaths(name);
673
- const needUnittest = "EGG_MOCK_SERVER_ENV" in process.env && this.serverEnv !== "unittest";
674
- const length = filepaths.length;
675
- for (let i = 0; i < length; i++) {
676
- const filepath = filepaths[i];
677
- filepaths.push(filepath + `.${this.serverEnv}`);
678
- if (needUnittest) filepaths.push(filepath + ".unittest");
679
- }
680
- debug("loadExtend %s, filepaths: %j", name, filepaths);
681
- const mergeRecord = /* @__PURE__ */ new Map();
682
- for (const rawFilepath of filepaths) {
683
- const filepath = this.resolveModule(rawFilepath);
684
- if (!filepath) continue;
685
- if (filepath.endsWith("/index.js")) this.app.deprecate(`app/extend/${name}/index.js is deprecated, use app/extend/${name}.js instead`);
686
- else if (filepath.endsWith("/index.ts")) this.app.deprecate(`app/extend/${name}/index.ts is deprecated, use app/extend/${name}.ts instead`);
687
- let ext = await this.requireFile(filepath);
688
- if (isClass(ext)) ext = ext.prototype;
689
- const properties = Object.getOwnPropertyNames(ext).concat(Object.getOwnPropertySymbols(ext)).filter((name$1) => name$1 !== "constructor");
690
- for (const property of properties) {
691
- if (mergeRecord.has(property)) debug("Property: \"%s\" already exists in \"%s\",it will be redefined by \"%s\"", property, mergeRecord.get(property), filepath);
692
- let descriptor = Object.getOwnPropertyDescriptor(ext, property);
693
- let originalDescriptor = Object.getOwnPropertyDescriptor(proto, property);
694
- if (!originalDescriptor) {
695
- const originalProto = originalPrototypes[name];
696
- if (originalProto) originalDescriptor = Object.getOwnPropertyDescriptor(originalProto, property);
697
- }
698
- if (originalDescriptor) {
699
- descriptor = { ...descriptor };
700
- if (!descriptor.set && originalDescriptor.set) descriptor.set = originalDescriptor.set;
701
- if (!descriptor.get && originalDescriptor.get) descriptor.get = originalDescriptor.get;
702
- }
703
- Object.defineProperty(proto, property, descriptor);
704
- mergeRecord.set(property, filepath);
705
- }
706
- debug("merge %j to %s from %s", properties, name, filepath);
707
- }
708
- this.timing.end(`Load extend/${name}.js`);
709
- }
710
- /** end Extend loader */
711
- /** start Custom loader */
712
- /**
713
- * load app.js
714
- *
715
- * @example
716
- * - old:
717
- *
718
- * ```js
719
- * module.exports = function(app) {
720
- * doSomething();
721
- * }
722
- * ```
723
- *
724
- * - new:
725
- *
726
- * ```js
727
- * module.exports = class Boot {
728
- * constructor(app) {
729
- * this.app = app;
730
- * }
731
- * configDidLoad() {
732
- * doSomething();
733
- * }
734
- * }
735
- * @since 1.0.0
736
- */
737
- async loadCustomApp() {
738
- await this.#loadBootHook("app");
739
- this.lifecycle.triggerConfigWillLoad();
740
- }
741
- /**
742
- * Load agent.js, same as {@link EggLoader#loadCustomApp}
743
- */
744
- async loadCustomAgent() {
745
- await this.#loadBootHook("agent");
746
- this.lifecycle.triggerConfigWillLoad();
747
- }
748
- loadBootHook() {}
749
- async #loadBootHook(fileName) {
750
- this.timing.start(`Load ${fileName}.js`);
751
- for (const unit of this.getLoadUnits()) {
752
- const bootFile = path.join(unit.path, fileName);
753
- const bootFilePath = this.resolveModule(bootFile);
754
- if (!bootFilePath) {
755
- debug("[loadBootHook:ignore] %o not found", bootFile);
756
- continue;
757
- }
758
- debug("[loadBootHook:success] %o => %o", bootFile, bootFilePath);
759
- const bootHook = await this.requireFile(bootFilePath);
760
- if (isClass(bootHook)) {
761
- bootHook.prototype.fullPath = bootFilePath;
762
- this.lifecycle.addBootHook(bootHook);
763
- debug("[loadBootHook] add BootHookClass from %o", bootFilePath);
764
- } else if (typeof bootHook === "function") {
765
- this.lifecycle.addFunctionAsBootHook(bootHook, bootFilePath);
766
- debug("[loadBootHook] add bootHookFunction from %o", bootFilePath);
767
- } else this.options.logger.warn("[@eggjs/core/egg_loader] %s must exports a boot class", bootFilePath);
768
- }
769
- this.lifecycle.init();
770
- this.timing.end(`Load ${fileName}.js`);
771
- }
772
- /** end Custom loader */
773
- /** start Service loader */
774
- /**
775
- * Load app/service
776
- * @function EggLoader#loadService
777
- * @param {Object} options - LoaderOptions
778
- * @since 1.0.0
779
- */
780
- async loadService(options) {
781
- this.timing.start("Load Service");
782
- const servicePaths = this.getLoadUnits().map((unit) => path.join(unit.path, "app/service"));
783
- options = {
784
- call: true,
785
- caseStyle: CaseStyle.lower,
786
- fieldClass: "serviceClasses",
787
- directory: servicePaths,
788
- ...options
789
- };
790
- debug("[loadService] options: %o", options);
791
- await this.loadToContext(servicePaths, "service", options);
792
- this.timing.end("Load Service");
793
- }
794
- /** end Service loader */
795
- /** start Middleware loader */
796
- /**
797
- * Load app/middleware
798
- *
799
- * app.config.xx is the options of the middleware xx that has same name as config
800
- *
801
- * @function EggLoader#loadMiddleware
802
- * @param {Object} opt - LoaderOptions
803
- * @example
804
- * ```js
805
- * // app/middleware/status.js
806
- * module.exports = function(options, app) {
807
- * // options == app.config.status
808
- * return async next => {
809
- * await next();
810
- * }
811
- * }
812
- * ```
813
- * @since 1.0.0
814
- */
815
- async loadMiddleware(opt) {
816
- this.timing.start("Load Middleware");
817
- const app = this.app;
818
- const middlewarePaths = this.getLoadUnits().map((unit) => path.join(unit.path, "app/middleware"));
819
- opt = {
820
- call: false,
821
- override: true,
822
- caseStyle: CaseStyle.lower,
823
- directory: middlewarePaths,
824
- ...opt
825
- };
826
- await this.loadToApp(middlewarePaths, "middlewares", opt);
827
- debug("[loadMiddleware] middlewarePaths: %j", middlewarePaths);
828
- for (const name in app.middlewares) Object.defineProperty(app.middleware, name, {
829
- get() {
830
- return app.middlewares[name];
831
- },
832
- enumerable: false,
833
- configurable: false
834
- });
835
- this.options.logger.info("Use coreMiddleware order: %j", this.config.coreMiddleware);
836
- this.options.logger.info("Use appMiddleware order: %j", this.config.appMiddleware);
837
- const middlewareNames = this.config.coreMiddleware.concat(this.config.appMiddleware);
838
- debug("[loadMiddleware] middlewareNames: %j", middlewareNames);
839
- const middlewaresMap = /* @__PURE__ */ new Map();
840
- for (const name of middlewareNames) {
841
- const createMiddleware = app.middlewares[name];
842
- if (!createMiddleware) throw new TypeError(`Middleware ${name} not found`);
843
- if (middlewaresMap.has(name)) throw new TypeError(`Middleware ${name} redefined`);
844
- middlewaresMap.set(name, true);
845
- const options = this.config[name] || {};
846
- let mw$1 = createMiddleware(options, app);
847
- assert(typeof mw$1 === "function", `Middleware ${name} must be a function, but actual is ${inspect(mw$1)}`);
848
- if (isGeneratorFunction(mw$1)) {
849
- const fullpath = Reflect.get(createMiddleware, FULLPATH);
850
- throw new TypeError(`Support for generators was removed, middleware: ${name}, fullpath: ${fullpath}`);
851
- }
852
- mw$1._name = name;
853
- mw$1 = wrapMiddleware(mw$1, options);
854
- if (mw$1) {
855
- if (debug.enabled) mw$1 = debugMiddlewareWrapper(mw$1);
856
- app.use(mw$1);
857
- debug("[loadMiddleware] Use middleware: %s with options: %j", name, options);
858
- this.options.logger.info("[@eggjs/core/egg_loader] Use middleware: %s", name);
859
- } else this.options.logger.info("[@eggjs/core/egg_loader] Disable middleware: %s", name);
860
- }
861
- this.options.logger.info("[@eggjs/core/egg_loader] Loaded middleware from %j", middlewarePaths);
862
- this.timing.end("Load Middleware");
863
- const mw = this.app.router.middleware();
864
- Reflect.set(mw, "_name", "routerMiddleware");
865
- this.app.use(mw);
866
- }
867
- /** end Middleware loader */
868
- /** start Controller loader */
869
- /**
870
- * Load app/controller
871
- * @param {Object} opt - LoaderOptions
872
- * @since 1.0.0
873
- */
874
- async loadController(opt) {
875
- this.timing.start("Load Controller");
876
- const controllerBase = path.join(this.options.baseDir, "app/controller");
877
- opt = {
878
- caseStyle: CaseStyle.lower,
879
- directory: controllerBase,
880
- initializer: (obj, opt$1) => {
881
- if (isGeneratorFunction(obj)) throw new TypeError(`Support for generators was removed, fullpath: ${opt$1.path}`);
882
- if (!isClass(obj) && !isAsyncFunction(obj) && typeof obj === "function") {
883
- obj = obj(this.app);
884
- debug("[loadController] after init(app) => %o, meta: %j", obj, opt$1);
885
- if (isGeneratorFunction(obj)) throw new TypeError(`Support for generators was removed, fullpath: ${opt$1.path}`);
886
- }
887
- if (isClass(obj)) {
888
- obj.prototype.pathName = opt$1.pathName;
889
- obj.prototype.fullPath = opt$1.path;
890
- return wrapControllerClass(obj, opt$1.path);
891
- }
892
- if (isObject(obj)) return wrapObject(obj, opt$1.path);
893
- if (isAsyncFunction(obj)) return wrapObject({ "module.exports": obj }, opt$1.path)["module.exports"];
894
- return obj;
895
- },
896
- ...opt
897
- };
898
- await this.loadToApp(controllerBase, "controller", opt);
899
- debug("[loadController] app.controller => %o", this.app.controller);
900
- this.options.logger.info("[@eggjs/core/egg_loader] Controller loaded: %s", controllerBase);
901
- this.timing.end("Load Controller");
902
- }
903
- /** end Controller loader */
904
- /** start Router loader */
905
- /**
906
- * Load app/router.js
907
- * @function EggLoader#loadRouter
908
- * @since 1.0.0
909
- */
910
- async loadRouter() {
911
- this.timing.start("Load Router");
912
- await this.loadFile(path.join(this.options.baseDir, "app/router"));
913
- this.timing.end("Load Router");
914
- }
915
- /** end Router loader */
916
- /** start CustomLoader loader */
917
- async loadCustomLoader() {
918
- assert(this.config, "should loadConfig first");
919
- const customLoader = this.config.customLoader || {};
920
- for (const property of Object.keys(customLoader)) {
921
- const loaderConfig = { ...customLoader[property] };
922
- assert(loaderConfig.directory, `directory is required for config.customLoader.${property}`);
923
- let directory;
924
- if (loaderConfig.loadunit === true) directory = this.getLoadUnits().map((unit) => path.join(unit.path, loaderConfig.directory));
925
- else directory = path.join(this.appInfo.baseDir, loaderConfig.directory);
926
- const inject = loaderConfig.inject || "app";
927
- debug("[loadCustomLoader] loaderConfig: %o, inject: %o, directory: %o", loaderConfig, inject, directory);
928
- switch (inject) {
929
- case "ctx": {
930
- assert(!(property in this.app.context), `customLoader should not override ctx.${property}`);
931
- const options = {
932
- caseStyle: CaseStyle.lower,
933
- fieldClass: `${property}Classes`,
934
- ...loaderConfig,
935
- directory
936
- };
937
- await this.loadToContext(directory, property, options);
938
- break;
939
- }
940
- case "app": {
941
- assert(!(property in this.app), `customLoader should not override app.${property}`);
942
- const options = {
943
- caseStyle: CaseStyle.lower,
944
- initializer: (Clazz) => {
945
- return isClass(Clazz) ? new Clazz(this.app) : Clazz;
946
- },
947
- ...loaderConfig,
948
- directory
949
- };
950
- await this.loadToApp(directory, property, options);
951
- break;
952
- }
953
- default: throw new Error("inject only support app or ctx");
954
- }
955
- }
956
- }
957
- /** end CustomLoader loader */
958
- /**
959
- * Load single file, will invoke when export is function
960
- *
961
- * @param {String} filepath - fullpath
962
- * @param {Array} inject - pass rest arguments into the function when invoke
963
- * @returns {Object} exports
964
- * @example
965
- * ```js
966
- * app.loader.loadFile(path.join(app.options.baseDir, 'config/router.js'));
967
- * ```
968
- * @since 1.0.0
969
- */
970
- async loadFile(filepath, ...inject) {
971
- const fullpath = filepath && this.resolveModule(filepath);
972
- if (!fullpath) return null;
973
- if (inject.length === 0) inject = [this.app];
974
- let mod = await this.requireFile(fullpath);
975
- if (typeof mod === "function" && !isClass(mod)) {
976
- mod = mod(...inject);
977
- if (isPromise(mod)) mod = await mod;
978
- }
979
- return mod;
980
- }
981
- /**
982
- * @param {String} filepath - fullpath
983
- * @private
984
- */
985
- async requireFile(filepath) {
986
- const timingKey = `Require(${this.#requiredCount++}) ${utils_default.getResolvedFilename(filepath, this.options.baseDir)}`;
987
- this.timing.start(timingKey);
988
- const mod = await utils_default.loadFile(filepath);
989
- this.timing.end(timingKey);
990
- return mod;
991
- }
992
- /**
993
- * Get all loadUnit
994
- *
995
- * loadUnit is a directory that can be loaded by EggLoader, it has the same structure.
996
- * loadUnit has a path and a type(app, framework, plugin).
997
- *
998
- * The order of the loadUnits:
999
- *
1000
- * 1. plugin
1001
- * 2. framework
1002
- * 3. app
1003
- *
1004
- * @returns {Array} loadUnits
1005
- * @since 1.0.0
1006
- */
1007
- getLoadUnits() {
1008
- if (this.dirs) return this.dirs;
1009
- this.dirs = [];
1010
- if (this.orderPlugins) for (const plugin of this.orderPlugins) this.dirs.push({
1011
- path: plugin.path,
1012
- type: "plugin"
1013
- });
1014
- for (const eggPath of this.eggPaths) this.dirs.push({
1015
- path: eggPath,
1016
- type: "framework"
1017
- });
1018
- this.dirs.push({
1019
- path: this.options.baseDir,
1020
- type: "app"
1021
- });
1022
- debug("Loaded dirs %j", this.dirs);
1023
- return this.dirs;
1024
- }
1025
- /**
1026
- * Load files using {@link FileLoader}, inject to {@link Application}
1027
- * @param {String|Array} directory - see {@link FileLoader}
1028
- * @param {String} property - see {@link FileLoader}, e.g.: 'controller', 'middlewares'
1029
- * @param {Object} options - see {@link FileLoader}
1030
- * @since 1.0.0
1031
- */
1032
- async loadToApp(directory, property, options) {
1033
- const target = {};
1034
- Reflect.set(this.app, property, target);
1035
- const loadOptions = {
1036
- ...options,
1037
- directory: options?.directory ?? directory,
1038
- target,
1039
- inject: this.app
1040
- };
1041
- const timingKey = `Load "${String(property)}" to Application`;
1042
- this.timing.start(timingKey);
1043
- await new FileLoader(loadOptions).load();
1044
- this.timing.end(timingKey);
1045
- }
1046
- /**
1047
- * Load files using {@link ContextLoader}
1048
- * @param {String|Array} directory - see {@link ContextLoader}
1049
- * @param {String} property - see {@link ContextLoader}
1050
- * @param {Object} options - see {@link ContextLoader}
1051
- * @since 1.0.0
1052
- */
1053
- async loadToContext(directory, property, options) {
1054
- const loadOptions = {
1055
- ...options,
1056
- directory: options?.directory || directory,
1057
- property,
1058
- inject: this.app
1059
- };
1060
- const timingKey = `Load "${String(property)}" to Context`;
1061
- this.timing.start(timingKey);
1062
- await new ContextLoader(loadOptions).load();
1063
- this.timing.end(timingKey);
1064
- }
1065
- /**
1066
- * @member {FileLoader} EggLoader#FileLoader
1067
- * @since 1.0.0
1068
- */
1069
- get FileLoader() {
1070
- return FileLoader;
1071
- }
1072
- /**
1073
- * @member {ContextLoader} EggLoader#ContextLoader
1074
- * @since 1.0.0
1075
- */
1076
- get ContextLoader() {
1077
- return ContextLoader;
1078
- }
1079
- getTypeFiles(filename) {
1080
- const files = [`${filename}.default`];
1081
- if (this.serverScope) files.push(`${filename}.${this.serverScope}`);
1082
- if (this.serverEnv === "default") return files;
1083
- files.push(`${filename}.${this.serverEnv}`);
1084
- if (this.serverScope) files.push(`${filename}.${this.serverScope}_${this.serverEnv}`);
1085
- return files;
1086
- }
1087
- resolveModule(filepath) {
1088
- let fullPath;
1089
- try {
1090
- fullPath = utils_default.resolvePath(filepath);
1091
- } catch {
1092
- return;
1093
- }
1094
- return fullPath;
1095
- }
1096
- };
1097
- function depCompatible(plugin) {
1098
- if (plugin.dep && !(Array.isArray(plugin.dependencies) && plugin.dependencies.length > 0)) {
1099
- plugin.dependencies = plugin.dep;
1100
- delete plugin.dep;
1101
- }
1102
- }
1103
- function isValidatePackageName(name) {
1104
- if (name.startsWith(".")) return false;
1105
- if (name.startsWith("/")) return false;
1106
- if (name.includes(":")) return false;
1107
- return true;
1108
- }
1109
- function wrapMiddleware(mw, options) {
1110
- if (options.enable === false) return null;
1111
- if (!options.match && !options.ignore) return mw;
1112
- const match = pathMatching(options);
1113
- const fn = (ctx, next) => {
1114
- if (!match(ctx)) return next();
1115
- return mw(ctx, next);
1116
- };
1117
- fn._name = `${mw._name}middlewareWrapper`;
1118
- return fn;
1119
- }
1120
- function debugMiddlewareWrapper(mw) {
1121
- const fn = async (ctx, next) => {
1122
- const startTime = now();
1123
- debug("[debugMiddlewareWrapper] [%s %s] enter middleware: %s", ctx.method, ctx.url, mw._name);
1124
- await mw(ctx, next);
1125
- const rt = diff(startTime);
1126
- debug("[debugMiddlewareWrapper] [%s %s] after middleware: %s [%sms]", ctx.method, ctx.url, mw._name, rt);
1127
- };
1128
- fn._name = `${mw._name}DebugWrapper`;
1129
- return fn;
1130
- }
1131
- function wrapControllerClass(Controller, fullPath) {
1132
- let proto = Controller.prototype;
1133
- const ret = {};
1134
- while (proto !== Object.prototype) {
1135
- const keys = Object.getOwnPropertyNames(proto);
1136
- for (const key of keys) {
1137
- if (key === "constructor") continue;
1138
- const d = Object.getOwnPropertyDescriptor(proto, key);
1139
- if (typeof d?.value === "function" && !Object.hasOwn(ret, key)) {
1140
- const controllerMethodName = `${Controller.name}.${key}`;
1141
- if (isGeneratorFunction(d.value)) throw new TypeError(`Support for generators was removed, controller \`${controllerMethodName}\`, fullpath: ${fullPath}`);
1142
- ret[key] = controllerMethodToMiddleware(Controller, key);
1143
- ret[key][FULLPATH] = `${fullPath}#${controllerMethodName}()`;
1144
- }
1145
- }
1146
- proto = Object.getPrototypeOf(proto);
1147
- }
1148
- return ret;
1149
- }
1150
- function controllerMethodToMiddleware(Controller, key) {
1151
- return function classControllerMiddleware(...args) {
1152
- const controller = new Controller(this);
1153
- if (!this.app.config.controller?.supportParams) args = [this];
1154
- return controller[key](...args);
1155
- };
1156
- }
1157
- function wrapObject(obj, fullPath, prefix) {
1158
- const keys = Object.keys(obj);
1159
- const ret = {};
1160
- prefix = prefix ?? "";
1161
- for (const key of keys) {
1162
- const controllerMethodName = `${prefix}${key}`;
1163
- const item = obj[key];
1164
- if (isGeneratorFunction(item)) throw new TypeError(`Support for generators was removed, controller \`${controllerMethodName}\`, fullpath: ${fullPath}`);
1165
- if (typeof item === "function") {
1166
- if (getParamNames(item)[0] === "next") throw new Error(`controller \`${controllerMethodName}\` should not use next as argument from file ${fullPath}`);
1167
- ret[key] = objectFunctionToMiddleware(item);
1168
- ret[key][FULLPATH] = `${fullPath}#${controllerMethodName}()`;
1169
- } else if (isObject(item)) ret[key] = wrapObject(item, fullPath, `${controllerMethodName}.`);
1170
- }
1171
- debug("[wrapObject] fullPath: %s, prefix: %s => %o", fullPath, prefix, ret);
1172
- return ret;
1173
- }
1174
- function objectFunctionToMiddleware(func) {
1175
- async function objectControllerMiddleware(...args) {
1176
- if (!this.app.config.controller?.supportParams) args = [this];
1177
- return await func.apply(this, args);
1178
- }
1179
- for (const key in func) Reflect.set(objectControllerMiddleware, key, Reflect.get(func, key));
1180
- return objectControllerMiddleware;
1181
- }
1182
-
1183
- //#endregion
1184
- export { EggLoader };