@eggjs/core 6.0.0-beta.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.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +296 -0
  3. package/dist/commonjs/base_context_class.d.ts +16 -0
  4. package/dist/commonjs/base_context_class.js +41 -0
  5. package/dist/commonjs/egg.d.ts +204 -0
  6. package/dist/commonjs/egg.js +346 -0
  7. package/dist/commonjs/index.d.ts +5 -0
  8. package/dist/commonjs/index.js +26 -0
  9. package/dist/commonjs/lifecycle.d.ts +75 -0
  10. package/dist/commonjs/lifecycle.js +306 -0
  11. package/dist/commonjs/loader/context_loader.d.ts +24 -0
  12. package/dist/commonjs/loader/context_loader.js +109 -0
  13. package/dist/commonjs/loader/egg_loader.d.ts +405 -0
  14. package/dist/commonjs/loader/egg_loader.js +1497 -0
  15. package/dist/commonjs/loader/file_loader.d.ts +96 -0
  16. package/dist/commonjs/loader/file_loader.js +248 -0
  17. package/dist/commonjs/package.json +3 -0
  18. package/dist/commonjs/types.d.ts +1 -0
  19. package/dist/commonjs/types.js +403 -0
  20. package/dist/commonjs/utils/index.d.ts +14 -0
  21. package/dist/commonjs/utils/index.js +146 -0
  22. package/dist/commonjs/utils/sequencify.d.ts +13 -0
  23. package/dist/commonjs/utils/sequencify.js +59 -0
  24. package/dist/commonjs/utils/timing.d.ts +22 -0
  25. package/dist/commonjs/utils/timing.js +100 -0
  26. package/dist/esm/base_context_class.d.ts +16 -0
  27. package/dist/esm/base_context_class.js +37 -0
  28. package/dist/esm/egg.d.ts +204 -0
  29. package/dist/esm/egg.js +339 -0
  30. package/dist/esm/index.d.ts +5 -0
  31. package/dist/esm/index.js +6 -0
  32. package/dist/esm/lifecycle.d.ts +75 -0
  33. package/dist/esm/lifecycle.js +276 -0
  34. package/dist/esm/loader/context_loader.d.ts +24 -0
  35. package/dist/esm/loader/context_loader.js +102 -0
  36. package/dist/esm/loader/egg_loader.d.ts +405 -0
  37. package/dist/esm/loader/egg_loader.js +1490 -0
  38. package/dist/esm/loader/file_loader.d.ts +96 -0
  39. package/dist/esm/loader/file_loader.js +241 -0
  40. package/dist/esm/package.json +3 -0
  41. package/dist/esm/types.d.ts +1 -0
  42. package/dist/esm/types.js +402 -0
  43. package/dist/esm/utils/index.d.ts +14 -0
  44. package/dist/esm/utils/index.js +141 -0
  45. package/dist/esm/utils/sequencify.d.ts +13 -0
  46. package/dist/esm/utils/sequencify.js +56 -0
  47. package/dist/esm/utils/timing.d.ts +22 -0
  48. package/dist/esm/utils/timing.js +93 -0
  49. package/package.json +103 -0
  50. package/src/base_context_class.ts +39 -0
  51. package/src/egg.ts +430 -0
  52. package/src/index.ts +6 -0
  53. package/src/lifecycle.ts +363 -0
  54. package/src/loader/context_loader.ts +121 -0
  55. package/src/loader/egg_loader.ts +1703 -0
  56. package/src/loader/file_loader.ts +295 -0
  57. package/src/types.ts +447 -0
  58. package/src/utils/index.ts +154 -0
  59. package/src/utils/sequencify.ts +70 -0
  60. package/src/utils/timing.ts +114 -0
