@eggjs/core 6.4.1 → 6.6.0-beta.10

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