-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathegg_loader.ts
More file actions
1921 lines (1753 loc) · 60.4 KB
/
egg_loader.ts
File metadata and controls
1921 lines (1753 loc) · 60.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import assert from 'node:assert';
import fs from 'node:fs';
import path from 'node:path';
import { debuglog, inspect } from 'node:util';
import { extend } from '@eggjs/extend2';
import { Request, Response, Application, Context as KoaContext } from '@eggjs/koa';
import { pathMatching, type PathMatchingOptions } from '@eggjs/path-matching';
import { isESM, isSupportTypeScript } from '@eggjs/utils';
import type { Logger } from 'egg-logger';
import { isAsyncFunction, isClass, isGeneratorFunction, isObject, isPromise } from 'is-type-of';
import { homedir } from 'node-homedir';
import { now, diff } from 'performance-ms';
import { register as tsconfigPathsRegister } from 'tsconfig-paths';
import { getParamNames, readJSONSync, readJSON, exists } from 'utility';
import type { BaseContextClass } from '../base_context_class.ts';
import type { Context, EggCore, MiddlewareFunc } from '../egg.ts';
import type { Lifecycle } from '../lifecycle.ts';
import type { EggAppConfig, EggAppInfo, EggPluginInfo } from '../types.ts';
import utils, { type Fun } from '../utils/index.ts';
import { sequencify } from '../utils/sequencify.ts';
import { Timing } from '../utils/timing.ts';
import { type ContextLoaderOptions, ContextLoader } from './context_loader.ts';
import { type FileLoaderOptions, CaseStyle, FULLPATH, FileLoader } from './file_loader.ts';
import { ManifestStore, type ManifestTegg, type StartupManifest } from './manifest.ts';
const debug = debuglog('egg/core/loader/egg_loader');
const originalPrototypes: Record<string, unknown> = {
request: Request.prototype,
response: Response.prototype,
context: KoaContext.prototype,
application: Application.prototype,
};
export interface EggLoaderOptions {
/** server env */
env: string;
/** Application instance */
app: EggCore;
EggCoreClass?: typeof EggCore;
/** the directory of application */
baseDir: string;
/** egg logger */
logger: Logger;
/** server scope */
serverScope?: string;
/** custom plugins */
plugins?: Record<string, EggPluginInfo>;
}
export type EggDirInfoType = 'app' | 'plugin' | 'framework';
export interface EggDirInfo {
path: string;
type: EggDirInfoType;
}
export class EggLoader {
#requiredCount = 0;
readonly options: EggLoaderOptions;
readonly timing: Timing;
readonly pkg: Record<string, any>;
readonly eggPaths: string[];
readonly serverEnv: string;
readonly serverScope: string;
readonly appInfo: EggAppInfo;
readonly outDir?: string;
dirs?: EggDirInfo[];
/** Pre-computed startup manifest for skipping file I/O */
readonly manifest: ManifestStore | null;
/** Collected resolveModule results for manifest generation */
readonly resolveCacheCollector: Record<string, string | null> = {};
/** Collected file discovery results for manifest generation */
readonly fileDiscoveryCollector: Record<string, string[]> = {};
/** Collected tegg manifest data (populated by tegg plugin) */
teggManifestCollector?: ManifestTegg;
/**
* @class
* @param {Object} options - options
* @param {String} options.baseDir - the directory of application
* @param {EggCore} options.app - Application instance
* @param {Logger} options.logger - logger
* @param {Object} [options.plugins] - custom plugins
* @since 1.0.0
*/
constructor(options: EggLoaderOptions) {
this.options = options;
assert(fs.existsSync(this.options.baseDir), `${this.options.baseDir} not exists`);
assert(this.options.app, 'options.app is required');
assert(this.options.logger, 'options.logger is required');
this.timing = this.app.timing || new Timing();
/**
* @member {Object} EggLoader#pkg
* @see {@link AppInfo#pkg}
* @since 1.0.0
*/
this.pkg = readJSONSync(path.join(this.options.baseDir, 'package.json'));
this.outDir = this.#resolveOutDir();
// auto require('tsconfig-paths/register') on typescript app
// support env.EGG_TYPESCRIPT = true or { "egg": { "typescript": true } } on package.json
if (process.env.EGG_TYPESCRIPT === 'true' || (this.pkg.egg && this.pkg.egg.typescript)) {
// skip require tsconfig-paths if tsconfig.json not exists
const tsConfigFile = path.join(this.options.baseDir, 'tsconfig.json');
if (fs.existsSync(tsConfigFile)) {
// @ts-expect-error only cwd is required
tsconfigPathsRegister({ cwd: this.options.baseDir });
} else {
this.logger.info(
'[@eggjs/core/egg_loader] skip register "tsconfig-paths" because tsconfig.json not exists at %s',
tsConfigFile,
);
}
}
debug('-------------------- type: %s --------------------', this.app.type);
/**
* All framework directories.
*
* You can extend Application of egg, the entry point is options.app,
*
* loader will find all directories from the prototype of Application,
* you should define `Symbol.for('egg#eggPath')` property.
*
* ```ts
* // src/example.ts
* import { Application } from 'egg';
* class ExampleApplication extends Application {
* get [Symbol.for('egg#eggPath')]() {
* return baseDir;
* }
* }
* ```
* @member {Array} EggLoader#eggPaths
* @see EggLoader#getEggPaths
* @since 1.0.0
*/
this.eggPaths = this.getEggPaths();
debug('Loaded eggPaths %j', this.eggPaths);
/**
* @member {String} EggLoader#serverEnv
* @see AppInfo#env
* @since 1.0.0
*/
this.serverEnv = this.getServerEnv();
debug('Loaded serverEnv %j', this.serverEnv);
/**
* @member {String} EggLoader#serverScope
* @see AppInfo#serverScope
*/
this.serverScope = options.serverScope ?? this.getServerScope();
/**
* @member {AppInfo} EggLoader#appInfo
* @since 1.0.0
*/
this.appInfo = this.getAppInfo();
// Load pre-computed startup manifest if available
this.manifest = ManifestStore.load(this.options.baseDir, this.serverEnv, this.serverScope);
if (this.manifest) {
debug('startup manifest loaded, will skip redundant file I/O');
}
}
get app(): EggCore {
return this.options.app;
}
get lifecycle(): Lifecycle {
return this.app.lifecycle;
}
get logger(): Logger {
return this.options.logger;
}
/**
* Get {@link AppInfo#env}
* @returns {String} env
* @see AppInfo#env
* @private
* @since 1.0.0
*/
protected getServerEnv(): string {
let serverEnv = this.options.env;
const envPath = path.join(this.options.baseDir, 'config/env');
if (!serverEnv && fs.existsSync(envPath)) {
serverEnv = fs.readFileSync(envPath, 'utf8').trim();
}
if (!serverEnv && process.env.EGG_SERVER_ENV) {
serverEnv = process.env.EGG_SERVER_ENV;
}
if (serverEnv) {
serverEnv = serverEnv.trim();
} else {
// oxlint-disable-next-line eslint/no-lonely-if
if (process.env.NODE_ENV === 'test') {
serverEnv = 'unittest';
} else if (process.env.NODE_ENV === 'production') {
serverEnv = 'prod';
} else {
serverEnv = 'local';
}
}
return serverEnv;
}
/**
* Get {@link AppInfo#scope}
* @returns {String} serverScope
* @private
*/
protected getServerScope(): string {
return process.env.EGG_SERVER_SCOPE ?? '';
}
/**
* Get {@link AppInfo#name}
* @returns {String} appname
* @private
* @since 1.0.0
*/
getAppname(): string {
if (this.pkg.name) {
debug('Loaded appname(%s) from package.json', this.pkg.name);
return this.pkg.name;
}
const pkg = path.join(this.options.baseDir, 'package.json');
throw new Error(`name is required from ${pkg}`);
}
/**
* Get home directory
* @returns {String} home directory
* @since 3.4.0
*/
getHomedir(): string {
// EGG_HOME for test
return process.env.EGG_HOME || homedir() || '/home/admin';
}
/**
* Get app info
* @returns {AppInfo} appInfo
* @since 1.0.0
*/
protected getAppInfo(): EggAppInfo {
const env = this.serverEnv;
const scope = this.serverScope;
const home = this.getHomedir();
const baseDir = this.options.baseDir;
/**
* Meta information of the application
* @class AppInfo
*/
return {
/**
* The name of the application, retrieve from the name property in `package.json`.
* @member {String} AppInfo#name
*/
name: this.getAppname(),
/**
* The current directory, where the application code is.
* @member {String} AppInfo#baseDir
*/
baseDir,
/**
* The environment of the application, **it's not NODE_ENV**
*
* 1. from `$baseDir/config/env`
* 2. from EGG_SERVER_ENV
* 3. from NODE_ENV
*
* env | description
* --- | ---
* test | system integration testing
* prod | production
* local | local on your own computer
* unittest | unit test
*
* @member {String} AppInfo#env
* @see https://eggjs.org/zh-cn/basics/env.html
*/
env,
/**
* @member {String} AppInfo#scope
*/
scope,
/**
* The use directory, same as `process.env.HOME`
* @member {String} AppInfo#HOME
*/
HOME: home,
/**
* parsed from `package.json`
* @member {Object} AppInfo#pkg
*/
pkg: this.pkg,
/**
* The directory whether is baseDir or HOME depend on env.
* it's good for test when you want to write some file to HOME,
* but don't want to write to the real directory,
* so use root to write file to baseDir instead of HOME when unittest.
* keep root directory in baseDir when local and unittest
* @member {String} AppInfo#root
*/
root: env === 'local' || env === 'unittest' ? baseDir : home,
};
}
/**
* Get {@link EggLoader#eggPaths}
* @returns {Array} framework directories
* @see {@link EggLoader#eggPaths}
* @private
* @since 1.0.0
*/
protected getEggPaths(): string[] {
// avoid require recursively
const EggCore = this.options.EggCoreClass;
let eggPaths: string[] = [];
// @ts-expect-error customEggPaths is protected
if (this.app.customEggPaths) {
// @ts-expect-error customEggPaths is protected
eggPaths = this.app.customEggPaths();
}
// try to get egg paths from old way
let proto = this.app;
// Loop for the prototype chain
while (proto) {
proto = Object.getPrototypeOf(proto);
// stop the loop if
// - object extends Object
// - object extends EggCore
if (proto === Object.prototype || proto === EggCore?.prototype) {
break;
}
let eggPath: string;
eggPath = Reflect.get(proto, Symbol.for('egg#eggPath')) as string;
if (!eggPath) {
// if (EggCore) {
// throw new TypeError('Symbol.for(\'egg#eggPath\') is required on Application');
// }
continue;
}
if (this.app.deprecate) {
this.app.deprecate(
'Symbol.for(\'egg#eggPath\') is deprecated, please use "override the `customEggPaths()` method" instead',
);
}
assert(typeof eggPath === 'string', "Symbol.for('egg#eggPath') should be string");
assert(fs.existsSync(eggPath), `${eggPath} not exists`);
const realpath = fs.realpathSync(eggPath);
if (!eggPaths.includes(realpath)) {
eggPaths.unshift(realpath);
}
}
return eggPaths;
}
/** start Plugin loader */
lookupDirs: Set<string>;
eggPlugins: Record<string, EggPluginInfo>;
appPlugins: Record<string, EggPluginInfo>;
customPlugins: Record<string, EggPluginInfo>;
allPlugins: Record<string, EggPluginInfo>;
orderPlugins: EggPluginInfo[];
/** enable plugins */
plugins: Record<string, EggPluginInfo>;
/**
* Load config/plugin.js from {EggLoader#loadUnits}
*
* plugin.js is written below
*
* ```js
* {
* 'xxx-client': {
* enable: true,
* package: 'xxx-client',
* dep: [],
* env: [],
* },
* // short hand
* 'rds': false,
* 'depd': {
* enable: true,
* path: 'path/to/depd'
* }
* }
* ```
*
* If the plugin has path, Loader will find the module from it.
*
* Otherwise Loader will lookup follow the order by packageName
*
* 1. $APP_BASE/node_modules/${package}
* 2. $EGG_BASE/node_modules/${package}
*
* You can call `loader.plugins` that retrieve enabled plugins.
*
* ```js
* loader.plugins['xxx-client'] = {
* name: 'xxx-client', // the plugin name, it can be used in `dep`
* package: 'xxx-client', // the package name of plugin
* enable: true, // whether enabled
* path: 'path/to/xxx-client', // the directory of the plugin package
* dep: [], // the dependent plugins, you can use the plugin name
* env: [ 'local', 'unittest' ], // specify the serverEnv that only enable the plugin in it
* }
* ```
*
* `loader.allPlugins` can be used when retrieve all plugins.
* @function EggLoader#loadPlugin
* @since 1.0.0
*/
async loadPlugin(): Promise<void> {
this.timing.start('Load Plugin');
this.lookupDirs = this.getLookupDirs();
this.allPlugins = {};
this.eggPlugins = await this.loadEggPlugins();
this.appPlugins = await this.loadAppPlugins();
this.customPlugins = this.loadCustomPlugins();
this.#extendPlugins(this.allPlugins, this.eggPlugins);
this.#extendPlugins(this.allPlugins, this.appPlugins);
this.#extendPlugins(this.allPlugins, this.customPlugins);
const enabledPluginNames: string[] = []; // enabled plugins that configured explicitly
const plugins: Record<string, EggPluginInfo> = {};
const env = this.serverEnv;
for (const name in this.allPlugins) {
const plugin = this.allPlugins[name];
// resolve the real plugin.path based on plugin or package
plugin.path = this.getPluginPath(plugin);
// read plugin information from ${plugin.path}/package.json
if (!plugin.skipMerge) {
await this.#mergePluginConfig(plugin);
}
// disable the plugin that not match the serverEnv
if (env && plugin.env.length > 0 && !plugin.env.includes(env)) {
this.logger.info(
'[egg/core] Plugin %o is disabled by env unmatched, require env(%o) but got env is %o',
name,
plugin.env,
env,
);
plugin.enable = false;
continue;
}
plugins[name] = plugin;
if (plugin.enable) {
enabledPluginNames.push(name);
}
}
// retrieve the ordered plugins
this.orderPlugins = this.getOrderPlugins(plugins, enabledPluginNames, this.appPlugins);
const enablePlugins: Record<string, EggPluginInfo> = {};
for (const plugin of this.orderPlugins) {
enablePlugins[plugin.name] = plugin;
}
debug('Loaded enable plugins: %j', Object.keys(enablePlugins));
/**
* Retrieve enabled plugins
* @member {Object} EggLoader#plugins
* @since 1.0.0
*/
this.plugins = enablePlugins;
this.timing.end('Load Plugin');
}
protected async loadAppPlugins(): Promise<Record<string, EggPluginInfo>> {
// loader plugins from application
const appPlugins = await this.readPluginConfigs(path.join(this.options.baseDir, 'config/plugin.default'));
debug(
'Loaded app plugins: %j',
Object.keys(appPlugins).map((k) => `${k}:${appPlugins[k].enable}`),
);
return appPlugins;
}
protected async loadEggPlugins(): Promise<Record<string, EggPluginInfo>> {
// loader plugins from framework
const eggPluginConfigPaths = this.eggPaths.map((eggPath) => path.join(eggPath, 'config/plugin.default'));
const eggPlugins = await this.readPluginConfigs(eggPluginConfigPaths);
debug(
'Loaded egg plugins: %j',
Object.keys(eggPlugins).map((k) => `${k}:${eggPlugins[k].enable}`),
);
return eggPlugins;
}
protected loadCustomPlugins(): Record<string, EggPluginInfo> {
// loader plugins from process.env.EGG_PLUGINS
let customPlugins: Record<string, EggPluginInfo> = {};
const configPaths: string[] = [];
if (process.env.EGG_PLUGINS) {
try {
customPlugins = JSON.parse(process.env.EGG_PLUGINS);
configPaths.push('<process.env.EGG_PLUGINS>');
} catch (e) {
debug('parse EGG_PLUGINS failed, %s', e);
}
}
// loader plugins from options.plugins
if (this.options.plugins) {
customPlugins = {
...customPlugins,
...this.options.plugins,
};
configPaths.push('<options.plugins>');
}
if (customPlugins) {
const configPath = configPaths.join(' or ');
for (const name in customPlugins) {
this.#normalizePluginConfig(customPlugins, name, configPath);
}
debug('Loaded custom plugins: %o', customPlugins);
}
return customPlugins;
}
/*
* Read plugin.js from multiple directory
*/
protected async readPluginConfigs(configPaths: string[] | string): Promise<Record<string, EggPluginInfo>> {
if (!Array.isArray(configPaths)) {
configPaths = [configPaths];
}
// Get all plugin configurations
// plugin.default.js
// plugin.${scope}.js
// plugin.${env}.js
// plugin.${scope}_${env}.js
const newConfigPaths: string[] = [];
for (const filename of this.getTypeFiles('plugin')) {
for (let configPath of configPaths) {
configPath = path.join(path.dirname(configPath), filename);
newConfigPaths.push(configPath);
}
}
const plugins: Record<string, EggPluginInfo> = {};
for (const configPath of newConfigPaths) {
let filepath = this.resolveModule(configPath);
// let plugin.js compatible
if (configPath.endsWith('plugin.default') && !filepath) {
filepath = this.resolveModule(configPath.replace(/plugin\.default$/, 'plugin'));
}
if (!filepath) {
debug('[readPluginConfigs:ignore] plugin config not found %o', configPath);
continue;
}
const config: Record<string, EggPluginInfo> = await utils.loadFile(filepath);
for (const name in config) {
this.#normalizePluginConfig(config, name, filepath);
}
this.#extendPlugins(plugins, config);
}
return plugins;
}
#normalizePluginConfig(plugins: Record<string, EggPluginInfo | boolean>, name: string, configPath: string): void {
const plugin = plugins[name];
// plugin_name: false
if (typeof plugin === 'boolean') {
plugins[name] = {
name,
enable: plugin,
dependencies: [],
optionalDependencies: [],
env: [],
from: configPath,
} satisfies EggPluginInfo;
return;
}
if (!('enable' in plugin)) {
Reflect.set(plugin, 'enable', true);
}
plugin.name = name;
plugin.dependencies = plugin.dependencies || [];
plugin.optionalDependencies = plugin.optionalDependencies || [];
plugin.env = plugin.env || [];
plugin.from = plugin.from || configPath;
depCompatible(plugin);
}
// Read plugin information from package.json and merge
// {
// eggPlugin: {
// "name": "", plugin name, must be same as name in config/plugin.js
// "dep": [], dependent plugins
// "env": "" env
// "strict": true, whether check plugin name, default to true.
// }
// }
async #mergePluginConfig(plugin: EggPluginInfo): Promise<void> {
let pkg: any;
let eggPluginConfig: any;
const pluginPackage = path.join(plugin.path as string, 'package.json');
if (await utils.existsPath(pluginPackage)) {
pkg = await readJSON(pluginPackage);
eggPluginConfig = pkg.eggPlugin;
if (pkg.version) {
plugin.version = pkg.version;
}
// support commonjs and esm dist files
plugin.path = await this.#formatPluginPathFromPackageJSON(plugin.path as string, pkg);
}
if (!eggPluginConfig) {
// eggPlugin in package.json is no longer required since plugins
// now use definePluginFactory() to declare their config
return;
}
const logger = this.options.logger;
if (eggPluginConfig.name && eggPluginConfig.strict !== false && eggPluginConfig.name !== plugin.name) {
// pluginName is configured in config/plugin.js
// pluginConfigName is pkg.eggPlugin.name
logger.warn(
`[@eggjs/core/egg_loader] pluginName(${plugin.name}) is different from pluginConfigName(${eggPluginConfig.name})`,
);
}
// dep compatible
depCompatible(eggPluginConfig);
for (const key of ['dependencies', 'optionalDependencies', 'env']) {
const values = eggPluginConfig[key];
const existsValues = Reflect.get(plugin, key);
if (Array.isArray(values) && !existsValues?.length) {
Reflect.set(plugin, key, values);
}
}
}
protected getOrderPlugins(
allPlugins: Record<string, EggPluginInfo>,
enabledPluginNames: string[],
appPlugins: Record<string, EggPluginInfo>,
): EggPluginInfo[] {
// no plugins enabled
if (enabledPluginNames.length === 0) {
return [];
}
const result = sequencify(allPlugins, enabledPluginNames);
debug('Got plugins %j after sequencify', result);
// catch error when result.sequence is empty
if (result.sequence.length === 0) {
const err = new Error(
`sequencify plugins has problem, missing: [${result.missingTasks}], recursive: [${result.recursiveDependencies}]`,
);
// find plugins which is required by the missing plugin
for (const missName of result.missingTasks) {
const requires = [];
for (const name in allPlugins) {
if (allPlugins[name].dependencies.includes(missName)) {
requires.push(name);
}
}
err.message += `\n\t>> Plugin [${missName}] is disabled or missed, but is required by [${requires}]`;
}
err.name = 'PluginSequencifyError';
throw err;
}
// log the plugins that be enabled implicitly
const implicitEnabledPlugins: string[] = [];
const requireMap: Record<string, string[]> = {};
for (const name of result.sequence) {
for (const depName of allPlugins[name].dependencies) {
if (!requireMap[depName]) {
requireMap[depName] = [];
}
requireMap[depName].push(name);
}
if (!allPlugins[name].enable) {
implicitEnabledPlugins.push(name);
allPlugins[name].enable = true;
allPlugins[name].implicitEnable = true;
}
}
for (const [name, dependents] of Object.entries(requireMap)) {
// note:`dependents` will not includes `optionalDependencies`
allPlugins[name].dependents = dependents;
}
// Following plugins will be enabled implicitly.
// - configclient required by [rpcClient]
// - monitor required by [rpcClient]
// - diamond required by [rpcClient]
if (implicitEnabledPlugins.length > 0) {
let message = implicitEnabledPlugins.map((name) => ` - ${name} required by [${requireMap[name]}]`).join('\n');
this.options.logger.info(`Following plugins will be enabled implicitly.\n${message}`);
// should warn when the plugin is disabled by app
const disabledPlugins = implicitEnabledPlugins.filter(
(name) => appPlugins[name] && appPlugins[name].enable === false,
);
if (disabledPlugins.length > 0) {
message = disabledPlugins.map((name) => ` - ${name} required by [${requireMap[name]}]`).join('\n');
this.options.logger.warn(
`Following plugins will be enabled implicitly that is disabled by application.\n${message}`,
);
}
}
return result.sequence.map((name) => allPlugins[name]);
}
protected getLookupDirs(): Set<string> {
const lookupDirs = new Set<string>();
// try to locate the plugin in the following directories's node_modules
// -> {APP_PATH} -> {EGG_PATH} -> $CWD
lookupDirs.add(this.options.baseDir);
// try to locate the plugin at framework from upper to lower
for (let i = this.eggPaths.length - 1; i >= 0; i--) {
const eggPath = this.eggPaths[i];
lookupDirs.add(eggPath);
}
// should find the $cwd when test the plugins under npm3
lookupDirs.add(process.cwd());
return lookupDirs;
}
// Get the real plugin path
protected getPluginPath(plugin: EggPluginInfo): string {
if (plugin.path) {
return plugin.path;
}
if (plugin.package) {
assert(
isValidatePackageName(plugin.package),
`plugin ${plugin.name} invalid, use 'path' instead of package: "${plugin.package}"`,
);
}
return this.#resolvePluginPath(plugin);
}
#resolvePluginPath(plugin: EggPluginInfo): string {
const name = plugin.package || plugin.name;
try {
// should find the plugin directory
// pnpm will lift the node_modules to the sibling directory
// 'node_modules/.pnpm/yadan@2.0.0/node_modules/yadan/node_modules',
// 'node_modules/.pnpm/yadan@2.0.0/node_modules', <- this is the sibling directory
// 'node_modules/.pnpm/egg@2.33.1/node_modules/egg/node_modules',
// 'node_modules/.pnpm/egg@2.33.1/node_modules', <- this is the sibling directory
const pluginPkgFile = utils.resolvePath(`${name}/package.json`, {
paths: [...this.lookupDirs],
});
return path.dirname(pluginPkgFile);
} catch (err) {
debug('[resolvePluginPath] error: %o, plugin info: %o', err, plugin);
throw new Error(`Can not find plugin ${name} in "${[...this.lookupDirs].join(', ')}"`, {
cause: err,
});
}
}
async #formatPluginPathFromPackageJSON(
pluginPath: string,
pluginPkg: {
eggPlugin?: {
exports?: {
import?: string;
require?: string;
typescript?: string;
};
};
type?: 'module' | 'commonjs';
exports?: {
'.'?:
| string
| {
import?:
| string
| {
default?: string;
};
};
};
},
): Promise<string> {
let realPluginPath = pluginPath;
const exports = pluginPkg.eggPlugin?.exports;
if (exports) {
if (isESM) {
if (exports.import) {
realPluginPath = path.join(pluginPath, exports.import);
}
} else if (exports.require) {
realPluginPath = path.join(pluginPath, exports.require);
}
if (exports.typescript && isSupportTypeScript() && !(await exists(realPluginPath))) {
// if require/import path not exists, use typescript path for development stage
realPluginPath = path.join(pluginPath, exports.typescript);
debug('[formatPluginPathFromPackageJSON] use typescript path %o', realPluginPath);
}
} else if (pluginPkg.exports?.['.'] && pluginPkg.type === 'module') {
// support esm exports
let defaultExport = pluginPkg.exports['.'];
if (typeof defaultExport === 'string') {
// "exports": {
// ".": "./src/index.ts",
// "./app": "./src/app.ts",
// }
realPluginPath = path.dirname(path.join(pluginPath, defaultExport));
} else if (defaultExport?.import) {
if (typeof defaultExport.import === 'string') {
// {
// "exports": {
// ".": {
// "import": "./src/index.ts",
// },
// }
// }
realPluginPath = path.dirname(path.join(pluginPath, defaultExport.import));
} else if (defaultExport.import.default) {
// {
// "exports": {
// ".": {
// "import": {
// "default": "./src/index.ts",
// },
// },
// }
// }
realPluginPath = path.dirname(path.join(pluginPath, defaultExport.import.default));
}
}
debug(
'[formatPluginPathFromPackageJSON] resolve plugin path from %o to %o, defaultExport: %o',
pluginPath,
realPluginPath,
defaultExport,
);
}
return realPluginPath;
}
#extendPlugins(targets: Record<string, EggPluginInfo>, plugins: Record<string, EggPluginInfo>): void {
if (!plugins) {
return;
}
for (const name in plugins) {
const plugin = plugins[name];
let targetPlugin = targets[name];
if (!targetPlugin) {
targetPlugin = {} as EggPluginInfo;
targets[name] = targetPlugin;
}
if (targetPlugin.package && targetPlugin.package === plugin.package) {
this.logger.warn(
'[@eggjs/core] plugin %s has been defined that is %j, but you define again in %s',
name,
targetPlugin,
plugin.from,
);
}
if (plugin.path || plugin.package) {
delete targetPlugin.path;
delete targetPlugin.package;
}
for (const [prop, value] of Object.entries(plugin)) {
if (value === undefined) {
continue;
}
if (Reflect.get(targetPlugin, prop) && Array.isArray(value) && value.length === 0) {
continue;
}
Reflect.set(targetPlugin, prop, value);
}
}
}
/** end Plugin loader */
/** start Config loader */
configMeta: Record<string, any>;
config: EggAppConfig;
/**
* Load config/config.js
*
* Will merge config.default.js 和 config.${env}.js
*
* @function EggLoader#loadConfig
* @since 1.0.0
*/
async loadConfig(): Promise<void> {
this.timing.start('Load Config');
this.configMeta = {};
const target: EggAppConfig = {
middleware: [],
coreMiddleware: [],
};
// Load Application config first
const appConfig = await this.#preloadAppConfig();
// plugin config.default
// framework config.default
// app config.default
// plugin config.{env}
// framework config.{env}
// app config.{env}
for (const filename of this.getTypeFiles('config')) {
for (const unit of this.getLoadUnits()) {
const isApp = unit.type === 'app';
const config = await this.#loadConfig(unit.path, filename, isApp ? undefined : appConfig, unit.type);
if (!config) {
continue;
}
debug('[loadConfig] Loaded config %s/%s, %j', unit.path, filename, config);
extend(true, target, config);
}
}
// load env from process.env.EGG_APP_CONFIG
const envConfig = this.#loadConfigFromEnv();
if (envConfig) {
debug('[loadConfig] Loaded config from env, %j', envConfig);
extend(true, target, envConfig);
}
// You can manipulate the order of app.config.coreMiddleware and app.config.appMiddleware in app.js
target.coreMiddleware = target.coreMiddleware || [];
// alias for coreMiddleware
target.coreMiddlewares = target.coreMiddleware;
target.appMiddleware = target.middleware || [];
// alias for appMiddleware
target.appMiddlewares = target.appMiddleware;
this.config = target;
debug('[loadConfig] type: %s, all config: %o', this.app.type, this.config);
this.timing.end('Load Config');
}
async #preloadAppConfig(): Promise<Record<string, any>> {
const names = ['config.default', `config.${this.serverEnv}`];
const target: Record<string, any> = {};
for (const filename of names) {
const config = await this.#loadConfig(this.options.baseDir, filename, undefined, 'app');
if (!config) {
continue;
}
extend(true, target, config);
}
return target;