@eggjs/core 6.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +296 -0
  3. package/dist/commonjs/base_context_class.d.ts +16 -0
  4. package/dist/commonjs/base_context_class.js +41 -0
  5. package/dist/commonjs/egg.d.ts +204 -0
  6. package/dist/commonjs/egg.js +346 -0
  7. package/dist/commonjs/index.d.ts +5 -0
  8. package/dist/commonjs/index.js +26 -0
  9. package/dist/commonjs/lifecycle.d.ts +75 -0
  10. package/dist/commonjs/lifecycle.js +306 -0
  11. package/dist/commonjs/loader/context_loader.d.ts +24 -0
  12. package/dist/commonjs/loader/context_loader.js +109 -0
  13. package/dist/commonjs/loader/egg_loader.d.ts +405 -0
  14. package/dist/commonjs/loader/egg_loader.js +1497 -0
  15. package/dist/commonjs/loader/file_loader.d.ts +96 -0
  16. package/dist/commonjs/loader/file_loader.js +248 -0
  17. package/dist/commonjs/package.json +3 -0
  18. package/dist/commonjs/types.d.ts +1 -0
  19. package/dist/commonjs/types.js +403 -0
  20. package/dist/commonjs/utils/index.d.ts +14 -0
  21. package/dist/commonjs/utils/index.js +146 -0
  22. package/dist/commonjs/utils/sequencify.d.ts +13 -0
  23. package/dist/commonjs/utils/sequencify.js +59 -0
  24. package/dist/commonjs/utils/timing.d.ts +22 -0
  25. package/dist/commonjs/utils/timing.js +100 -0
  26. package/dist/esm/base_context_class.d.ts +16 -0
  27. package/dist/esm/base_context_class.js +37 -0
  28. package/dist/esm/egg.d.ts +204 -0
  29. package/dist/esm/egg.js +339 -0
  30. package/dist/esm/index.d.ts +5 -0
  31. package/dist/esm/index.js +6 -0
  32. package/dist/esm/lifecycle.d.ts +75 -0
  33. package/dist/esm/lifecycle.js +276 -0
  34. package/dist/esm/loader/context_loader.d.ts +24 -0
  35. package/dist/esm/loader/context_loader.js +102 -0
  36. package/dist/esm/loader/egg_loader.d.ts +405 -0
  37. package/dist/esm/loader/egg_loader.js +1490 -0
  38. package/dist/esm/loader/file_loader.d.ts +96 -0
  39. package/dist/esm/loader/file_loader.js +241 -0
  40. package/dist/esm/package.json +3 -0
  41. package/dist/esm/types.d.ts +1 -0
  42. package/dist/esm/types.js +402 -0
  43. package/dist/esm/utils/index.d.ts +14 -0
  44. package/dist/esm/utils/index.js +141 -0
  45. package/dist/esm/utils/sequencify.d.ts +13 -0
  46. package/dist/esm/utils/sequencify.js +56 -0
  47. package/dist/esm/utils/timing.d.ts +22 -0
  48. package/dist/esm/utils/timing.js +93 -0
  49. package/package.json +103 -0
  50. package/src/base_context_class.ts +39 -0
  51. package/src/egg.ts +430 -0
  52. package/src/index.ts +6 -0
  53. package/src/lifecycle.ts +363 -0
  54. package/src/loader/context_loader.ts +121 -0
  55. package/src/loader/egg_loader.ts +1703 -0
  56. package/src/loader/file_loader.ts +295 -0
  57. package/src/types.ts +447 -0
  58. package/src/utils/index.ts +154 -0
  59. package/src/utils/sequencify.ts +70 -0
  60. package/src/utils/timing.ts +114 -0