@@ -0,0 +1,1703 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import assert from 'node:assert';
4
+ import { debuglog, inspect } from 'node:util';
5
+ import { isAsyncFunction, isClass, isGeneratorFunction, isObject } from 'is-type-of';
6
+ import homedir from 'node-homedir';
7
+ import type { Logger } from 'egg-logger';
8
+ import { getParamNames, readJSONSync } from 'utility';
9
+ import { extend } from 'extend2';
10
+ import { Request, Response, Context, Application, Next } from '@eggjs/koa';
11
+ import { pathMatching, type PathMatchingOptions } from 'egg-path-matching';
12
+ import { now, diff } from 'performance-ms';
13
+ import { FULLPATH, FileLoader, FileLoaderOptions } from './file_loader.js';
14
+ import { ContextLoader, ContextLoaderOptions } from './context_loader.js';
15
+ import utils, { Fun } from '../utils/index.js';
16
+ import sequencify from '../utils/sequencify.js';
17
+ import { Timing } from '../utils/timing.js';
18
+ import type { EggCoreContext, EggCore, MiddlewareFunc } from '../egg.js';
19
+ import { BaseContextClass } from '../base_context_class.js';
20
+
21
+ const debug = debuglog('@eggjs/core:egg_loader');
22
+
23
+ const originalPrototypes: Record<string, any> = {
24
+ request: Request.prototype,
25
+ response: Response.prototype,
26
+ context: Context.prototype,
27
+ application: Application.prototype,
28
+ };
29
+
30
+ export interface EggAppInfo {
31
+ /** package.json */
32
+ pkg: Record<string, any>;
33
+ /** the application name from package.json */
34
+ name: string;
35
+ /** current directory of application */
36
+ baseDir: string;
37
+ /** equals to serverEnv */
38
+ env: string;
39
+ /** equals to serverScope */
40
+ scope: string;
41
+ /** home directory of the OS */
42
+ HOME: string;
43
+ /** baseDir when local and unittest, HOME when other environment */
44
+ root: string;
45
+ }
46
+
47
+ export interface EggPluginInfo {
48
+ /** the plugin name, it can be used in `dep` */
49
+ name: string;
50
+ /** the package name of plugin */
51
+ package?: string;
52
+ version?: string;
53
+ /** whether enabled */
54
+ enable: boolean;
55
+ implicitEnable?: boolean;
56
+ /** the directory of the plugin package */
57
+ path?: string;
58
+ /** the dependent plugins, you can use the plugin name */
59
+ dependencies: string[];
60
+ /** the optional dependent plugins. */
61
+ optionalDependencies: string[];
62
+ dependents?: string[];
63
+ /** specify the serverEnv that only enable the plugin in it */
64
+ env: string[];
65
+ /** the file plugin config in. */
66
+ from: string;
67
+ }
68
+
69
+ export interface EggLoaderOptions {
70
+ /** server env */
71
+ env: string;
72
+ /** Application instance */
73
+ app: EggCore;
74
+ EggCoreClass?: typeof EggCore;
75
+ /** the directory of application */
76
+ baseDir: string;
77
+ /** egg logger */
78
+ logger: Logger;
79
+ /** server scope */
80
+ serverScope?: string;
81
+ /** custom plugins */
82
+ plugins?: Record<string, EggPluginInfo>;
83
+ }
84
+
85
+ export type EggDirInfoType = 'app' | 'plugin' | 'framework';
86
+
87
+ export interface EggDirInfo {
88
+ path: string;
89
+ type: EggDirInfoType;
90
+ }
91
+
92
+ export class EggLoader {
93
+ #requiredCount = 0;
94
+ readonly options: EggLoaderOptions;
95
+ readonly timing: Timing;
96
+ readonly pkg: Record<string, any>;
97
+ readonly eggPaths: string[];
98
+ readonly serverEnv: string;
99
+ readonly serverScope: string;
100
+ readonly appInfo: EggAppInfo;
101
+ dirs?: EggDirInfo[];
102
+
103
+
104
+ /**
105
+ * @class
106
+ * @param {Object} options - options
107
+ * @param {String} options.baseDir - the directory of application
108
+ * @param {EggCore} options.app - Application instance
109
+ * @param {Logger} options.logger - logger
110
+ * @param {Object} [options.plugins] - custom plugins
111
+ * @since 1.0.0
112
+ */
113
+ constructor(options: EggLoaderOptions) {
114
+ this.options = options;
115
+ assert(fs.existsSync(this.options.baseDir), `${this.options.baseDir} not exists`);
116
+ assert(this.options.app, 'options.app is required');
117
+ assert(this.options.logger, 'options.logger is required');
118
+
119
+ this.timing = this.app.timing || new Timing();
120
+
121
+ /**
122
+ * @member {Object} EggLoader#pkg
123
+ * @see {@link AppInfo#pkg}
124
+ * @since 1.0.0
125
+ */
126
+ this.pkg = readJSONSync(path.join(this.options.baseDir, 'package.json'));
127
+
128
+ // auto require('tsconfig-paths/register') on typescript app
129
+ // support env.EGG_TYPESCRIPT = true or { "egg": { "typescript": true } } on package.json
130
+ if (process.env.EGG_TYPESCRIPT === 'true' || (this.pkg.egg && this.pkg.egg.typescript)) {
131
+ // skip require tsconfig-paths if tsconfig.json not exists
132
+ const tsConfigFile = path.join(this.options.baseDir, 'tsconfig.json');
133
+ // FIXME: support esm
134
+ if (fs.existsSync(tsConfigFile) && typeof require === 'function') {
135
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
136
+ require('tsconfig-paths').register({ cwd: this.options.baseDir });
137
+ } else {
138
+ this.logger.info('[@eggjs/core:egg_loader] skip register "tsconfig-paths" because tsconfig.json not exists at %s',
139
+ tsConfigFile);
140
+ }
141
+ }
142
+
143
+ /**
144
+ * All framework directories.
145
+ *
146
+ * You can extend Application of egg, the entry point is options.app,
147
+ *
148
+ * loader will find all directories from the prototype of Application,
149
+ * you should define `Symbol.for('egg#eggPath')` property.
150
+ *
151
+ * ```
152
+ * // lib/example.js
153
+ * const egg = require('egg');
154
+ * class ExampleApplication extends egg.Application {
155
+ * constructor(options) {
156
+ * super(options);
157
+ * }
158
+ *
159
+ * get [Symbol.for('egg#eggPath')]() {
160
+ * return path.join(__dirname, '..');
161
+ * }
162
+ * }
163
+ * ```
164
+ * @member {Array} EggLoader#eggPaths
165
+ * @see EggLoader#getEggPaths
166
+ * @since 1.0.0
167
+ */
168
+ this.eggPaths = this.getEggPaths();
169
+ debug('Loaded eggPaths %j', this.eggPaths);
170
+
171
+ /**
172
+ * @member {String} EggLoader#serverEnv
173
+ * @see AppInfo#env
174
+ * @since 1.0.0
175
+ */
176
+ this.serverEnv = this.getServerEnv();
177
+ debug('Loaded serverEnv %j', this.serverEnv);
178
+
179
+ /**
180
+ * @member {String} EggLoader#serverScope
181
+ * @see AppInfo#serverScope
182
+ */
183
+ this.serverScope = options.serverScope !== undefined
184
+ ? options.serverScope
185
+ : this.getServerScope();
186
+
187
+ /**
188
+ * @member {AppInfo} EggLoader#appInfo
189
+ * @since 1.0.0
190
+ */
191
+ this.appInfo = this.getAppInfo();
192
+ }
193
+
194
+ get app() {
195
+ return this.options.app;
196
+ }
197
+
198
+ get lifecycle() {
199
+ return this.app.lifecycle;
200
+ }
201
+
202
+ get logger() {
203
+ return this.options.logger;
204
+ }
205
+
206
+ /**
207
+ * Get {@link AppInfo#env}
208
+ * @return {String} env
209
+ * @see AppInfo#env
210
+ * @private
211
+ * @since 1.0.0
212
+ */
213
+ protected getServerEnv(): string {
214
+ let serverEnv = this.options.env;
215
+
216
+ const envPath = path.join(this.options.baseDir, 'config/env');
217
+ if (!serverEnv && fs.existsSync(envPath)) {
218
+ serverEnv = fs.readFileSync(envPath, 'utf8').trim();
219
+ }
220
+
221
+ if (!serverEnv && process.env.EGG_SERVER_ENV) {
222
+ serverEnv = process.env.EGG_SERVER_ENV;
223
+ }
224
+
225
+ if (!serverEnv) {
226
+ if (process.env.NODE_ENV === 'test') {
227
+ serverEnv = 'unittest';
228
+ } else if (process.env.NODE_ENV === 'production') {
229
+ serverEnv = 'prod';
230
+ } else {
231
+ serverEnv = 'local';
232
+ }
233
+ } else {
234
+ serverEnv = serverEnv.trim();
235
+ }
236
+
237
+ return serverEnv;
238
+ }
239
+
240
+ /**
241
+ * Get {@link AppInfo#scope}
242
+ * @return {String} serverScope
243
+ * @private
244
+ */
245
+ protected getServerScope(): string {
246
+ return process.env.EGG_SERVER_SCOPE || '';
247
+ }
248
+
249
+ /**
250
+ * Get {@link AppInfo#name}
251
+ * @return {String} appname
252
+ * @private
253
+ * @since 1.0.0
254
+ */
255
+ getAppname(): string {
256
+ if (this.pkg.name) {
257
+ debug('Loaded appname(%s) from package.json', this.pkg.name);
258
+ return this.pkg.name;
259
+ }
260
+ const pkg = path.join(this.options.baseDir, 'package.json');
261
+ throw new Error(`name is required from ${pkg}`);
262
+ }
263
+
264
+ /**
265
+ * Get home directory
266
+ * @return {String} home directory
267
+ * @since 3.4.0
268
+ */
269
+ getHomedir(): string {
270
+ // EGG_HOME for test
271
+ return process.env.EGG_HOME || homedir() || '/home/admin';
272
+ }
273
+
274
+ /**
275
+ * Get app info
276
+ * @return {AppInfo} appInfo
277
+ * @since 1.0.0
278
+ */
279
+ protected getAppInfo(): EggAppInfo {
280
+ const env = this.serverEnv;
281
+ const scope = this.serverScope;
282
+ const home = this.getHomedir();
283
+ const baseDir = this.options.baseDir;
284
+
285
+ /**
286
+ * Meta information of the application
287
+ * @class AppInfo
288
+ */
289
+ return {
290
+ /**
291
+ * The name of the application, retrieve from the name property in `package.json`.
292
+ * @member {String} AppInfo#name
293
+ */
294
+ name: this.getAppname(),
295
+
296
+ /**
297
+ * The current directory, where the application code is.
298
+ * @member {String} AppInfo#baseDir
299
+ */
300
+ baseDir,
301
+
302
+ /**
303
+ * The environment of the application, **it's not NODE_ENV**
304
+ *
305
+ * 1. from `$baseDir/config/env`
306
+ * 2. from EGG_SERVER_ENV
307
+ * 3. from NODE_ENV
308
+ *
309
+ * env | description
310
+ * --- | ---
311
+ * test | system integration testing
312
+ * prod | production
313
+ * local | local on your own computer
314
+ * unittest | unit test
315
+ *
316
+ * @member {String} AppInfo#env
317
+ * @see https://eggjs.org/zh-cn/basics/env.html
318
+ */
319
+ env,
320
+
321
+ /**
322
+ * @member {String} AppInfo#scope
323
+ */
324
+ scope,
325
+
326
+ /**
327
+ * The use directory, same as `process.env.HOME`
328
+ * @member {String} AppInfo#HOME
329
+ */
330
+ HOME: home,
331
+
332
+ /**
333
+ * parsed from `package.json`
334
+ * @member {Object} AppInfo#pkg
335
+ */
336
+ pkg: this.pkg,
337
+
338
+ /**
339
+ * The directory whether is baseDir or HOME depend on env.
340
+ * it's good for test when you want to write some file to HOME,
341
+ * but don't want to write to the real directory,
342
+ * so use root to write file to baseDir instead of HOME when unittest.
343
+ * keep root directory in baseDir when local and unittest
344
+ * @member {String} AppInfo#root
345
+ */
346
+ root: env === 'local' || env === 'unittest' ? baseDir : home,
347
+ };
348
+ }
349
+
350
+ /**
351
+ * Get {@link EggLoader#eggPaths}
352
+ * @return {Array} framework directories
353
+ * @see {@link EggLoader#eggPaths}
354
+ * @private
355
+ * @since 1.0.0
356
+ */
357
+ protected getEggPaths(): string[] {
358
+ // avoid require recursively
359
+ const EggCore = this.options.EggCoreClass!;
360
+ const eggPaths: string[] = [];
361
+
362
+ let proto = this.app;
363
+
364
+ // Loop for the prototype chain
365
+ while (proto) {
366
+ proto = Object.getPrototypeOf(proto);
367
+ // stop the loop if
368
+ // - object extends Object
369
+ // - object extends EggCore
370
+ if (proto === Object.prototype || proto === EggCore.prototype) {
371
+ break;
372
+ }
373
+
374
+ assert(proto.hasOwnProperty(Symbol.for('egg#eggPath')), 'Symbol.for(\'egg#eggPath\') is required on Application');
375
+ const eggPath = Reflect.get(proto, Symbol.for('egg#eggPath'));
376
+ assert(eggPath && typeof eggPath === 'string', 'Symbol.for(\'egg#eggPath\') should be string');
377
+ assert(fs.existsSync(eggPath), `${eggPath} not exists`);
378
+ const realpath = fs.realpathSync(eggPath);
379
+ if (!eggPaths.includes(realpath)) {
380
+ eggPaths.unshift(realpath);
381
+ }
382
+ }
383
+
384
+ return eggPaths;
385
+ }
386
+
387
+ /** start Plugin loader */
388
+ lookupDirs: Set<string>;
389
+ eggPlugins: Record<string, EggPluginInfo>;
390
+ appPlugins: Record<string, EggPluginInfo>;
391
+ customPlugins: Record<string, EggPluginInfo>;
392
+ allPlugins: Record<string, EggPluginInfo>;
393
+ orderPlugins: EggPluginInfo[];
394
+ /** enable plugins */
395
+ plugins: Record<string, EggPluginInfo>;
396
+
397
+ /**
398
+ * Load config/plugin.js from {EggLoader#loadUnits}
399
+ *
400
+ * plugin.js is written below
401
+ *
402
+ * ```js
403
+ * {
404
+ * 'xxx-client': {
405
+ * enable: true,
406
+ * package: 'xxx-client',
407
+ * dep: [],
408
+ * env: [],
409
+ * },
410
+ * // short hand
411
+ * 'rds': false,
412
+ * 'depd': {
413
+ * enable: true,
414
+ * path: 'path/to/depd'
415
+ * }
416
+ * }
417
+ * ```
418
+ *
419
+ * If the plugin has path, Loader will find the module from it.
420
+ *
421
+ * Otherwise Loader will lookup follow the order by packageName
422
+ *
423
+ * 1. $APP_BASE/node_modules/${package}
424
+ * 2. $EGG_BASE/node_modules/${package}
425
+ *
426
+ * You can call `loader.plugins` that retrieve enabled plugins.
427
+ *
428
+ * ```js
429
+ * loader.plugins['xxx-client'] = {
430
+ * name: 'xxx-client', // the plugin name, it can be used in `dep`
431
+ * package: 'xxx-client', // the package name of plugin
432
+ * enable: true, // whether enabled
433
+ * path: 'path/to/xxx-client', // the directory of the plugin package
434
+ * dep: [], // the dependent plugins, you can use the plugin name
435
+ * env: [ 'local', 'unittest' ], // specify the serverEnv that only enable the plugin in it
436
+ * }
437
+ * ```
438
+ *
439
+ * `loader.allPlugins` can be used when retrieve all plugins.
440
+ * @function EggLoader#loadPlugin
441
+ * @since 1.0.0
442
+ */
443
+ async loadPlugin() {
444
+ this.timing.start('Load Plugin');
445
+
446
+ this.lookupDirs = this.getLookupDirs();
447
+ this.allPlugins = {};
448
+ this.eggPlugins = await this.loadEggPlugins();
449
+ this.appPlugins = await this.loadAppPlugins();
450
+ this.customPlugins = this.loadCustomPlugins();
451
+
452
+ this.#extendPlugins(this.allPlugins, this.eggPlugins);
453
+ this.#extendPlugins(this.allPlugins, this.appPlugins);
454
+ this.#extendPlugins(this.allPlugins, this.customPlugins);
455
+
456
+ const enabledPluginNames: string[] = []; // enabled plugins that configured explicitly
457
+ const plugins: Record<string, EggPluginInfo> = {};
458
+ const env = this.serverEnv;
459
+ for (const name in this.allPlugins) {
460
+ const plugin = this.allPlugins[name];
461
+
462
+ // resolve the real plugin.path based on plugin or package
463
+ plugin.path = this.getPluginPath(plugin);
464
+
465
+ // read plugin information from ${plugin.path}/package.json
466
+ this.#mergePluginConfig(plugin);
467
+
468
+ // disable the plugin that not match the serverEnv
469
+ if (env && plugin.env.length > 0 && !plugin.env.includes(env)) {
470
+ this.logger.info('[@eggjs/core] Plugin %o is disabled by env unmatched, require env(%o) but got env is %o',
471
+ name, plugin.env, env);
472
+ plugin.enable = false;
473
+ continue;
474
+ }
475
+
476
+ plugins[name] = plugin;
477
+ if (plugin.enable) {
478
+ enabledPluginNames.push(name);
479
+ }
480
+ }
481
+
482
+ // retrieve the ordered plugins
483
+ this.orderPlugins = this.getOrderPlugins(plugins, enabledPluginNames, this.appPlugins);
484
+
485
+ const enablePlugins: Record<string, EggPluginInfo> = {};
486
+ for (const plugin of this.orderPlugins) {
487
+ enablePlugins[plugin.name] = plugin;
488
+ }
489
+ debug('Loaded enable plugins: %j', Object.keys(enablePlugins));
490
+
491
+ /**
492
+ * Retrieve enabled plugins
493
+ * @member {Object} EggLoader#plugins
494
+ * @since 1.0.0
495
+ */
496
+ this.plugins = enablePlugins;
497
+ this.timing.end('Load Plugin');
498
+ }
499
+
500
+ protected async loadAppPlugins() {
501
+ // loader plugins from application
502
+ const appPlugins = await this.readPluginConfigs(path.join(this.options.baseDir, 'config/plugin.default'));
503
+ debug('Loaded app plugins: %j', Object.keys(appPlugins).map(k => `${k}:${appPlugins[k].enable}`));
504
+ return appPlugins;
505
+ }
506
+
507
+ protected async loadEggPlugins() {
508
+ // loader plugins from framework
509
+ const eggPluginConfigPaths = this.eggPaths.map(eggPath => path.join(eggPath, 'config/plugin.default'));
510
+ const eggPlugins = await this.readPluginConfigs(eggPluginConfigPaths);
511
+ debug('Loaded egg plugins: %j', Object.keys(eggPlugins).map(k => `${k}:${eggPlugins[k].enable}`));
512
+ return eggPlugins;
513
+ }
514
+
515
+ protected loadCustomPlugins() {
516
+ // loader plugins from process.env.EGG_PLUGINS
517
+ let customPlugins: Record<string, EggPluginInfo> = {};
518
+ const configPaths: string[] = [];
519
+ if (process.env.EGG_PLUGINS) {
520
+ try {
521
+ customPlugins = JSON.parse(process.env.EGG_PLUGINS);
522
+ configPaths.push('<process.env.EGG_PLUGINS>');
523
+ } catch (e) {
524
+ debug('parse EGG_PLUGINS failed, %s', e);
525
+ }
526
+ }
527
+
528
+ // loader plugins from options.plugins
529
+ if (this.options.plugins) {
530
+ customPlugins = {
531
+ ...customPlugins,
532
+ ...this.options.plugins,
533
+ };
534
+ configPaths.push('<options.plugins>');
535
+ }
536
+
537
+ if (customPlugins) {
538
+ const configPath = configPaths.join(' or ');
539
+ for (const name in customPlugins) {
540
+ this.#normalizePluginConfig(customPlugins, name, configPath);
541
+ }
542
+ debug('Loaded custom plugins: %j', Object.keys(customPlugins));
543
+ }
544
+ return customPlugins;
545
+ }
546
+
547
+ /*
548
+ * Read plugin.js from multiple directory
549
+ */
550
+ protected async readPluginConfigs(configPaths: string[] | string) {
551
+ if (!Array.isArray(configPaths)) {
552
+ configPaths = [ configPaths ];
553
+ }
554
+
555
+ // Get all plugin configurations
556
+ // plugin.default.js
557
+ // plugin.${scope}.js
558
+ // plugin.${env}.js
559
+ // plugin.${scope}_${env}.js
560
+ const newConfigPaths: string[] = [];
561
+ for (const filename of this.getTypeFiles('plugin')) {
562
+ for (let configPath of configPaths) {
563
+ configPath = path.join(path.dirname(configPath), filename);
564
+ newConfigPaths.push(configPath);
565
+ }
566
+ }
567
+
568
+ const plugins: Record<string, EggPluginInfo> = {};
569
+ for (const configPath of newConfigPaths) {
570
+ let filepath = this.resolveModule(configPath);
571
+
572
+ // let plugin.js compatible
573
+ if (configPath.endsWith('plugin.default') && !filepath) {
574
+ filepath = this.resolveModule(configPath.replace(/plugin\.default$/, 'plugin'));
575
+ }
576
+
577
+ if (!filepath) {
578
+ continue;
579
+ }
580
+
581
+ const config = await utils.loadFile(filepath) as Record<string, EggPluginInfo>;
582
+ for (const name in config) {
583
+ this.#normalizePluginConfig(config, name, filepath);
584
+ }
585
+ this.#extendPlugins(plugins, config);
586
+ }
587
+
588
+ return plugins;
589
+ }
590
+
591
+ #normalizePluginConfig(plugins: Record<string, EggPluginInfo | boolean>, name: string, configPath: string) {
592
+ const plugin = plugins[name];
593
+
594
+ // plugin_name: false
595
+ if (typeof plugin === 'boolean') {
596
+ plugins[name] = {
597
+ name,
598
+ enable: plugin,
599
+ dependencies: [],
600
+ optionalDependencies: [],
601
+ env: [],
602
+ from: configPath,
603
+ } satisfies EggPluginInfo;
604
+ return;
605
+ }
606
+
607
+ if (!('enable' in plugin)) {
608
+ Reflect.set(plugin, 'enable', true);
609
+ }
610
+ plugin.name = name;
611
+ plugin.dependencies = plugin.dependencies || [];
612
+ plugin.optionalDependencies = plugin.optionalDependencies || [];
613
+ plugin.env = plugin.env || [];
614
+ plugin.from = plugin.from || configPath;
615
+ depCompatible(plugin);
616
+ }
617
+
618
+ // Read plugin information from package.json and merge
619
+ // {
620
+ // eggPlugin: {
621
+ // "name": "", plugin name, must be same as name in config/plugin.js
622
+ // "dep": [], dependent plugins
623
+ // "env": "" env
624
+ // "strict": true, whether check plugin name, default to true.
625
+ // }
626
+ // }
627
+ #mergePluginConfig(plugin: EggPluginInfo) {
628
+ let pkg;
629
+ let config;
630
+ const pluginPackage = path.join(plugin.path!, 'package.json');
631
+ if (fs.existsSync(pluginPackage)) {
632
+ pkg = readJSONSync(pluginPackage);
633
+ config = pkg.eggPlugin;
634
+ if (pkg.version) {
635
+ plugin.version = pkg.version;
636
+ }
637
+ }
638
+
639
+ const logger = this.options.logger;
640
+ if (!config) {
641
+ logger.warn(`[@eggjs/core:egg_loader] pkg.eggPlugin is missing in ${pluginPackage}`);
642
+ return;
643
+ }
644
+
645
+ if (config.name && config.strict !== false && config.name !== plugin.name) {
646
+ // pluginName is configured in config/plugin.js
647
+ // pluginConfigName is pkg.eggPlugin.name
648
+ logger.warn(`[@eggjs/core:egg_loader] pluginName(${plugin.name}) is different from pluginConfigName(${config.name})`);
649
+ }
650
+
651
+ // dep compatible
652
+ depCompatible(config);
653
+
654
+ for (const key of [ 'dependencies', 'optionalDependencies', 'env' ]) {
655
+ const values = config[key];
656
+ const existsValues = Reflect.get(plugin, key);
657
+ if (Array.isArray(values) && !existsValues?.length) {
658
+ Reflect.set(plugin, key, values);
659
+ }
660
+ }
661
+ }
662
+
663
+ protected getOrderPlugins(allPlugins: Record<string, EggPluginInfo>, enabledPluginNames: string[],
664
+ appPlugins: Record<string, EggPluginInfo>) {
665
+ // no plugins enabled
666
+ if (!enabledPluginNames.length) {
667
+ return [];
668
+ }
669
+
670
+ const result = sequencify(allPlugins, enabledPluginNames);
671
+ debug('Got plugins %j after sequencify', result);
672
+
673
+ // catch error when result.sequence is empty
674
+ if (!result.sequence.length) {
675
+ const err = new Error(
676
+ `sequencify plugins has problem, missing: [${result.missingTasks}], recursive: [${result.recursiveDependencies}]`);
677
+ // find plugins which is required by the missing plugin
678
+ for (const missName of result.missingTasks) {
679
+ const requires = [];
680
+ for (const name in allPlugins) {
681
+ if (allPlugins[name].dependencies.includes(missName)) {
682
+ requires.push(name);
683
+ }
684
+ }
685
+ err.message += `\n\t>> Plugin [${missName}] is disabled or missed, but is required by [${requires}]`;
686
+ }
687
+
688
+ err.name = 'PluginSequencifyError';
689
+ throw err;
690
+ }
691
+
692
+ // log the plugins that be enabled implicitly
693
+ const implicitEnabledPlugins: string[] = [];
694
+ const requireMap: Record<string, string[]> = {};
695
+ result.sequence.forEach(name => {
696
+ for (const depName of allPlugins[name].dependencies) {
697
+ if (!requireMap[depName]) {
698
+ requireMap[depName] = [];
699
+ }
700
+ requireMap[depName].push(name);
701
+ }
702
+
703
+ if (!allPlugins[name].enable) {
704
+ implicitEnabledPlugins.push(name);
705
+ allPlugins[name].enable = true;
706
+ allPlugins[name].implicitEnable = true;
707
+ }
708
+ });
709
+
710
+ for (const [ name, dependents ] of Object.entries(requireMap)) {
711
+ // note:`dependents` will not includes `optionalDependencies`
712
+ allPlugins[name].dependents = dependents;
713
+ }
714
+
715
+ // Following plugins will be enabled implicitly.
716
+ // - configclient required by [hsfclient]
717
+ // - eagleeye required by [hsfclient]
718
+ // - diamond required by [hsfclient]
719
+ if (implicitEnabledPlugins.length) {
720
+ let message = implicitEnabledPlugins
721
+ .map(name => ` - ${name} required by [${requireMap[name]}]`)
722
+ .join('\n');
723
+ this.options.logger.info(`Following plugins will be enabled implicitly.\n${message}`);
724
+
725
+ // should warn when the plugin is disabled by app
726
+ const disabledPlugins = implicitEnabledPlugins.filter(
727
+ name => appPlugins[name] && appPlugins[name].enable === false);
728
+ if (disabledPlugins.length) {
729
+ message = disabledPlugins
730
+ .map(name => ` - ${name} required by [${requireMap[name]}]`)
731
+ .join('\n');
732
+ this.options.logger.warn(
733
+ `Following plugins will be enabled implicitly that is disabled by application.\n${message}`);
734
+ }
735
+ }
736
+
737
+ return result.sequence.map(name => allPlugins[name]);
738
+ }
739
+
740
+ protected getLookupDirs() {
741
+ const lookupDirs = new Set<string>();
742
+
743
+ // try to locate the plugin in the following directories's node_modules
744
+ // -> {APP_PATH} -> {EGG_PATH} -> $CWD
745
+ lookupDirs.add(this.options.baseDir);
746
+
747
+ // try to locate the plugin at framework from upper to lower
748
+ for (let i = this.eggPaths.length - 1; i >= 0; i--) {
749
+ const eggPath = this.eggPaths[i];
750
+ lookupDirs.add(eggPath);
751
+ }
752
+
753
+ // should find the $cwd when test the plugins under npm3
754
+ lookupDirs.add(process.cwd());
755
+ return lookupDirs;
756
+ }
757
+
758
+ // Get the real plugin path
759
+ protected getPluginPath(plugin: EggPluginInfo) {
760
+ if (plugin.path) {
761
+ return plugin.path;
762
+ }
763
+
764
+ if (plugin.package) {
765
+ assert(isValidatePackageName(plugin.package),
766
+ `plugin ${plugin.name} invalid, use 'path' instead of package: "${plugin.package}"`);
767
+ }
768
+ return this.#resolvePluginPath(plugin);
769
+ }
770
+
771
+ #resolvePluginPath(plugin: EggPluginInfo) {
772
+ const name = plugin.package || plugin.name;
773
+
774
+ try {
775
+ // should find the plugin directory
776
+ // pnpm will lift the node_modules to the sibling directory
777
+ // 'node_modules/.pnpm/yadan@2.0.0/node_modules/yadan/node_modules',
778
+ // 'node_modules/.pnpm/yadan@2.0.0/node_modules', <- this is the sibling directory
779
+ // 'node_modules/.pnpm/egg@2.33.1/node_modules/egg/node_modules',
780
+ // 'node_modules/.pnpm/egg@2.33.1/node_modules', <- this is the sibling directory
781
+ const filePath = utils.resolvePath(`${name}/package.json`, { paths: [ ...this.lookupDirs ] });
782
+ return path.dirname(filePath);
783
+ } catch (err: any) {
784
+ debug('[resolvePluginPath] error: %o', err);
785
+ throw new Error(`Can not find plugin ${name} in "${[ ...this.lookupDirs ].join(', ')}"`);
786
+ }
787
+ }
788
+
789
+ #extendPlugins(targets: Record<string, EggPluginInfo>, plugins: Record<string, EggPluginInfo>) {
790
+ if (!plugins) {
791
+ return;
792
+ }
793
+ for (const name in plugins) {
794
+ const plugin = plugins[name];
795
+ let targetPlugin = targets[name];
796
+ if (!targetPlugin) {
797
+ targetPlugin = targets[name] = {} as EggPluginInfo;
798
+ }
799
+ if (targetPlugin.package && targetPlugin.package === plugin.package) {
800
+ this.logger.warn('[@eggjs/core] plugin %s has been defined that is %j, but you define again in %s',
801
+ name, targetPlugin, plugin.from);
802
+ }
803
+ if (plugin.path || plugin.package) {
804
+ delete targetPlugin.path;
805
+ delete targetPlugin.package;
806
+ }
807
+ for (const [ prop, value ] of Object.entries(plugin)) {
808
+ if (value === undefined) {
809
+ continue;
810
+ }
811
+ if (Reflect.get(targetPlugin, prop) && Array.isArray(value) && !value.length) {
812
+ continue;
813
+ }
814
+ Reflect.set(targetPlugin, prop, value);
815
+ }
816
+ }
817
+ }
818
+ /** end Plugin loader */
819
+
820
+ /** start Config loader */
821
+ configMeta: Record<string, any>;
822
+ config: Record<string, any>;
823
+
824
+ /**
825
+ * Load config/config.js
826
+ *
827
+ * Will merge config.default.js 和 config.${env}.js
828
+ *
829
+ * @function EggLoader#loadConfig
830
+ * @since 1.0.0
831
+ */
832
+ async loadConfig() {
833
+ this.timing.start('Load Config');
834
+ this.configMeta = {};
835
+
836
+ const target: Record<string, any> = {};
837
+
838
+ // Load Application config first
839
+ const appConfig = await this.#preloadAppConfig();
840
+
841
+ // plugin config.default
842
+ // framework config.default
843
+ // app config.default
844
+ // plugin config.{env}
845
+ // framework config.{env}
846
+ // app config.{env}
847
+ for (const filename of this.getTypeFiles('config')) {
848
+ for (const unit of this.getLoadUnits()) {
849
+ const isApp = unit.type === 'app';
850
+ const config = await this.#loadConfig(
851
+ unit.path, filename, isApp ? undefined : appConfig, unit.type);
852
+ if (!config) {
853
+ continue;
854
+ }
855
+ debug('[loadConfig] Loaded config %s/%s, %j', unit.path, filename, config);
856
+ extend(true, target, config);
857
+ }
858
+ }
859
+
860
+ // load env from process.env.EGG_APP_CONFIG
861
+ const envConfig = this.#loadConfigFromEnv();
862
+ debug('[loadConfig] Loaded config from env, %j', envConfig);
863
+ extend(true, target, envConfig);
864
+
865
+ // You can manipulate the order of app.config.coreMiddleware and app.config.appMiddleware in app.js
866
+ target.coreMiddleware = target.coreMiddlewares = target.coreMiddleware || [];
867
+ target.appMiddleware = target.appMiddlewares = target.middleware || [];
868
+
869
+ this.config = target;
870
+ debug('[loadConfig] all config: %o', this.config);
871
+ this.timing.end('Load Config');
872
+ }
873
+
874
+ async #preloadAppConfig() {
875
+ const names = [
876
+ 'config.default',
877
+ `config.${this.serverEnv}`,
878
+ ];
879
+ const target: Record<string, any> = {};
880
+ for (const filename of names) {
881
+ const config = await this.#loadConfig(this.options.baseDir, filename, undefined, 'app');
882
+ if (!config) {
883
+ continue;
884
+ }
885
+ extend(true, target, config);
886
+ }
887
+ return target;
888
+ }
889
+
890
+ async #loadConfig(dirpath: string, filename: string, extraInject: object | undefined, type: EggDirInfoType) {
891
+ const isPlugin = type === 'plugin';
892
+ const isApp = type === 'app';
893
+
894
+ let filepath = this.resolveModule(path.join(dirpath, 'config', filename));
895
+ // let config.js compatible
896
+ if (filename === 'config.default' && !filepath) {
897
+ filepath = this.resolveModule(path.join(dirpath, 'config/config'));
898
+ }
899
+ const config: Record<string, any> = await this.loadFile(filepath!, this.appInfo, extraInject);
900
+ if (!config) return;
901
+ if (isPlugin || isApp) {
902
+ assert(!config.coreMiddleware, 'Can not define coreMiddleware in app or plugin');
903
+ }
904
+ if (!isApp) {
905
+ assert(!config.middleware, 'Can not define middleware in ' + filepath);
906
+ }
907
+ // store config meta, check where is the property of config come from.
908
+ this.#setConfigMeta(config, filepath!);
909
+ return config;
910
+ }
911
+
912
+ #loadConfigFromEnv() {
913
+ const envConfigStr = process.env.EGG_APP_CONFIG;
914
+ if (!envConfigStr) return;
915
+ try {
916
+ const envConfig: Record<string, any> = JSON.parse(envConfigStr);
917
+ this.#setConfigMeta(envConfig, '<process.env.EGG_APP_CONFIG>');
918
+ return envConfig;
919
+ } catch (err) {
920
+ this.options.logger.warn('[egg-loader] process.env.EGG_APP_CONFIG is not invalid JSON: %s', envConfigStr);
921
+ }
922
+ }
923
+
924
+ #setConfigMeta(config: Record<string, any>, filepath: string) {
925
+ config = extend(true, {}, config);
926
+ this.#setConfig(config, filepath);
927
+ extend(true, this.configMeta, config);
928
+ }
929
+
930
+ #setConfig(obj: Record<string, any>, filepath: string) {
931
+ for (const key of Object.keys(obj)) {
932
+ const val = obj[key];
933
+ // ignore console
934
+ if (key === 'console' && val && typeof val.Console === 'function' && val.Console === console.Console) {
935
+ obj[key] = filepath;
936
+ continue;
937
+ }
938
+ if (val && Object.getPrototypeOf(val) === Object.prototype && Object.keys(val).length > 0) {
939
+ this.#setConfig(val, filepath);
940
+ continue;
941
+ }
942
+ obj[key] = filepath;
943
+ }
944
+ }
945
+ /** end Config loader */
946
+
947
+ /** start Extend loader */
948
+ /**
949
+ * mixin Agent.prototype
950
+ * @function EggLoader#loadAgentExtend
951
+ * @since 1.0.0
952
+ */
953
+ async loadAgentExtend() {
954
+ await this.loadExtend('agent', this.app);
955
+ }
956
+
957
+ /**
958
+ * mixin Application.prototype
959
+ * @function EggLoader#loadApplicationExtend
960
+ * @since 1.0.0
961
+ */
962
+ async loadApplicationExtend() {
963
+ await this.loadExtend('application', this.app);
964
+ }
965
+
966
+ /**
967
+ * mixin Request.prototype
968
+ * @function EggLoader#loadRequestExtend
969
+ * @since 1.0.0
970
+ */
971
+ async loadRequestExtend() {
972
+ await this.loadExtend('request', this.app.request);
973
+ }
974
+
975
+ /**
976
+ * mixin Response.prototype
977
+ * @function EggLoader#loadResponseExtend
978
+ * @since 1.0.0
979
+ */
980
+ async loadResponseExtend() {
981
+ await this.loadExtend('response', this.app.response);
982
+ }
983
+
984
+ /**
985
+ * mixin Context.prototype
986
+ * @function EggLoader#loadContextExtend
987
+ * @since 1.0.0
988
+ */
989
+ async loadContextExtend() {
990
+ await this.loadExtend('context', this.app.context);
991
+ }
992
+
993
+ /**
994
+ * mixin app.Helper.prototype
995
+ * @function EggLoader#loadHelperExtend
996
+ * @since 1.0.0
997
+ */
998
+ async loadHelperExtend() {
999
+ if (this.app.Helper) {
1000
+ await this.loadExtend('helper', this.app.Helper.prototype);
1001
+ }
1002
+ }
1003
+
1004
+ /**
1005
+ * Find all extend file paths by name
1006
+ * can be override in top level framework to support load `app/extends/{name}.js`
1007
+ *
1008
+ * @param {String} name - filename which may be `app/extend/{name}.js`
1009
+ * @return {Array} filepaths extend file paths
1010
+ * @private
1011
+ */
1012
+ protected getExtendFilePaths(name: string): string[] {
1013
+ return this.getLoadUnits().map(unit => path.join(unit.path, 'app/extend', name));
1014
+ }
1015
+
1016
+ /**
1017
+ * Loader app/extend/xx.js to `prototype`,
1018
+ * @function loadExtend
1019
+ * @param {String} name - filename which may be `app/extend/{name}.js`
1020
+ * @param {Object} proto - prototype that mixed
1021
+ * @since 1.0.0
1022
+ */
1023
+ async loadExtend(name: string, proto: object) {
1024
+ this.timing.start(`Load extend/${name}.js`);
1025
+ // All extend files
1026
+ const filepaths = this.getExtendFilePaths(name);
1027
+ // if use mm.env and serverEnv is not unittest
1028
+ const needUnittest = 'EGG_MOCK_SERVER_ENV' in process.env && this.serverEnv !== 'unittest';
1029
+ const length = filepaths.length;
1030
+ for (let i = 0; i < length; i++) {
1031
+ const filepath = filepaths[i];
1032
+ filepaths.push(filepath + `.${this.serverEnv}`);
1033
+ if (needUnittest) {
1034
+ filepaths.push(filepath + '.unittest');
1035
+ }
1036
+ }
1037
+ debug('loadExtend %s, filepaths: %j', name, filepaths);
1038
+
1039
+ const mergeRecord = new Map();
1040
+ for (let filepath of filepaths) {
1041
+ filepath = this.resolveModule(filepath)!;
1042
+ if (!filepath) {
1043
+ continue;
1044
+ }
1045
+ if (filepath.endsWith('/index.js')) {
1046
+ this.app.deprecate(`app/extend/${name}/index.js is deprecated, use app/extend/${name}.js instead`);
1047
+ } else if (filepath.endsWith('/index.ts')) {
1048
+ this.app.deprecate(`app/extend/${name}/index.ts is deprecated, use app/extend/${name}.ts instead`);
1049
+ }
1050
+
1051
+ const ext = await this.requireFile(filepath);
1052
+ const properties = Object.getOwnPropertyNames(ext)
1053
+ .concat(Object.getOwnPropertySymbols(ext) as any[]);
1054
+
1055
+ for (const property of properties) {
1056
+ if (mergeRecord.has(property)) {
1057
+ debug('Property: "%s" already exists in "%s",it will be redefined by "%s"',
1058
+ property, mergeRecord.get(property), filepath);
1059
+ }
1060
+
1061
+ // Copy descriptor
1062
+ let descriptor = Object.getOwnPropertyDescriptor(ext, property);
1063
+ let originalDescriptor = Object.getOwnPropertyDescriptor(proto, property);
1064
+ if (!originalDescriptor) {
1065
+ // try to get descriptor from originalPrototypes
1066
+ const originalProto = originalPrototypes[name];
1067
+ if (originalProto) {
1068
+ originalDescriptor = Object.getOwnPropertyDescriptor(originalProto, property);
1069
+ }
1070
+ }
1071
+ if (originalDescriptor) {
1072
+ // don't override descriptor
1073
+ descriptor = {
1074
+ ...descriptor,
1075
+ };
1076
+ if (!descriptor.set && originalDescriptor.set) {
1077
+ descriptor.set = originalDescriptor.set;
1078
+ }
1079
+ if (!descriptor.get && originalDescriptor.get) {
1080
+ descriptor.get = originalDescriptor.get;
1081
+ }
1082
+ }
1083
+ Object.defineProperty(proto, property, descriptor!);
1084
+ mergeRecord.set(property, filepath);
1085
+ }
1086
+ debug('merge %j to %s from %s', Object.keys(ext), name, filepath);
1087
+ }
1088
+ this.timing.end(`Load extend/${name}.js`);
1089
+ }
1090
+ /** end Extend loader */
1091
+
1092
+ /** start Custom loader */
1093
+ /**
1094
+ * load app.js
1095
+ *
1096
+ * @example
1097
+ * - old:
1098
+ *
1099
+ * ```js
1100
+ * module.exports = function(app) {
1101
+ * doSomething();
1102
+ * }
1103
+ * ```
1104
+ *
1105
+ * - new:
1106
+ *
1107
+ * ```js
1108
+ * module.exports = class Boot {
1109
+ * constructor(app) {
1110
+ * this.app = app;
1111
+ * }
1112
+ * configDidLoad() {
1113
+ * doSomething();
1114
+ * }
1115
+ * }
1116
+ * @since 1.0.0
1117
+ */
1118
+ async loadCustomApp() {
1119
+ await this.#loadBootHook('app');
1120
+ this.lifecycle.triggerConfigWillLoad();
1121
+ }
1122
+
1123
+ /**
1124
+ * Load agent.js, same as {@link EggLoader#loadCustomApp}
1125
+ */
1126
+ async loadCustomAgent() {
1127
+ await this.#loadBootHook('agent');
1128
+ this.lifecycle.triggerConfigWillLoad();
1129
+ }
1130
+
1131
+ // FIXME: no logger used after egg removed
1132
+ loadBootHook() {
1133
+ // do nothing
1134
+ }
1135
+
1136
+ async #loadBootHook(fileName: string) {
1137
+ this.timing.start(`Load ${fileName}.js`);
1138
+ for (const unit of this.getLoadUnits()) {
1139
+ const bootFilePath = this.resolveModule(path.join(unit.path, fileName));
1140
+ if (!bootFilePath) {
1141
+ continue;
1142
+ }
1143
+ const bootHook = await this.requireFile(bootFilePath);
1144
+ if (isClass(bootHook)) {
1145
+ bootHook.prototype.fullPath = bootFilePath;
1146
+ // if is boot class, add to lifecycle
1147
+ this.lifecycle.addBootHook(bootHook);
1148
+ } else if (typeof bootHook === 'function') {
1149
+ // if is boot function, wrap to class
1150
+ // for compatibility
1151
+ this.lifecycle.addFunctionAsBootHook(bootHook);
1152
+ } else {
1153
+ this.options.logger.warn('[@eggjs/core:egg_loader] %s must exports a boot class', bootFilePath);
1154
+ }
1155
+ }
1156
+ // init boots
1157
+ this.lifecycle.init();
1158
+ this.timing.end(`Load ${fileName}.js`);
1159
+ }
1160
+ /** end Custom loader */
1161
+
1162
+ /** start Service loader */
1163
+ /**
1164
+ * Load app/service
1165
+ * @function EggLoader#loadService
1166
+ * @param {Object} options - LoaderOptions
1167
+ * @since 1.0.0
1168
+ */
1169
+ async loadService(options?: Partial<ContextLoaderOptions>) {
1170
+ this.timing.start('Load Service');
1171
+ // 载入到 app.serviceClasses
1172
+ const servicePaths = this.getLoadUnits().map(unit => path.join(unit.path, 'app/service'));
1173
+ options = {
1174
+ call: true,
1175
+ caseStyle: 'lower',
1176
+ fieldClass: 'serviceClasses',
1177
+ directory: servicePaths,
1178
+ ...options,
1179
+ };
1180
+ debug('[loadService] options: %o', options);
1181
+ await this.loadToContext(servicePaths, 'service', options as ContextLoaderOptions);
1182
+ this.timing.end('Load Service');
1183
+ }
1184
+ /** end Service loader */
1185
+
1186
+ /** start Middleware loader */
1187
+ /**
1188
+ * Load app/middleware
1189
+ *
1190
+ * app.config.xx is the options of the middleware xx that has same name as config
1191
+ *
1192
+ * @function EggLoader#loadMiddleware
1193
+ * @param {Object} opt - LoaderOptions
1194
+ * @example
1195
+ * ```js
1196
+ * // app/middleware/status.js
1197
+ * module.exports = function(options, app) {
1198
+ * // options == app.config.status
1199
+ * return async next => {
1200
+ * await next();
1201
+ * }
1202
+ * }
1203
+ * ```
1204
+ * @since 1.0.0
1205
+ */
1206
+ async loadMiddleware(opt?: Partial<FileLoaderOptions>) {
1207
+ this.timing.start('Load Middleware');
1208
+ const app = this.app;
1209
+
1210
+ // load middleware to app.middleware
1211
+ const middlewarePaths = this.getLoadUnits().map(unit => path.join(unit.path, 'app/middleware'));
1212
+ opt = {
1213
+ call: false,
1214
+ override: true,
1215
+ caseStyle: 'lower',
1216
+ directory: middlewarePaths,
1217
+ ...opt,
1218
+ };
1219
+ await this.loadToApp(middlewarePaths, 'middlewares', opt as FileLoaderOptions);
1220
+
1221
+ for (const name in app.middlewares) {
1222
+ Object.defineProperty(app.middleware, name, {
1223
+ get() {
1224
+ return app.middlewares[name];
1225
+ },
1226
+ enumerable: false,
1227
+ configurable: false,
1228
+ });
1229
+ }
1230
+
1231
+ this.options.logger.info('Use coreMiddleware order: %j', this.config.coreMiddleware);
1232
+ this.options.logger.info('Use appMiddleware order: %j', this.config.appMiddleware);
1233
+
1234
+ // use middleware ordered by app.config.coreMiddleware and app.config.appMiddleware
1235
+ const middlewareNames = this.config.coreMiddleware.concat(this.config.appMiddleware);
1236
+ debug('[loadMiddleware] middlewareNames: %j', middlewareNames);
1237
+ const middlewaresMap = new Map<string, boolean>();
1238
+ for (const name of middlewareNames) {
1239
+ const createMiddleware = app.middlewares[name];
1240
+ if (!createMiddleware) {
1241
+ throw new TypeError(`Middleware ${name} not found`);
1242
+ }
1243
+ if (middlewaresMap.has(name)) {
1244
+ throw new TypeError(`Middleware ${name} redefined`);
1245
+ }
1246
+ middlewaresMap.set(name, true);
1247
+ const options = this.config[name] || {};
1248
+ let mw: MiddlewareFunc | null = createMiddleware(options, app);
1249
+ assert(typeof mw === 'function', `Middleware ${name} must be a function, but actual is ${inspect(mw)}`);
1250
+ if (isGeneratorFunction(mw)) {
1251
+ const fullpath = Reflect.get(createMiddleware, FULLPATH);
1252
+ throw new TypeError(`Support for generators was removed, middleware: ${name}, fullpath: ${fullpath}`);
1253
+ }
1254
+ mw._name = name;
1255
+ // middlewares support options.enable, options.ignore and options.match
1256
+ mw = wrapMiddleware(mw, options);
1257
+ if (mw) {
1258
+ if (debug.enabled) {
1259
+ // show mw debug log on every request
1260
+ mw = debugMiddlewareWrapper(mw);
1261
+ }
1262
+ app.use(mw);
1263
+ debug('[loadMiddleware] Use middleware: %s with options: %j', name, options);
1264
+ this.options.logger.info('[@eggjs/core:egg_loader] Use middleware: %s', name);
1265
+ } else {
1266
+ this.options.logger.info('[@eggjs/core:egg_loader] Disable middleware: %s', name);
1267
+ }
1268
+ }
1269
+
1270
+ this.options.logger.info('[@eggjs/core:egg_loader] Loaded middleware from %j', middlewarePaths);
1271
+ this.timing.end('Load Middleware');
1272
+ }
1273
+ /** end Middleware loader */
1274
+
1275
+ /** start Controller loader */
1276
+ /**
1277
+ * Load app/controller
1278
+ * @param {Object} opt - LoaderOptions
1279
+ * @since 1.0.0
1280
+ */
1281
+ async loadController(opt?: Partial<FileLoaderOptions>) {
1282
+ this.timing.start('Load Controller');
1283
+ const controllerBase = path.join(this.options.baseDir, 'app/controller');
1284
+ opt = {
1285
+ caseStyle: 'lower',
1286
+ directory: controllerBase,
1287
+ initializer: (obj, opt) => {
1288
+ // return class if it exports a function
1289
+ // ```js
1290
+ // module.exports = app => {
1291
+ // return class HomeController extends app.Controller {};
1292
+ // }
1293
+ // ```
1294
+ if (isGeneratorFunction(obj)) {
1295
+ throw new TypeError(`Support for generators was removed, fullpath: ${opt.path}`);
1296
+ }
1297
+ if (!isClass(obj) && !isAsyncFunction(obj)) {
1298
+ if (typeof obj === 'function') {
1299
+ obj = obj(this.app);
1300
+ debug('[loadController] after init(app) => %o, meta: %j', obj, opt);
1301
+ if (isGeneratorFunction(obj)) {
1302
+ throw new TypeError(`Support for generators was removed, fullpath: ${opt.path}`);
1303
+ }
1304
+ }
1305
+ }
1306
+ if (isClass(obj)) {
1307
+ obj.prototype.pathName = opt.pathName;
1308
+ obj.prototype.fullPath = opt.path;
1309
+ return wrapControllerClass(obj, opt.path);
1310
+ }
1311
+ if (isObject(obj)) {
1312
+ return wrapObject(obj, opt.path);
1313
+ }
1314
+ if (isAsyncFunction(obj)) {
1315
+ return wrapObject({ 'module.exports': obj }, opt.path)['module.exports'];
1316
+ }
1317
+ return obj;
1318
+ },
1319
+ ...opt,
1320
+ };
1321
+ await this.loadToApp(controllerBase, 'controller', opt as FileLoaderOptions);
1322
+ debug('[loadController] app.controller => %o', this.app.controller);
1323
+ this.options.logger.info('[@eggjs/core:egg_loader] Controller loaded: %s', controllerBase);
1324
+ this.timing.end('Load Controller');
1325
+ }
1326
+ /** end Controller loader */
1327
+
1328
+ /** start Router loader */
1329
+ /**
1330
+ * Load app/router.js
1331
+ * @function EggLoader#loadRouter
1332
+ * @since 1.0.0
1333
+ */
1334
+ async loadRouter() {
1335
+ this.timing.start('Load Router');
1336
+ await this.loadFile(path.join(this.options.baseDir, 'app/router'));
1337
+ // add router middleware
1338
+ const mw = this.app.router.middleware();
1339
+ Reflect.set(mw, '_name', 'routerMiddleware');
1340
+ this.app.use(mw);
1341
+ this.timing.end('Load Router');
1342
+ }
1343
+ /** end Router loader */
1344
+
1345
+ /** start CustomLoader loader */
1346
+ async loadCustomLoader() {
1347
+ assert(this.config, 'should loadConfig first');
1348
+ const customLoader = this.config.customLoader || {};
1349
+
1350
+ for (const property of Object.keys(customLoader)) {
1351
+ const loaderConfig = {
1352
+ ...customLoader[property],
1353
+ };
1354
+ assert(loaderConfig.directory, `directory is required for config.customLoader.${property}`);
1355
+ let directory: string | string[];
1356
+ if (loaderConfig.loadunit === true) {
1357
+ directory = this.getLoadUnits().map(unit => path.join(unit.path, loaderConfig.directory));
1358
+ } else {
1359
+ directory = path.join(this.appInfo.baseDir, loaderConfig.directory);
1360
+ }
1361
+ const inject = loaderConfig.inject || 'app';
1362
+ debug('[loadCustomLoader] loaderConfig: %o, inject: %o, directory: %o',
1363
+ loaderConfig, inject, directory);
1364
+
1365
+ switch (inject) {
1366
+ case 'ctx': {
1367
+ assert(!(property in this.app.context), `customLoader should not override ctx.${property}`);
1368
+ const options = {
1369
+ caseStyle: 'lower',
1370
+ fieldClass: `${property}Classes`,
1371
+ ...loaderConfig,
1372
+ directory,
1373
+ };
1374
+ await this.loadToContext(directory, property, options);
1375
+ break;
1376
+ }
1377
+ case 'app': {
1378
+ assert(!(property in this.app), `customLoader should not override app.${property}`);
1379
+ const options = {
1380
+ caseStyle: 'lower',
1381
+ initializer: (Clazz: unknown) => {
1382
+ return isClass(Clazz) ? new Clazz(this.app) : Clazz;
1383
+ },
1384
+ ...loaderConfig,
1385
+ directory,
1386
+ };
1387
+ await this.loadToApp(directory, property, options);
1388
+ break;
1389
+ }
1390
+ default:
1391
+ throw new Error('inject only support app or ctx');
1392
+ }
1393
+ }
1394
+ }
1395
+ /** end CustomLoader loader */
1396
+
1397
+ // Low Level API
1398
+
1399
+ /**
1400
+ * Load single file, will invoke when export is function
1401
+ *
1402
+ * @param {String} filepath - fullpath
1403
+ * @param {Array} inject - pass rest arguments into the function when invoke
1404
+ * @return {Object} exports
1405
+ * @example
1406
+ * ```js
1407
+ * app.loader.loadFile(path.join(app.options.baseDir, 'config/router.js'));
1408
+ * ```
1409
+ * @since 1.0.0
1410
+ */
1411
+ async loadFile(filepath: string, ...inject: any[]) {
1412
+ const fullpath = filepath && this.resolveModule(filepath);
1413
+ if (!fullpath) {
1414
+ return null;
1415
+ }
1416
+
1417
+ // function(arg1, args, ...) {}
1418
+ if (inject.length === 0) {
1419
+ inject = [ this.app ];
1420
+ }
1421
+ let mod = await this.requireFile(fullpath);
1422
+ if (typeof mod === 'function' && !isClass(mod)) {
1423
+ mod = mod(...inject);
1424
+ }
1425
+ return mod;
1426
+ }
1427
+
1428
+ /**
1429
+ * @param {String} filepath - fullpath
1430
+ * @return {Object} exports
1431
+ * @private
1432
+ */
1433
+ async requireFile(filepath: string) {
1434
+ const timingKey = `Require(${this.#requiredCount++}) ${utils.getResolvedFilename(filepath, this.options.baseDir)}`;
1435
+ this.timing.start(timingKey);
1436
+ const mod = await utils.loadFile(filepath);
1437
+ this.timing.end(timingKey);
1438
+ return mod;
1439
+ }
1440
+
1441
+ /**
1442
+ * Get all loadUnit
1443
+ *
1444
+ * loadUnit is a directory that can be loaded by EggLoader, it has the same structure.
1445
+ * loadUnit has a path and a type(app, framework, plugin).
1446
+ *
1447
+ * The order of the loadUnits:
1448
+ *
1449
+ * 1. plugin
1450
+ * 2. framework
1451
+ * 3. app
1452
+ *
1453
+ * @return {Array} loadUnits
1454
+ * @since 1.0.0
1455
+ */
1456
+ getLoadUnits(): EggDirInfo[] {
1457
+ if (this.dirs) {
1458
+ return this.dirs;
1459
+ }
1460
+
1461
+ this.dirs = [];
1462
+
1463
+ if (this.orderPlugins) {
1464
+ for (const plugin of this.orderPlugins) {
1465
+ this.dirs.push({
1466
+ path: plugin.path!,
1467
+ type: 'plugin',
1468
+ });
1469
+ }
1470
+ }
1471
+
1472
+ // framework or egg path
1473
+ for (const eggPath of this.eggPaths) {
1474
+ this.dirs.push({
1475
+ path: eggPath,
1476
+ type: 'framework',
1477
+ });
1478
+ }
1479
+
1480
+ // application
1481
+ this.dirs.push({
1482
+ path: this.options.baseDir,
1483
+ type: 'app',
1484
+ });
1485
+
1486
+ debug('Loaded dirs %j', this.dirs);
1487
+ return this.dirs;
1488
+ }
1489
+
1490
+ /**
1491
+ * Load files using {@link FileLoader}, inject to {@link Application}
1492
+ * @param {String|Array} directory - see {@link FileLoader}
1493
+ * @param {String} property - see {@link FileLoader}
1494
+ * @param {Object} options - see {@link FileLoader}
1495
+ * @since 1.0.0
1496
+ */
1497
+ async loadToApp(directory: string | string[], property: string, options: FileLoaderOptions) {
1498
+ const target = {};
1499
+ Reflect.set(this.app, property, target);
1500
+ options = {
1501
+ ...options,
1502
+ directory: options.directory ?? directory,
1503
+ target,
1504
+ inject: this.app,
1505
+ };
1506
+
1507
+ const timingKey = `Load "${String(property)}" to Application`;
1508
+ this.timing.start(timingKey);
1509
+ await new FileLoader(options).load();
1510
+ this.timing.end(timingKey);
1511
+ }
1512
+
1513
+ /**
1514
+ * Load files using {@link ContextLoader}
1515
+ * @param {String|Array} directory - see {@link ContextLoader}
1516
+ * @param {String} property - see {@link ContextLoader}
1517
+ * @param {Object} options - see {@link ContextLoader}
1518
+ * @since 1.0.0
1519
+ */
1520
+ async loadToContext(directory: string | string[], property: string, options?: ContextLoaderOptions) {
1521
+ options = {
1522
+ ...options,
1523
+ directory: options?.directory || directory,
1524
+ property,
1525
+ inject: this.app,
1526
+ };
1527
+
1528
+ const timingKey = `Load "${String(property)}" to Context`;
1529
+ this.timing.start(timingKey);
1530
+ await new ContextLoader(options).load();
1531
+ this.timing.end(timingKey);
1532
+ }
1533
+
1534
+ /**
1535
+ * @member {FileLoader} EggLoader#FileLoader
1536
+ * @since 1.0.0
1537
+ */
1538
+ get FileLoader() {
1539
+ return FileLoader;
1540
+ }
1541
+
1542
+ /**
1543
+ * @member {ContextLoader} EggLoader#ContextLoader
1544
+ * @since 1.0.0
1545
+ */
1546
+ get ContextLoader() {
1547
+ return ContextLoader;
1548
+ }
1549
+
1550
+ getTypeFiles(filename: string) {
1551
+ const files = [ `${filename}.default` ];
1552
+ if (this.serverScope) files.push(`${filename}.${this.serverScope}`);
1553
+ if (this.serverEnv === 'default') return files;
1554
+ files.push(`${filename}.${this.serverEnv}`);
1555
+ if (this.serverScope) {
1556
+ files.push(`${filename}.${this.serverScope}_${this.serverEnv}`);
1557
+ }
1558
+ return files;
1559
+ }
1560
+
1561
+ resolveModule(filepath: string) {
1562
+ let fullPath;
1563
+ try {
1564
+ fullPath = utils.resolvePath(filepath);
1565
+ } catch (e) {
1566
+ return undefined;
1567
+ }
1568
+
1569
+ if (process.env.EGG_TYPESCRIPT !== 'true' && fullPath.endsWith('.ts')) {
1570
+ return undefined;
1571
+ }
1572
+ return fullPath;
1573
+ }
1574
+ }
1575
+
1576
+ function depCompatible(plugin: EggPluginInfo & { dep?: string[] }) {
1577
+ if (plugin.dep && !(Array.isArray(plugin.dependencies) && plugin.dependencies.length)) {
1578
+ plugin.dependencies = plugin.dep;
1579
+ delete plugin.dep;
1580
+ }
1581
+ }
1582
+
1583
+ function isValidatePackageName(name: string) {
1584
+ // only check file path style
1585
+ if (name.startsWith('.')) return false;
1586
+ if (name.startsWith('/')) return false;
1587
+ if (name.includes(':')) return false;
1588
+ return true;
1589
+ }
1590
+
1591
+ // support pathMatching on middleware
1592
+ function wrapMiddleware(mw: MiddlewareFunc,
1593
+ options: PathMatchingOptions & { enable?: boolean }): MiddlewareFunc | null {
1594
+ // support options.enable
1595
+ if (options.enable === false) {
1596
+ return null;
1597
+ }
1598
+
1599
+ // support options.match and options.ignore
1600
+ if (!options.match && !options.ignore) {
1601
+ return mw;
1602
+ }
1603
+ const match = pathMatching(options);
1604
+
1605
+ const fn = (ctx: EggCoreContext, next: Next) => {
1606
+ if (!match(ctx)) return next();
1607
+ return mw(ctx, next);
1608
+ };
1609
+ fn._name = `${mw._name}middlewareWrapper`;
1610
+ return fn;
1611
+ }
1612
+
1613
+ function debugMiddlewareWrapper(mw: MiddlewareFunc): MiddlewareFunc {
1614
+ const fn = async (ctx: EggCoreContext, next: Next) => {
1615
+ const startTime = now();
1616
+ debug('[debugMiddlewareWrapper] [%s %s] enter middleware: %s', ctx.method, ctx.url, mw._name);
1617
+ await mw(ctx, next);
1618
+ const rt = diff(startTime);
1619
+ debug('[debugMiddlewareWrapper] [%s %s] after middleware: %s [%sms]', ctx.method, ctx.url, mw._name, rt);
1620
+ };
1621
+ fn._name = `${mw._name}DebugWrapper`;
1622
+ return fn;
1623
+ }
1624
+
1625
+ // wrap the controller class, yield a object with middlewares
1626
+ function wrapControllerClass(Controller: typeof BaseContextClass, fullPath: string) {
1627
+ let proto = Controller.prototype;
1628
+ const ret: Record<string, any> = {};
1629
+ // tracing the prototype chain
1630
+ while (proto !== Object.prototype) {
1631
+ const keys = Object.getOwnPropertyNames(proto);
1632
+ for (const key of keys) {
1633
+ // getOwnPropertyNames will return constructor
1634
+ // that should be ignored
1635
+ if (key === 'constructor') {
1636
+ continue;
1637
+ }
1638
+ // skip getter, setter & non-function properties
1639
+ const d = Object.getOwnPropertyDescriptor(proto, key);
1640
+ // prevent to override sub method
1641
+ if (typeof d?.value === 'function' && !ret.hasOwnProperty(key)) {
1642
+ const controllerMethodName = `${Controller.name}.${key}`;
1643
+ if (isGeneratorFunction(d.value)) {
1644
+ throw new TypeError(
1645
+ `Support for generators was removed, controller \`${controllerMethodName}\`, fullpath: ${fullPath}`);
1646
+ }
1647
+ ret[key] = controllerMethodToMiddleware(Controller, key);
1648
+ ret[key][FULLPATH] = `${fullPath}#${controllerMethodName}()`;
1649
+ }
1650
+ }
1651
+ proto = Object.getPrototypeOf(proto);
1652
+ }
1653
+ return ret;
1654
+ }
1655
+
1656
+ function controllerMethodToMiddleware(Controller: typeof BaseContextClass, key: string) {
1657
+ return function classControllerMiddleware(this: EggCoreContext, ...args: any[]) {
1658
+ const controller: any = new Controller(this);
1659
+ if (!this.app.config.controller?.supportParams) {
1660
+ args = [ this ];
1661
+ }
1662
+ return controller[key](...args);
1663
+ };
1664
+ }
1665
+
1666
+ // wrap the method of the object, method can receive ctx as it's first argument
1667
+ function wrapObject(obj: Record<string, any>, fullPath: string, prefix?: string) {
1668
+ const keys = Object.keys(obj);
1669
+ const ret: Record<string, any> = {};
1670
+ prefix = prefix ?? '';
1671
+ for (const key of keys) {
1672
+ const controllerMethodName = `${prefix}${key}`;
1673
+ const item = obj[key];
1674
+ if (isGeneratorFunction(item)) {
1675
+ throw new TypeError(`Support for generators was removed, controller \`${controllerMethodName}\`, fullpath: ${fullPath}`);
1676
+ }
1677
+ if (typeof item === 'function') {
1678
+ const names = getParamNames(item);
1679
+ if (names[0] === 'next') {
1680
+ throw new Error(`controller \`${controllerMethodName}\` should not use next as argument from file ${fullPath}`);
1681
+ }
1682
+ ret[key] = objectFunctionToMiddleware(item);
1683
+ ret[key][FULLPATH] = `${fullPath}#${controllerMethodName}()`;
1684
+ } else if (isObject(item)) {
1685
+ ret[key] = wrapObject(item, fullPath, `${controllerMethodName}.`);
1686
+ }
1687
+ }
1688
+ debug('[wrapObject] fullPath: %s, prefix: %s => %o', fullPath, prefix, ret);
1689
+ return ret;
1690
+ }
1691
+
1692
+ function objectFunctionToMiddleware(func: Fun) {
1693
+ async function objectControllerMiddleware(this: EggCoreContext, ...args: any[]) {
1694
+ if (!this.app.config.controller?.supportParams) {
1695
+ args = [ this ];
1696
+ }
1697
+ return await func.apply(this, args);
1698
+ }
1699
+ for (const key in func) {
1700
+ Reflect.set(objectControllerMiddleware, key, Reflect.get(func, key));
1701
+ }
1702
+ return objectControllerMiddleware;
1703
+ }