@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
package/src/lifecycle.ts DELETED
@@ -1,399 +0,0 @@
1
- import assert from 'node:assert';
2
- import { EventEmitter } from 'node:events';
3
- import { debuglog, format } from 'node:util';
4
- import { isClass } from 'is-type-of';
5
- import { Ready as ReadyObject } from 'get-ready';
6
- import type { ReadyFunctionArg } from 'get-ready';
7
- import { Ready } from 'ready-callback';
8
- import { EggConsoleLogger } from 'egg-logger';
9
- import utils from './utils/index.js';
10
- import type { Fun } from './utils/index.js';
11
- import type { EggCore } from './egg.js';
12
-
13
- const debug = debuglog('@eggjs/core/lifecycle');
14
-
15
- export interface ILifecycleBoot {
16
- // loader auto set 'fullPath' property on boot class
17
- fullPath?: string;
18
- /**
19
- * Ready to call configDidLoad,
20
- * Config, plugin files are referred,
21
- * this is the last chance to modify the config.
22
- */
23
- configWillLoad?(): void;
24
-
25
- /**
26
- * Config, plugin files have loaded
27
- */
28
- configDidLoad?(): void;
29
-
30
- /**
31
- * All files have loaded, start plugin here
32
- */
33
- didLoad?(): Promise<void>;
34
-
35
- /**
36
- * All plugins have started, can do some thing before app ready
37
- */
38
- willReady?(): Promise<void>;
39
-
40
- /**
41
- * Worker is ready, can do some things,
42
- * don't need to block the app boot
43
- */
44
- didReady?(err?: Error): Promise<void>;
45
-
46
- /**
47
- * Server is listening
48
- */
49
- serverDidReady?(): Promise<void>;
50
-
51
- /**
52
- * Do some thing before app close
53
- */
54
- beforeClose?(): Promise<void>;
55
- }
56
-
57
- export type BootImplClass<T = ILifecycleBoot> = new(...args: any[]) => T;
58
-
59
- export interface LifecycleOptions {
60
- baseDir: string;
61
- app: EggCore;
62
- logger: EggConsoleLogger;
63
- }
64
-
65
- export type FunWithFullPath = Fun & { fullPath?: string };
66
-
67
- export class Lifecycle extends EventEmitter {
68
- #init: boolean;
69
- #readyObject: ReadyObject;
70
- #bootHooks: (BootImplClass | ILifecycleBoot)[];
71
- #boots: ILifecycleBoot[];
72
- #isClosed: boolean;
73
- #closeFunctionSet: Set<FunWithFullPath>;
74
- loadReady: Ready;
75
- bootReady: Ready;
76
- options: LifecycleOptions;
77
- readyTimeout: number;
78
-
79
- constructor(options: Partial<LifecycleOptions>) {
80
- super();
81
- options.logger = options.logger ?? new EggConsoleLogger();
82
- this.options = options as LifecycleOptions;
83
- this.#readyObject = new ReadyObject();
84
- this.#bootHooks = [];
85
- this.#boots = [];
86
- this.#closeFunctionSet = new Set();
87
- this.#isClosed = false;
88
- this.#init = false;
89
-
90
- this.timing.start(`${this.options.app.type} Start`);
91
- // get app timeout from env or use default timeout 10 second
92
- const eggReadyTimeoutEnv = parseInt(process.env.EGG_READY_TIMEOUT_ENV || '10000');
93
- assert(
94
- Number.isInteger(eggReadyTimeoutEnv),
95
- `process.env.EGG_READY_TIMEOUT_ENV ${process.env.EGG_READY_TIMEOUT_ENV} should be able to parseInt.`);
96
- this.readyTimeout = eggReadyTimeoutEnv;
97
-
98
- this.#initReady();
99
- this
100
- .on('ready_stat', data => {
101
- this.logger.info('[@eggjs/core/lifecycle:ready_stat] end ready task %s, remain %j', data.id, data.remain);
102
- })
103
- .on('ready_timeout', id => {
104
- this.logger.warn('[@eggjs/core/lifecycle:ready_timeout] %s seconds later %s was still unable to finish.', this.readyTimeout / 1000, id);
105
- });
106
-
107
- this.ready(err => {
108
- this.triggerDidReady(err);
109
- debug('app ready');
110
- this.timing.end(`${this.options.app.type} Start`);
111
- });
112
- }
113
-
114
- ready(): Promise<void>;
115
- ready(flagOrFunction: ReadyFunctionArg): void;
116
- ready(flagOrFunction?: ReadyFunctionArg) {
117
- if (flagOrFunction === undefined) {
118
- return this.#readyObject.ready();
119
- }
120
- return this.#readyObject.ready(flagOrFunction);
121
- }
122
-
123
- get app() {
124
- return this.options.app;
125
- }
126
-
127
- get logger() {
128
- return this.options.logger;
129
- }
130
-
131
- get timing() {
132
- return this.app.timing;
133
- }
134
-
135
- legacyReadyCallback(name: string, opt?: object) {
136
- const timingKeyPrefix = 'readyCallback';
137
- const timing = this.timing;
138
- const cb = this.loadReady.readyCallback(name, opt);
139
- const timingKey = `${timingKeyPrefix} in ` + utils.getResolvedFilename(name, this.app.baseDir);
140
- this.timing.start(timingKey);
141
- debug('register legacyReadyCallback');
142
- return function legacyReadyCallback(...args: any[]) {
143
- timing.end(timingKey);
144
- debug('end legacyReadyCallback');
145
- cb(...args);
146
- };
147
- }
148
-
149
- addBootHook(bootHootOrBootClass: BootImplClass | ILifecycleBoot) {
150
- assert(this.#init === false, 'do not add hook when lifecycle has been initialized');
151
- this.#bootHooks.push(bootHootOrBootClass);
152
- }
153
-
154
- addFunctionAsBootHook<T = EggCore>(hook: (app: T) => void, fullPath?: string) {
155
- assert(this.#init === false, 'do not add hook when lifecycle has been initialized');
156
- // app.js is exported as a function
157
- // call this function in configDidLoad
158
- class Boot implements ILifecycleBoot {
159
- static fullPath?: string;
160
- app: T;
161
- constructor(app: T) {
162
- this.app = app;
163
- }
164
- configDidLoad() {
165
- hook(this.app);
166
- }
167
- }
168
- Boot.fullPath = fullPath;
169
- this.#bootHooks.push(Boot);
170
- }
171
-
172
- /**
173
- * init boots and trigger config did config
174
- */
175
- init() {
176
- debug('%s init lifecycle', this.app.type);
177
- assert(this.#init === false, 'lifecycle have been init');
178
- this.#init = true;
179
- this.#boots = this.#bootHooks.map(BootHootOrBootClass => {
180
- let instance = BootHootOrBootClass as ILifecycleBoot;
181
- if (isClass(BootHootOrBootClass)) {
182
- instance = new BootHootOrBootClass(this.app);
183
- if (!instance.fullPath && 'fullPath' in BootHootOrBootClass) {
184
- instance.fullPath = BootHootOrBootClass.fullPath as string;
185
- }
186
- }
187
- debug('[init] add boot instance: %o', instance.fullPath);
188
- return instance;
189
- });
190
- }
191
-
192
- registerBeforeStart(scope: Fun, name: string) {
193
- debug('%s add registerBeforeStart, name: %o',
194
- this.options.app.type, name);
195
- this.#registerReadyCallback({
196
- scope,
197
- ready: this.loadReady,
198
- timingKeyPrefix: 'Before Start',
199
- scopeFullName: name,
200
- });
201
- }
202
-
203
- registerBeforeClose(fn: FunWithFullPath, fullPath?: string) {
204
- assert(typeof fn === 'function', 'argument should be function');
205
- assert(this.#isClosed === false, 'app has been closed');
206
- if (fullPath) {
207
- fn.fullPath = fullPath;
208
- }
209
- this.#closeFunctionSet.add(fn);
210
- debug('%s register beforeClose at %o, count: %d',
211
- this.app.type, fullPath, this.#closeFunctionSet.size);
212
- }
213
-
214
- async close() {
215
- // close in reverse order: first created, last closed
216
- const closeFns = Array.from(this.#closeFunctionSet);
217
- debug('%s start trigger %d beforeClose functions',
218
- this.app.type, closeFns.length);
219
- for (const fn of closeFns.reverse()) {
220
- debug('%s trigger beforeClose at %o', this.app.type, fn.fullPath);
221
- await utils.callFn(fn);
222
- this.#closeFunctionSet.delete(fn);
223
- }
224
- // Be called after other close callbacks
225
- this.app.emit('close');
226
- this.removeAllListeners();
227
- this.app.removeAllListeners();
228
- this.#isClosed = true;
229
- debug('%s closed', this.app.type);
230
- }
231
-
232
- triggerConfigWillLoad() {
233
- debug('trigger configWillLoad start');
234
- for (const boot of this.#boots) {
235
- if (typeof boot.configWillLoad === 'function') {
236
- debug('trigger configWillLoad at %o', boot.fullPath);
237
- boot.configWillLoad();
238
- }
239
- }
240
- debug('trigger configWillLoad end');
241
- this.triggerConfigDidLoad();
242
- }
243
-
244
- triggerConfigDidLoad() {
245
- debug('trigger configDidLoad start');
246
- for (const boot of this.#boots) {
247
- if (typeof boot.configDidLoad === 'function') {
248
- debug('trigger configDidLoad at %o', boot.fullPath);
249
- boot.configDidLoad();
250
- }
251
- // function boot hook register after configDidLoad trigger
252
- if (typeof boot.beforeClose === 'function') {
253
- const beforeClose = boot.beforeClose.bind(boot);
254
- this.registerBeforeClose(beforeClose, boot.fullPath);
255
- }
256
- }
257
- debug('trigger configDidLoad end');
258
- this.triggerDidLoad();
259
- }
260
-
261
- triggerDidLoad() {
262
- debug('trigger didLoad start');
263
- debug('loadReady start');
264
- this.loadReady.start();
265
- for (const boot of this.#boots) {
266
- if (typeof boot.didLoad === 'function') {
267
- const didLoad = boot.didLoad.bind(boot);
268
- this.#registerReadyCallback({
269
- scope: didLoad,
270
- ready: this.loadReady,
271
- timingKeyPrefix: 'Did Load',
272
- scopeFullName: boot.fullPath + ':didLoad',
273
- });
274
- }
275
- }
276
- }
277
-
278
- triggerWillReady() {
279
- debug('trigger willReady start');
280
- debug('bootReady start');
281
- this.bootReady.start();
282
- for (const boot of this.#boots) {
283
- if (typeof boot.willReady === 'function') {
284
- const willReady = boot.willReady.bind(boot);
285
- this.#registerReadyCallback({
286
- scope: willReady,
287
- ready: this.bootReady,
288
- timingKeyPrefix: 'Will Ready',
289
- scopeFullName: boot.fullPath + ':willReady',
290
- });
291
- }
292
- }
293
- }
294
-
295
- triggerDidReady(err?: Error) {
296
- debug('trigger didReady start');
297
- return (async () => {
298
- for (const boot of this.#boots) {
299
- if (typeof boot.didReady === 'function') {
300
- debug('trigger didReady at %o', boot.fullPath);
301
- try {
302
- await boot.didReady(err);
303
- } catch (err) {
304
- debug('trigger didReady error at %o, error: %s', boot.fullPath, err);
305
- this.emit('error', err);
306
- }
307
- }
308
- }
309
- debug('trigger didReady end');
310
- })();
311
- }
312
-
313
- triggerServerDidReady() {
314
- debug('trigger serverDidReady start');
315
- return (async () => {
316
- for (const boot of this.#boots) {
317
- if (typeof boot.serverDidReady !== 'function') {
318
- continue;
319
- }
320
- debug('trigger serverDidReady at %o', boot.fullPath);
321
- try {
322
- await boot.serverDidReady();
323
- } catch (err) {
324
- debug('trigger serverDidReady error at %o, error: %s', boot.fullPath, err);
325
- this.emit('error', err);
326
- }
327
- }
328
- debug('trigger serverDidReady end');
329
- })();
330
- }
331
-
332
- #initReady() {
333
- debug('loadReady init');
334
- this.loadReady = new Ready({ timeout: this.readyTimeout, lazyStart: true });
335
- this.#delegateReadyEvent(this.loadReady);
336
- this.loadReady.ready((err?: Error) => {
337
- debug('loadReady end, err: %o', err);
338
- debug('trigger didLoad end');
339
- if (err) {
340
- this.ready(err);
341
- } else {
342
- this.triggerWillReady();
343
- }
344
- });
345
-
346
- debug('bootReady init');
347
- this.bootReady = new Ready({ timeout: this.readyTimeout, lazyStart: true });
348
- this.#delegateReadyEvent(this.bootReady);
349
- this.bootReady.ready((err?: Error) => {
350
- debug('bootReady end, err: %o', err);
351
- debug('trigger willReady end');
352
- this.ready(err || true);
353
- });
354
- }
355
-
356
- #delegateReadyEvent(ready: Ready) {
357
- ready.once('error', (err?: Error) => ready.ready(err));
358
- ready.on('ready_timeout', (id: any) => this.emit('ready_timeout', id));
359
- ready.on('ready_stat', (data: any) => this.emit('ready_stat', data));
360
- ready.on('error', (err?: Error) => this.emit('error', err));
361
- }
362
-
363
- #registerReadyCallback(args: {
364
- scope: Fun;
365
- ready: Ready;
366
- timingKeyPrefix: string;
367
- scopeFullName?: string;
368
- }) {
369
- const { scope, ready, timingKeyPrefix, scopeFullName } = args;
370
- if (typeof scope !== 'function') {
371
- throw new Error('boot only support function');
372
- }
373
-
374
- // get filename from stack if scopeFullName is undefined
375
- const name = scopeFullName || utils.getCalleeFromStack(true, 4);
376
- const timingKey = `${timingKeyPrefix} in ` + utils.getResolvedFilename(name, this.app.baseDir);
377
-
378
- this.timing.start(timingKey);
379
-
380
- debug('[registerReadyCallback] start name: %o', name);
381
- const done = ready.readyCallback(name);
382
-
383
- // ensure scope executes after load completed
384
- process.nextTick(() => {
385
- utils.callFn(scope).then(() => {
386
- debug('[registerReadyCallback] end name: %o', name);
387
- done();
388
- this.timing.end(timingKey);
389
- }, (err: Error) => {
390
- // avoid non-stringify error: TypeError: Cannot convert object to primitive value
391
- if (!(err instanceof Error)) {
392
- err = new Error(format('%s', err));
393
- }
394
- done(err);
395
- this.timing.end(timingKey);
396
- });
397
- });
398
- }
399
- }
@@ -1,121 +0,0 @@
1
- import assert from 'node:assert';
2
- import { isClass, isPrimitive } from 'is-type-of';
3
- import { FileLoader, EXPORTS, type FileLoaderOptions } from './file_loader.js';
4
- import type { Context } from '../egg.js';
5
-
6
- const CLASS_LOADER = Symbol('classLoader');
7
-
8
- export interface ClassLoaderOptions {
9
- ctx: Context;
10
- properties: any;
11
- }
12
-
13
- export class ClassLoader {
14
- readonly _cache = new Map();
15
- _ctx: Context;
16
-
17
- constructor(options: ClassLoaderOptions) {
18
- assert(options.ctx, 'options.ctx is required');
19
- const properties = options.properties;
20
- this._ctx = options.ctx;
21
-
22
- for (const property in properties) {
23
- this.#defineProperty(property, properties[property]);
24
- }
25
- }
26
-
27
- #defineProperty(property: string, values: any) {
28
- Object.defineProperty(this, property, {
29
- get() {
30
- let instance: any = this._cache.get(property);
31
- if (!instance) {
32
- instance = getInstance(values, this._ctx);
33
- this._cache.set(property, instance);
34
- }
35
- return instance;
36
- },
37
- });
38
- }
39
- }
40
-
41
- export interface ContextLoaderOptions extends Omit<FileLoaderOptions, 'target'> {
42
- /** required inject */
43
- inject: Record<string, any>;
44
- /** property name defined to target */
45
- property: string | symbol;
46
- /** determine the field name of inject object. */
47
- fieldClass?: string;
48
- }
49
-
50
- /**
51
- * Same as {@link FileLoader}, but it will attach file to `inject[fieldClass]`.
52
- * The exports will be lazy loaded, such as `ctx.group.repository`.
53
- * @augments FileLoader
54
- * @since 1.0.0
55
- */
56
- export class ContextLoader extends FileLoader {
57
- readonly #inject: Record<string, any>;
58
- /**
59
- * @class
60
- * @param {Object} options - options same as {@link FileLoader}
61
- * @param {String} options.fieldClass - determine the field name of inject object.
62
- */
63
- constructor(options: ContextLoaderOptions) {
64
- assert(options.property, 'options.property is required');
65
- assert(options.inject, 'options.inject is required');
66
- const target = {};
67
- if (options.fieldClass) {
68
- options.inject[options.fieldClass] = target;
69
- }
70
- super({
71
- ...options,
72
- target,
73
- });
74
- this.#inject = this.options.inject!;
75
-
76
- const app = this.#inject;
77
- const property = options.property;
78
- // define ctx.service
79
- Object.defineProperty(app.context, property, {
80
- get() {
81
- // eslint-disable-next-line @typescript-eslint/no-this-alias
82
- const ctx = this;
83
- // distinguish property cache,
84
- // cache's lifecycle is the same with this context instance
85
- // e.x. ctx.service1 and ctx.service2 have different cache
86
- if (!ctx[CLASS_LOADER]) {
87
- ctx[CLASS_LOADER] = new Map();
88
- }
89
- const classLoader: Map<string | symbol, ClassLoader> = ctx[CLASS_LOADER];
90
- let instance = classLoader.get(property);
91
- if (!instance) {
92
- instance = getInstance(target, ctx);
93
- classLoader.set(property, instance!);
94
- }
95
- return instance;
96
- },
97
- });
98
- }
99
- }
100
-
101
- function getInstance(values: any, ctx: Context) {
102
- // it's a directory when it has no exports
103
- // then use ClassLoader
104
- const Class = values[EXPORTS] ? values : null;
105
- let instance;
106
- if (Class) {
107
- if (isClass(Class)) {
108
- instance = new Class(ctx);
109
- } else {
110
- // it's just an object
111
- instance = Class;
112
- }
113
- // Can't set property to primitive, so check again
114
- // e.x. module.exports = 1;
115
- } else if (isPrimitive(values)) {
116
- instance = values;
117
- } else {
118
- instance = new ClassLoader({ ctx, properties: values });
119
- }
120
- return instance;
121
- }