@@ -0,0 +1,295 @@
1
+ import assert from 'node:assert';
2
+ import fs from 'node:fs';
3
+ import { debuglog } from 'node:util';
4
+ import path from 'node:path';
5
+ import globby from 'globby';
6
+ import { isClass, isGeneratorFunction, isAsyncFunction, isPrimitive } from 'is-type-of';
7
+ import utils, { Fun } from '../utils/index.js';
8
+
9
+ const debug = debuglog('@eggjs/core:file_loader');
10
+
11
+ export const FULLPATH = Symbol('EGG_LOADER_ITEM_FULLPATH');
12
+ export const EXPORTS = Symbol('EGG_LOADER_ITEM_EXPORTS');
13
+
14
+ export type CaseStyle = 'camel' | 'lower' | 'upper';
15
+ export type CaseStyleFunction = (filepath: string) => string[];
16
+ export type FileLoaderInitializer = (exports: unknown, options: { path: string; pathName: string }) => unknown;
17
+ export type FileLoaderFilter = (exports: unknown) => boolean;
18
+
19
+ export interface FileLoaderOptions {
20
+ /** directories to be loaded */
21
+ directory: string | string[];
22
+ /** attach the target object from loaded files */
23
+ target: Record<string, any>;
24
+ /** match the files when load, support glob, default to all js files */
25
+ match?: string | string[];
26
+ /** ignore the files when load, support glob */
27
+ ignore?: string | string[];
28
+ /** custom file exports, receive two parameters, first is the inject object(if not js file, will be content buffer), second is an `options` object that contain `path` */
29
+ initializer?: FileLoaderInitializer;
30
+ /** determine whether invoke when exports is function */
31
+ call?: boolean;
32
+ /** determine whether override the property when get the same name */
33
+ override?: boolean;
34
+ /** an object that be the argument when invoke the function */
35
+ inject?: Record<string, any>;
36
+ /** a function that filter the exports which can be loaded */
37
+ filter?: FileLoaderFilter;
38
+ /** set property's case when converting a filepath to property list. */
39
+ caseStyle?: CaseStyle | CaseStyleFunction;
40
+ lowercaseFirst?: boolean;
41
+ }
42
+
43
+ export interface FileLoaderParseItem {
44
+ fullpath: string;
45
+ properties: string[];
46
+ exports: object | Fun;
47
+ }
48
+
49
+ /**
50
+ * Load files from directory to target object.
51
+ * @since 1.0.0
52
+ */
53
+ export class FileLoader {
54
+ static get FULLPATH() {
55
+ return FULLPATH;
56
+ }
57
+
58
+ static get EXPORTS() {
59
+ return EXPORTS;
60
+ }
61
+
62
+ readonly options: FileLoaderOptions & Required<Pick<FileLoaderOptions, 'caseStyle'>>;
63
+
64
+ /**
65
+ * @class
66
+ * @param {Object} options - options
67
+ * @param {String|Array} options.directory - directories to be loaded
68
+ * @param {Object} options.target - attach the target object from loaded files
69
+ * @param {String} options.match - match the files when load, support glob, default to all js files
70
+ * @param {String} options.ignore - ignore the files when load, support glob
71
+ * @param {Function} options.initializer - custom file exports, receive two parameters, first is the inject object(if not js file, will be content buffer), second is an `options` object that contain `path`
72
+ * @param {Boolean} options.call - determine whether invoke when exports is function
73
+ * @param {Boolean} options.override - determine whether override the property when get the same name
74
+ * @param {Object} options.inject - an object that be the argument when invoke the function
75
+ * @param {Function} options.filter - a function that filter the exports which can be loaded
76
+ * @param {String|Function} options.caseStyle - set property's case when converting a filepath to property list.
77
+ */
78
+ constructor(options: FileLoaderOptions) {
79
+ assert(options.directory, 'options.directory is required');
80
+ assert(options.target, 'options.target is required');
81
+ this.options = {
82
+ caseStyle: 'camel',
83
+ call: true,
84
+ override: false,
85
+ ...options,
86
+ };
87
+
88
+ // compatible old options _lowercaseFirst_
89
+ if (this.options.lowercaseFirst === true) {
90
+ utils.deprecated('lowercaseFirst is deprecated, use caseStyle instead');
91
+ this.options.caseStyle = 'lower';
92
+ }
93
+ }
94
+
95
+ /**
96
+ * attach items to target object. Mapping the directory to properties.
97
+ * `app/controller/group/repository.js` => `target.group.repository`
98
+ * @return {Object} target
99
+ * @since 1.0.0
100
+ */
101
+ async load(): Promise<object> {
102
+ const items = await this.parse();
103
+ const target = this.options.target;
104
+ for (const item of items) {
105
+ debug('loading item: %o', item);
106
+ // item { properties: [ 'a', 'b', 'c'], exports }
107
+ // => target.a.b.c = exports
108
+ item.properties.reduce((target, property, index) => {
109
+ let obj;
110
+ const properties = item.properties.slice(0, index + 1).join('.');
111
+ if (index === item.properties.length - 1) {
112
+ if (property in target) {
113
+ if (!this.options.override) throw new Error(`can't overwrite property '${properties}' from ${target[property][FULLPATH]} by ${item.fullpath}`);
114
+ }
115
+ obj = item.exports;
116
+ if (obj && !isPrimitive(obj)) {
117
+ Reflect.set(obj, FULLPATH, item.fullpath);
118
+ Reflect.set(obj, EXPORTS, true);
119
+ }
120
+ } else {
121
+ obj = target[property] || {};
122
+ }
123
+ target[property] = obj;
124
+ debug('loaded item properties: %o => %o', properties, obj);
125
+ return obj;
126
+ }, target);
127
+ }
128
+ return target;
129
+ }
130
+
131
+ /**
132
+ * Parse files from given directories, then return an items list, each item contains properties and exports.
133
+ *
134
+ * For example, parse `app/controller/group/repository.js`
135
+ *
136
+ * ```
137
+ * module.exports = app => {
138
+ * return class RepositoryController extends app.Controller {};
139
+ * }
140
+ * ```
141
+ *
142
+ * It returns a item
143
+ *
144
+ * ```
145
+ * {
146
+ * properties: [ 'group', 'repository' ],
147
+ * exports: app => { ... },
148
+ * }
149
+ * ```
150
+ *
151
+ * `Properties` is an array that contains the directory of a filepath.
152
+ *
153
+ * `Exports` depends on type, if exports is a function, it will be called. if initializer is specified, it will be called with exports for customizing.
154
+ * @return {Array} items
155
+ * @since 1.0.0
156
+ */
157
+ protected async parse(): Promise<FileLoaderParseItem[]> {
158
+ let files = this.options.match;
159
+ if (!files) {
160
+ files = (process.env.EGG_TYPESCRIPT === 'true' && utils.extensions['.ts'])
161
+ ? [ '**/*.(js|ts)', '!**/*.d.ts' ]
162
+ : [ '**/*.js' ];
163
+ } else {
164
+ files = Array.isArray(files) ? files : [ files ];
165
+ }
166
+
167
+ let ignore = this.options.ignore;
168
+ if (ignore) {
169
+ ignore = Array.isArray(ignore) ? ignore : [ ignore ];
170
+ ignore = ignore.filter(f => !!f).map(f => '!' + f);
171
+ files = files.concat(ignore);
172
+ }
173
+
174
+ let directories = this.options.directory;
175
+ if (!Array.isArray(directories)) {
176
+ directories = [ directories ];
177
+ }
178
+
179
+ const filter = typeof this.options.filter === 'function' ? this.options.filter : null;
180
+ const items: FileLoaderParseItem[] = [];
181
+ debug('[parse] parsing directories: %j', directories);
182
+ for (const directory of directories) {
183
+ const filepaths = globby.sync(files, { cwd: directory });
184
+ debug('[parse] globby files: %o, cwd: %o => %o', files, directory, filepaths);
185
+ for (const filepath of filepaths) {
186
+ const fullpath = path.join(directory, filepath);
187
+ if (!fs.statSync(fullpath).isFile()) continue;
188
+ // get properties
189
+ // app/service/foo/bar.js => [ 'foo', 'bar' ]
190
+ const properties = getProperties(filepath, this.options.caseStyle);
191
+ // app/service/foo/bar.js => service.foo.bar
192
+ const pathName = directory.split(/[/\\]/).slice(-1) + '.' + properties.join('.');
193
+ // get exports from the file
194
+ const exports = await getExports(fullpath, this.options, pathName);
195
+
196
+ // ignore exports when it's null or false returned by filter function
197
+ if (exports == null || (filter && filter(exports) === false)) {
198
+ continue;
199
+ }
200
+
201
+ // set properties of class
202
+ if (isClass(exports)) {
203
+ exports.prototype.pathName = pathName;
204
+ exports.prototype.fullPath = fullpath;
205
+ }
206
+
207
+ items.push({ fullpath, properties, exports });
208
+ debug('[parse] parse %s, properties %j, exports %o', fullpath, properties, exports);
209
+ }
210
+ }
211
+
212
+ return items;
213
+ }
214
+ }
215
+
216
+ // convert file path to an array of properties
217
+ // a/b/c.js => ['a', 'b', 'c']
218
+ function getProperties(filepath: string, caseStyle: CaseStyle | CaseStyleFunction) {
219
+ // if caseStyle is function, return the result of function
220
+ if (typeof caseStyle === 'function') {
221
+ const result = caseStyle(filepath);
222
+ assert(Array.isArray(result), `caseStyle expect an array, but got ${JSON.stringify(result)}`);
223
+ return result;
224
+ }
225
+ // use default camelize
226
+ return defaultCamelize(filepath, caseStyle);
227
+ }
228
+
229
+ // Get exports from filepath
230
+ // If exports is null/undefined, it will be ignored
231
+ async function getExports(fullpath: string, options: FileLoaderOptions, pathName: string) {
232
+ let exports = await utils.loadFile(fullpath);
233
+ // process exports as you like
234
+ if (options.initializer) {
235
+ exports = options.initializer(exports, { path: fullpath, pathName });
236
+ debug('[getExports] after initializer => %o', exports);
237
+ }
238
+
239
+ if (isGeneratorFunction(exports)) {
240
+ throw new TypeError(`Support for generators was removed, fullpath: ${fullpath}`);
241
+ }
242
+
243
+ // return exports when it's a class or async function
244
+ //
245
+ // module.exports = class Service {};
246
+ // or
247
+ // module.exports = async function() {}
248
+ if (isClass(exports) || isAsyncFunction(exports)) {
249
+ return exports;
250
+ }
251
+
252
+ // return exports after call when it's a function
253
+ //
254
+ // module.exports = function(app) {
255
+ // return {};
256
+ // }
257
+ if (options.call && typeof exports === 'function') {
258
+ exports = exports(options.inject);
259
+ if (exports != null) {
260
+ return exports;
261
+ }
262
+ }
263
+
264
+ // return exports what is
265
+ return exports;
266
+ }
267
+
268
+ function defaultCamelize(filepath: string, caseStyle: CaseStyle) {
269
+ const properties = filepath.substring(0, filepath.lastIndexOf('.')).split('/');
270
+ return properties.map(property => {
271
+ if (!/^[a-z][a-z0-9_-]*$/i.test(property)) {
272
+ throw new Error(`${property} is not match 'a-z0-9_-' in ${filepath}`);
273
+ }
274
+
275
+ // use default camelize, will capitalize the first letter
276
+ // foo_bar.js > FooBar
277
+ // fooBar.js > FooBar
278
+ // FooBar.js > FooBar
279
+ // FooBar.js > FooBar
280
+ // FooBar.js > fooBar (if lowercaseFirst is true)
281
+ property = property.replace(/[_-][a-z]/ig, s => s.substring(1).toUpperCase());
282
+ let first = property[0];
283
+ switch (caseStyle) {
284
+ case 'lower':
285
+ first = first.toLowerCase();
286
+ break;
287
+ case 'upper':
288
+ first = first.toUpperCase();
289
+ break;
290
+ case 'camel':
291
+ default:
292
+ }
293
+ return first + property.substring(1);
294
+ });
295
+ }