ee-core 1.0.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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -0
  3. package/bin/tools.js +22 -0
  4. package/config/config.default.js +179 -0
  5. package/core/index.js +13 -0
  6. package/core/lib/ee.js +220 -0
  7. package/core/lib/loader/context_loader.js +105 -0
  8. package/core/lib/loader/ee_loader.js +427 -0
  9. package/core/lib/loader/file_loader.js +262 -0
  10. package/core/lib/loader/mixin/config.js +138 -0
  11. package/core/lib/loader/mixin/controller.js +123 -0
  12. package/core/lib/loader/mixin/service.js +29 -0
  13. package/core/lib/utils/base_context_class.js +34 -0
  14. package/core/lib/utils/index.js +100 -0
  15. package/core/lib/utils/sequencify.js +59 -0
  16. package/core/lib/utils/timing.js +77 -0
  17. package/index.js +50 -0
  18. package/lib/appLoader.js +45 -0
  19. package/lib/application.js +69 -0
  20. package/lib/baseApp.js +155 -0
  21. package/lib/constant.js +30 -0
  22. package/lib/eeApp.js +306 -0
  23. package/lib/helper.js +52 -0
  24. package/lib/httpclient.js +136 -0
  25. package/lib/logger.js +47 -0
  26. package/lib/socket/io.js +22 -0
  27. package/lib/socket/ipcServer.js +112 -0
  28. package/lib/socket/socketClient.js +51 -0
  29. package/lib/socket/socketServer.js +70 -0
  30. package/lib/socket/start.js +18 -0
  31. package/lib/storage/appStorage.js +14 -0
  32. package/lib/storage/index.js +22 -0
  33. package/lib/storage/lowdbStorage.js +144 -0
  34. package/package.json +39 -0
  35. package/resource/images/loding.gif +0 -0
  36. package/resource/images/tray_logo.png +0 -0
  37. package/resource/loading.html +22 -0
  38. package/resource/view_example.html +22 -0
  39. package/tools/codeCompress.js +202 -0
  40. package/tools/replaceDist.js +71 -0
  41. package/utils/index.js +141 -0
  42. package/utils/wrap.js +38 -0
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ const debug = require('debug')('ee-core:config');
4
+ const path = require('path');
5
+ const extend = require('extend2');
6
+ const assert = require('assert');
7
+ const { Console } = require('console');
8
+
9
+ module.exports = {
10
+
11
+ /**
12
+ * Load config/config.js
13
+ *
14
+ * Will merge config.default.js 和 config.${env}.js
15
+ *
16
+ * @function EggLoader#loadConfig
17
+ * @since 1.0.0
18
+ */
19
+ loadConfig() {
20
+ this.timing.start('Load Config');
21
+ this.configMeta = {};
22
+
23
+ const target = {};
24
+
25
+ // Load Application config first
26
+ const appConfig = this._preloadAppConfig();
27
+ //console.log('----------------------- appConfig:', appConfig);
28
+
29
+ // plugin config.default
30
+ // framework config.default
31
+ // app config.default
32
+ // plugin config.{env}
33
+ // framework config.{env}
34
+ // app config.{env}
35
+ for (const filename of this.getTypeFiles('config')) {
36
+ for (const unit of this.getLoadUnits()) {
37
+ const isApp = unit.type === 'app';
38
+ const config = this._loadConfig(unit.path, filename, isApp ? undefined : appConfig, unit.type);
39
+
40
+ if (!config) {
41
+ continue;
42
+ }
43
+
44
+ debug('Loaded config %s, %s, %j', unit.path, filename, config);
45
+ extend(true, target, config);
46
+ }
47
+ }
48
+
49
+ // load env from process.env.EE_APP_CONFIG
50
+ const envConfig = this._loadConfigFromEnv();
51
+ debug('Loaded config from private env, %j', envConfig);
52
+ extend(true, target, envConfig);
53
+
54
+ // You can manipulate the order of app.config.coreMiddleware and app.config.appMiddleware in app.js
55
+ target.coreMiddleware = target.coreMiddlewares = target.coreMiddleware || [];
56
+ target.appMiddleware = target.appMiddlewares = target.middleware || [];
57
+
58
+ this.config = target;
59
+ this.timing.end('Load Config');
60
+ },
61
+
62
+ _preloadAppConfig() {
63
+ const names = [
64
+ 'config.default',
65
+ `config.${this.serverEnv}`,
66
+ ];
67
+ const target = {};
68
+ for (const filename of names) {
69
+ const config = this._loadConfig(this.options.baseDir, filename, undefined, 'app');
70
+ extend(true, target, config);
71
+ }
72
+ return target;
73
+ },
74
+
75
+ _loadConfig(dirpath, filename, extraInject, type) {
76
+ const isPlugin = type === 'plugin';
77
+ const isApp = type === 'app';
78
+
79
+ let filepath = this.resolveModule(path.join(dirpath, 'config', filename));
80
+
81
+ //console.log("_loadConfig filepath:", filepath);
82
+
83
+ // let config.js compatible
84
+ if (filename === 'config.default' && !filepath) {
85
+ filepath = this.resolveModule(path.join(dirpath, 'config/config'));
86
+ }
87
+
88
+ const config = this.loadFile(filepath, this.appInfo, extraInject);
89
+
90
+ if (!config) return null;
91
+
92
+ if (isPlugin || isApp) {
93
+ assert(!config.coreMiddleware, 'Can not define coreMiddleware in app or plugin');
94
+ }
95
+ if (!isApp) {
96
+ assert(!config.middleware, 'Can not define middleware in ' + filepath);
97
+ }
98
+
99
+ // store config meta, check where is the property of config come from.
100
+ this._setConfigMeta(config, filepath);
101
+
102
+ return config;
103
+ },
104
+
105
+ _loadConfigFromEnv() {
106
+ const envConfigStr = process.env.EE_APP_CONFIG;
107
+ if (!envConfigStr) return;
108
+ try {
109
+ const envConfig = JSON.parse(envConfigStr);
110
+ this._setConfigMeta(envConfig, '<process.env.EE_APP_CONFIG>');
111
+ return envConfig;
112
+ } catch (err) {
113
+ this.options.logger.warn('[egg-loader] process.env.EE_APP_CONFIG is not invalid JSON: %s', envConfigStr);
114
+ }
115
+ },
116
+
117
+ _setConfigMeta(config, filepath) {
118
+ config = extend(true, {}, config);
119
+ setConfig(config, filepath);
120
+ extend(true, this.configMeta, config);
121
+ },
122
+ };
123
+
124
+ function setConfig(obj, filepath) {
125
+ for (const key of Object.keys(obj)) {
126
+ const val = obj[key];
127
+ // ignore console
128
+ if (key === 'console' && val && typeof val.Console === 'function' && val.Console === Console) {
129
+ obj[key] = filepath;
130
+ continue;
131
+ }
132
+ if (val && Object.getPrototypeOf(val) === Object.prototype && Object.keys(val).length > 0) {
133
+ setConfig(val, filepath);
134
+ continue;
135
+ }
136
+ obj[key] = filepath;
137
+ }
138
+ }
@@ -0,0 +1,123 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const is = require('is-type-of');
5
+ const utility = require('utility');
6
+ const utils = require('../../utils');
7
+ const FULLPATH = require('../file_loader').FULLPATH;
8
+
9
+
10
+ module.exports = {
11
+
12
+ /**
13
+ * Load app/controller
14
+ * @param {Object} opt - LoaderOptions
15
+ * @since 1.0.0
16
+ */
17
+ loadController(opt) {
18
+ this.timing.start('Load Controller');
19
+ opt = Object.assign({
20
+ caseStyle: 'lower',
21
+ directory: path.join(this.options.baseDir, 'controller'),
22
+ initializer: (obj, opt) => {
23
+ // return class if it exports a function
24
+ // ```js
25
+ // module.exports = app => {
26
+ // return class HomeController extends app.Controller {};
27
+ // }
28
+ // ```
29
+ if (is.function(obj) && !is.generatorFunction(obj) && !is.class(obj) && !is.asyncFunction(obj)) {
30
+ obj = obj(this.app);
31
+ }
32
+ if (is.class(obj)) {
33
+ obj.prototype.pathName = opt.pathName;
34
+ obj.prototype.fullPath = opt.path;
35
+ return wrapClass(obj);
36
+ }
37
+ if (is.object(obj)) {
38
+ return wrapObject(obj, opt.path);
39
+ }
40
+ // support generatorFunction for forward compatbility
41
+ if (is.generatorFunction(obj) || is.asyncFunction(obj)) {
42
+ return wrapObject({ 'module.exports': obj }, opt.path)['module.exports'];
43
+ }
44
+ return obj;
45
+ },
46
+ }, opt);
47
+ const controllerBase = opt.directory;
48
+
49
+ this.loadToApp(controllerBase, 'controller', opt);
50
+ this.options.logger.info('[egg:loader] Controller loaded: %s', controllerBase);
51
+ this.timing.end('Load Controller');
52
+ },
53
+
54
+ };
55
+
56
+ // wrap the class, yield a object with middlewares
57
+ function wrapClass(Controller) {
58
+ let proto = Controller.prototype;
59
+ const ret = {};
60
+ // tracing the prototype chain
61
+ while (proto !== Object.prototype) {
62
+ const keys = Object.getOwnPropertyNames(proto);
63
+ for (const key of keys) {
64
+ // getOwnPropertyNames will return constructor
65
+ // that should be ignored
66
+ if (key === 'constructor') {
67
+ continue;
68
+ }
69
+ // skip getter, setter & non-function properties
70
+ const d = Object.getOwnPropertyDescriptor(proto, key);
71
+ // prevent to override sub method
72
+ if (is.function(d.value) && !ret.hasOwnProperty(key)) {
73
+ ret[key] = methodToMiddleware(Controller, key);
74
+ ret[key][FULLPATH] = Controller.prototype.fullPath + '#' + Controller.name + '.' + key + '()';
75
+ }
76
+ }
77
+ proto = Object.getPrototypeOf(proto);
78
+ }
79
+ return ret;
80
+
81
+ function methodToMiddleware(Controller, key) {
82
+ return function classControllerMiddleware(...args) {
83
+ const controller = new Controller(this);
84
+ // if (!this.app.config.controller || !this.app.config.controller.supportParams) {
85
+ // args = [ this ];
86
+ // }
87
+ //args = [ this ];
88
+ return utils.callFn(controller[key], args, controller);
89
+ };
90
+ }
91
+ }
92
+
93
+ // wrap the method of the object, method can receive ctx as it's first argument
94
+ function wrapObject(obj, path, prefix) {
95
+ const keys = Object.keys(obj);
96
+ const ret = {};
97
+ for (const key of keys) {
98
+ if (is.function(obj[key])) {
99
+ const names = utility.getParamNames(obj[key]);
100
+ if (names[0] === 'next') {
101
+ throw new Error(`controller \`${prefix || ''}${key}\` should not use next as argument from file ${path}`);
102
+ }
103
+ ret[key] = functionToMiddleware(obj[key]);
104
+ ret[key][FULLPATH] = `${path}#${prefix || ''}${key}()`;
105
+ } else if (is.object(obj[key])) {
106
+ ret[key] = wrapObject(obj[key], path, `${prefix || ''}${key}.`);
107
+ }
108
+ }
109
+ return ret;
110
+
111
+ function functionToMiddleware(func) {
112
+ const objectControllerMiddleware = async function(...args) {
113
+ // if (!this.app.config.controller || !this.app.config.controller.supportParams) {
114
+ // args = [ this ];
115
+ // }
116
+ return await utils.callFn(func, args, this);
117
+ };
118
+ for (const key in func) {
119
+ objectControllerMiddleware[key] = func[key];
120
+ }
121
+ return objectControllerMiddleware;
122
+ }
123
+ }
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+
5
+
6
+ module.exports = {
7
+
8
+ /**
9
+ * Load app/service
10
+ * @function EeLoader#loadService
11
+ * @param {Object} opt - LoaderOptions
12
+ * @since 1.0.0
13
+ */
14
+ loadService(opt) {
15
+ this.timing.start('Load Service');
16
+ // 载入到 app.serviceClasses
17
+ opt = Object.assign({
18
+ call: true,
19
+ caseStyle: 'lower',
20
+ fieldClass: 'serviceClasses',
21
+ directory: this.getLoadUnits().map(unit => path.join(unit.path, 'service')), // this.getLoadUnits().map(unit => path.join(unit.path, 'app/service'))
22
+ }, opt);
23
+
24
+ const servicePaths = opt.directory;
25
+ this.loadToContext(servicePaths, 'service', opt);
26
+ this.timing.end('Load Service');
27
+ },
28
+
29
+ };
@@ -0,0 +1,34 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * BaseContextClass is a base class that can be extended,
5
+ * it's instantiated in context level,
6
+ * {@link Helper}, {@link Service} is extending it.
7
+ */
8
+ class BaseContextClass {
9
+
10
+ /**
11
+ * @class
12
+ * @param {Context} ctx - context instance
13
+ * @since 1.0.0
14
+ */
15
+ constructor(ctx) {
16
+ /**
17
+ * @member {Application} BaseContextClass#app
18
+ * @since 1.0.0
19
+ */
20
+ this.app = ctx;
21
+ /**
22
+ * @member {Config} BaseContextClass#config
23
+ * @since 1.0.0
24
+ */
25
+ this.config = ctx.config;
26
+ /**
27
+ * @member {Service} BaseContextClass#service
28
+ * @since 1.0.0
29
+ */
30
+ this.service = ctx.service;
31
+ }
32
+ }
33
+
34
+ module.exports = BaseContextClass;
@@ -0,0 +1,100 @@
1
+ 'use strict';
2
+
3
+ const convert = require('koa-convert');
4
+ const is = require('is-type-of');
5
+ const path = require('path');
6
+ const fs = require('fs');
7
+ const co = require('co');
8
+ const BuiltinModule = require('module');
9
+
10
+ // Guard against poorly mocked module constructors.
11
+ const Module = module.constructor.length > 1
12
+ ? module.constructor
13
+ /* istanbul ignore next */
14
+ : BuiltinModule;
15
+
16
+ module.exports = {
17
+ extensions: Module._extensions,
18
+
19
+ loadFile(filepath) {
20
+ try {
21
+ // if not js module, just return content buffer
22
+ const extname = path.extname(filepath);
23
+ if (extname && !Module._extensions[extname]) {
24
+ return fs.readFileSync(filepath);
25
+ }
26
+ // require js module
27
+ const obj = require(filepath);
28
+ if (!obj) return obj;
29
+ // it's es module
30
+ if (obj.__esModule) return 'default' in obj ? obj.default : obj;
31
+ return obj;
32
+ } catch (err) {
33
+ err.message = `[egg-core] load file: ${filepath}, error: ${err.message}`;
34
+ throw err;
35
+ }
36
+ },
37
+
38
+ methods: [ 'head', 'options', 'get', 'put', 'patch', 'post', 'delete' ],
39
+
40
+ async callFn(fn, args, ctx) {
41
+ args = args || [];
42
+ if (!is.function(fn)) return;
43
+ if (is.generatorFunction(fn)) fn = co.wrap(fn);
44
+ return ctx ? fn.call(ctx, ...args) : fn(...args);
45
+ },
46
+
47
+ middleware(fn) {
48
+ return is.generatorFunction(fn) ? convert(fn) : fn;
49
+ },
50
+
51
+ getCalleeFromStack(withLine, stackIndex) {
52
+ stackIndex = stackIndex === undefined ? 2 : stackIndex;
53
+ const limit = Error.stackTraceLimit;
54
+ const prep = Error.prepareStackTrace;
55
+
56
+ Error.prepareStackTrace = prepareObjectStackTrace;
57
+ Error.stackTraceLimit = 5;
58
+
59
+ // capture the stack
60
+ const obj = {};
61
+ Error.captureStackTrace(obj);
62
+ let callSite = obj.stack[stackIndex];
63
+ let fileName;
64
+ /* istanbul ignore else */
65
+ if (callSite) {
66
+ // egg-mock will create a proxy
67
+ // https://github.com/eggjs/egg-mock/blob/master/lib/app.js#L174
68
+ fileName = callSite.getFileName();
69
+ /* istanbul ignore if */
70
+ if (fileName && fileName.endsWith('egg-mock/lib/app.js')) {
71
+ // TODO: add test
72
+ callSite = obj.stack[stackIndex + 1];
73
+ fileName = callSite.getFileName();
74
+ }
75
+ }
76
+
77
+ Error.prepareStackTrace = prep;
78
+ Error.stackTraceLimit = limit;
79
+
80
+ /* istanbul ignore if */
81
+ if (!callSite || !fileName) return '<anonymous>';
82
+ if (!withLine) return fileName;
83
+ return `${fileName}:${callSite.getLineNumber()}:${callSite.getColumnNumber()}`;
84
+ },
85
+
86
+ getResolvedFilename(filepath, baseDir) {
87
+ const reg = /[/\\]/g;
88
+ return filepath.replace(baseDir + path.sep, '').replace(reg, '/');
89
+ },
90
+ };
91
+
92
+
93
+ /**
94
+ * Capture call site stack from v8.
95
+ * https://github.com/v8/v8/wiki/Stack-Trace-API
96
+ */
97
+
98
+ function prepareObjectStackTrace(obj, stack) {
99
+ return stack;
100
+ }
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+
3
+ const debug = require('debug')('egg-core#sequencify');
4
+
5
+ function sequence(tasks, names, results, missing, recursive, nest, optional, parent) {
6
+ names.forEach(function(name) {
7
+ if (results.requires[name]) return;
8
+
9
+ const node = tasks[name];
10
+
11
+ if (!node) {
12
+ if (optional === true) return;
13
+ missing.push(name);
14
+ } else if (nest.includes(name)) {
15
+ nest.push(name);
16
+ recursive.push(nest.slice(0));
17
+ nest.pop(name);
18
+ } else if (node.dependencies.length || node.optionalDependencies.length) {
19
+ nest.push(name);
20
+ if (node.dependencies.length) {
21
+ sequence(tasks, node.dependencies, results, missing, recursive, nest, optional, name);
22
+ }
23
+ if (node.optionalDependencies.length) {
24
+ sequence(tasks, node.optionalDependencies, results, missing, recursive, nest, true, name);
25
+ }
26
+ nest.pop(name);
27
+ }
28
+ if (!optional) {
29
+ results.requires[name] = true;
30
+ debug('task: %s is enabled by %s', name, parent);
31
+ }
32
+ if (!results.sequence.includes(name)) {
33
+ results.sequence.push(name);
34
+ }
35
+ });
36
+ }
37
+
38
+ // tasks: object with keys as task names
39
+ // names: array of task names
40
+ module.exports = function(tasks, names) {
41
+ const results = {
42
+ sequence: [],
43
+ requires: {},
44
+ }; // the final sequence
45
+ const missing = []; // missing tasks
46
+ const recursive = []; // recursive task dependencies
47
+
48
+ sequence(tasks, names, results, missing, recursive, [], false, 'app');
49
+
50
+ if (missing.length || recursive.length) {
51
+ results.sequence = []; // results are incomplete at best, completely wrong at worst, remove them to avoid confusion
52
+ }
53
+
54
+ return {
55
+ sequence: results.sequence.filter(item => results.requires[item]),
56
+ missingTasks: missing,
57
+ recursiveDependencies: recursive,
58
+ };
59
+ };
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ const assert = require('assert');
4
+ const MAP = Symbol('Timing#map');
5
+ const LIST = Symbol('Timing#list');
6
+
7
+
8
+ class Timing {
9
+
10
+ constructor() {
11
+ this._enable = true;
12
+ this[MAP] = new Map();
13
+ this[LIST] = [];
14
+
15
+ this.init();
16
+ }
17
+
18
+ init() {
19
+ // process start time
20
+ this.start('Process Start', Date.now() - Math.floor((process.uptime() * 1000)));
21
+ this.end('Process Start');
22
+
23
+ if (typeof process.scriptStartTime === 'number') {
24
+ // js script start execute time
25
+ this.start('Script Start', process.scriptStartTime);
26
+ this.end('Script Start');
27
+ }
28
+ }
29
+
30
+ start(name, start) {
31
+ if (!name || !this._enable) return;
32
+
33
+ if (this[MAP].has(name)) this.end(name);
34
+
35
+ start = start || Date.now();
36
+ const item = {
37
+ name,
38
+ start,
39
+ end: undefined,
40
+ duration: undefined,
41
+ pid: process.pid,
42
+ index: this[LIST].length,
43
+ };
44
+ this[MAP].set(name, item);
45
+ this[LIST].push(item);
46
+ return item;
47
+ }
48
+
49
+ end(name) {
50
+ if (!name || !this._enable) return;
51
+ assert(this[MAP].has(name), `should run timing.start('${name}') first`);
52
+
53
+ const item = this[MAP].get(name);
54
+ item.end = Date.now();
55
+ item.duration = item.end - item.start;
56
+ return item;
57
+ }
58
+
59
+ enable() {
60
+ this._enable = true;
61
+ }
62
+
63
+ disable() {
64
+ this._enable = false;
65
+ }
66
+
67
+ clear() {
68
+ this[MAP].clear();
69
+ this[LIST] = [];
70
+ }
71
+
72
+ toJSON() {
73
+ return this[LIST];
74
+ }
75
+ }
76
+
77
+ module.exports = Timing;
package/index.js ADDED
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @namespace EeCore
5
+ */
6
+
7
+ /**
8
+ * @member {Appliaction} EeCore#Appliaction
9
+ * @since 1.0.0
10
+ */
11
+ const Appliaction = require('./lib/application');
12
+
13
+ /**
14
+ * @member {Controller} EeCore#Controller
15
+ * @since 1.0.0
16
+ */
17
+ const Controller = require('./core/lib/utils/base_context_class');
18
+
19
+ /**
20
+ * @member {Service} EeCore#Service
21
+ * @since 1.0.0
22
+ */
23
+ const Service = require('./core/lib/utils/base_context_class');
24
+
25
+ /**
26
+ * @member {Storage}
27
+ * @since 1.0.0
28
+ */
29
+ const Storage = require('./lib/storage/index');
30
+
31
+ /**
32
+ * @member {Utils}
33
+ * @since 1.0.0
34
+ */
35
+ const Utils = require('./utils/index');
36
+
37
+ /**
38
+ * @member {Socket}
39
+ * @since 1.0.0
40
+ */
41
+ const Socket = require('./lib/socket/io');
42
+
43
+ module.exports = {
44
+ Appliaction,
45
+ Controller,
46
+ Service,
47
+ Storage,
48
+ Socket,
49
+ Utils
50
+ };
@@ -0,0 +1,45 @@
1
+ 'use strict';
2
+
3
+ const EeLoader = require('../core/index').EeLoader;
4
+
5
+ /**
6
+ * App Loader
7
+ * @see
8
+ */
9
+ class AppLoader extends EeLoader {
10
+
11
+ /**
12
+ * loadPlugin first, then loadConfig
13
+ * @since 1.0.0
14
+ */
15
+ loadConfig() {
16
+ super.loadConfig();
17
+ }
18
+
19
+ /**
20
+ * Load all directories in convention
21
+ * @since 1.0.0
22
+ */
23
+ load() {
24
+
25
+ // app > plugin
26
+ this.loadService();
27
+
28
+ // app
29
+ this.loadController();
30
+
31
+ }
32
+
33
+ /**
34
+ * load electron modules
35
+ * @since 1.0.0
36
+ */
37
+ loadElectron() {
38
+
39
+ // 预加载功能模块
40
+ //this.loadPreload();
41
+
42
+ }
43
+ }
44
+
45
+ module.exports = AppLoader;