oox 0.0.9 → 0.3.0-beta1

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 (53) hide show
  1. package/README.md +4 -1
  2. package/app.js +142 -0
  3. package/bin/argv.js +59 -84
  4. package/bin/cli.js +39 -54
  5. package/bin/configurer.js +37 -66
  6. package/bin/proxyer.js +54 -88
  7. package/bin/register.js +44 -95
  8. package/bin/starter.js +66 -129
  9. package/index.js +149 -9
  10. package/index.mjs +4 -0
  11. package/modules/http/index.js +180 -0
  12. package/modules/http/utils.js +73 -0
  13. package/modules/index.js +88 -0
  14. package/modules/module.js +16 -0
  15. package/modules/socketio/client.js +101 -0
  16. package/modules/socketio/index.js +148 -0
  17. package/modules/socketio/server.js +130 -0
  18. package/modules/socketio/socket.js +4 -0
  19. package/package.json +35 -17
  20. package/types/app.d.ts +37 -0
  21. package/types/bin/argv.d.ts +8 -0
  22. package/types/bin/cli.d.ts +2 -0
  23. package/types/bin/configurer.d.ts +1 -0
  24. package/types/bin/proxyer.d.ts +1 -0
  25. package/types/bin/register.d.ts +1 -0
  26. package/types/bin/starter.d.ts +1 -0
  27. package/types/index.d.ts +70 -0
  28. package/types/modules/http/index.d.ts +47 -0
  29. package/types/modules/http/utils.d.ts +17 -0
  30. package/types/modules/index.d.ts +23 -0
  31. package/types/modules/module.d.ts +11 -0
  32. package/types/modules/socketio/client.d.ts +23 -0
  33. package/types/modules/socketio/index.d.ts +35 -0
  34. package/types/modules/socketio/server.d.ts +35 -0
  35. package/types/modules/socketio/socket.d.ts +11 -0
  36. package/types/utils.d.ts +6 -0
  37. package/utils.js +63 -0
  38. package/.gitattributes +0 -2
  39. package/global.class.js +0 -124
  40. package/global.js +0 -13
  41. package/rpc/config.class.js +0 -48
  42. package/rpc/context.class.js +0 -15
  43. package/rpc/http.class.js +0 -327
  44. package/rpc/rpc.class.js +0 -130
  45. package/rpc/rpc.interface.class.js +0 -121
  46. package/rpc/socketio.class.js +0 -231
  47. package/service/service.class.js +0 -86
  48. package/service/socketio.class.js +0 -188
  49. package/setMap.class.js +0 -67
  50. package/socketio/client.class.js +0 -190
  51. package/socketio/server.class.js +0 -222
  52. package/socketio/socket.class.js +0 -23
  53. package/util.js +0 -352
package/README.md CHANGED
@@ -1,4 +1,7 @@
1
- # OOX
1
+ ![oox-logo-dark](https://user-images.githubusercontent.com/16621637/146079784-d4d5805f-903d-44bd-998e-ff374b91ccb4.png#gh-light-mode-only)
2
+
3
+ ![oox-logo-light](https://user-images.githubusercontent.com/16621637/146079978-29a0b6fc-ec6d-4d8f-9b80-9a089f716405.png#gh-dark-mode-only)
4
+
2
5
  graceful microservice framework.
3
6
 
4
7
  ### Features
package/app.js ADDED
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.execute = exports.call = exports.on = exports.getMethods = exports.setMethods = exports.sourceKVMethods = exports.kvMethods = exports.eventHub = exports.asyncStore = exports.Context = void 0;
4
+ const node_events_1 = require("node:events");
5
+ const node_async_hooks_1 = require("node:async_hooks");
6
+ const utils_1 = require("./utils");
7
+ class Context {
8
+ // 请求溯源ID
9
+ traceId = '';
10
+ }
11
+ exports.Context = Context;
12
+ exports.asyncStore = new node_async_hooks_1.AsyncLocalStorage();
13
+ exports.eventHub = new node_events_1.EventEmitter();
14
+ /**
15
+ * sourceMethods => methods
16
+ */
17
+ let sourceMethods = {};
18
+ /**
19
+ * the kvMethods is all actions refs [has bind this]
20
+ */
21
+ exports.kvMethods = new Map();
22
+ exports.sourceKVMethods = new Map();
23
+ function setMethods(methods) {
24
+ sourceMethods = methods;
25
+ exports.kvMethods.clear();
26
+ exports.sourceKVMethods.clear();
27
+ (0, utils_1.genKVMethods)(methods, exports.kvMethods, exports.sourceKVMethods);
28
+ }
29
+ exports.setMethods = setMethods;
30
+ function getMethods() {
31
+ return sourceMethods;
32
+ }
33
+ exports.getMethods = getMethods;
34
+ function on(event, listener) {
35
+ return exports.eventHub.on(event, listener);
36
+ }
37
+ exports.on = on;
38
+ /**
39
+ * Call an Function on RPC server
40
+ * @param action
41
+ * @param params
42
+ * @param context
43
+ * @returns
44
+ */
45
+ async function call(action, params = [], context) {
46
+ if (!Array.isArray(params))
47
+ params = [params];
48
+ const { traceId } = context;
49
+ exports.eventHub.emit('request', action, params, context);
50
+ const returns = {
51
+ traceId,
52
+ success: false
53
+ };
54
+ try {
55
+ const result = await execute(action, [...params], context);
56
+ returns.body = result;
57
+ returns.success = true;
58
+ exports.eventHub.emit('success', action, params, context, result);
59
+ }
60
+ catch (error) {
61
+ returns.error = {
62
+ message: error.message,
63
+ stack: error.stack
64
+ };
65
+ exports.eventHub.emit('fail', action, params, context, error);
66
+ }
67
+ finally {
68
+ return returns;
69
+ }
70
+ }
71
+ exports.call = call;
72
+ async function execute(action, params, context) {
73
+ const __proxy = '__proxy', _proxy = '_proxy';
74
+ if (__proxy === action || _proxy === action || action.endsWith(_proxy))
75
+ throw new Error('Invalid Action[' + action + ']');
76
+ const methods = exports.kvMethods;
77
+ // 目标函数
78
+ const target = methods.get(action);
79
+ // 目标代理函数
80
+ const targetProxy = methods.get(action + _proxy);
81
+ // 即不存在目标也不存在目标代理时, 报错函数不存在
82
+ if (!target && !targetProxy)
83
+ throw new Error('Unknown Action [' + action + ']');
84
+ exports.asyncStore.enterWith(context);
85
+ // ============================ PROXY BEGIN ============================
86
+ // 最顶层代理
87
+ const topProxy = methods.get(__proxy);
88
+ if (topProxy) {
89
+ const proxyReturns = await topProxy(action, params, context);
90
+ if (proxyReturns !== undefined)
91
+ return proxyReturns;
92
+ }
93
+ // 'x.y.z' => [ 'x', 'y', 'z' ]
94
+ const nameStack = action.split('.'), size = nameStack.length - 1;
95
+ let index = -1, proxyPrefix = '';
96
+ // 根代理遍历
97
+ while (++index < size) {
98
+ // x.
99
+ // x.y.
100
+ proxyPrefix += nameStack[index] + '.';
101
+ // x.__proxy
102
+ // x.y.__proxy
103
+ const rootProxy = methods.get(proxyPrefix + __proxy);
104
+ // x.__proxy ( 'y.z', ... )
105
+ // x.y.__proxy ( 'z', ... )
106
+ if (rootProxy) {
107
+ const proxyReturns = await rootProxy(nameStack.slice(index).join('.'), params, context);
108
+ if (proxyReturns !== undefined)
109
+ return proxyReturns;
110
+ }
111
+ }
112
+ // 同级代理
113
+ const layerProxy = methods.get(proxyPrefix + _proxy);
114
+ if (layerProxy) {
115
+ const proxyReturns = await layerProxy(nameStack[index], params, context);
116
+ if (proxyReturns !== undefined)
117
+ return proxyReturns;
118
+ }
119
+ if (targetProxy) {
120
+ const proxyReturns = await targetProxy(params, context);
121
+ if (proxyReturns !== undefined)
122
+ return proxyReturns;
123
+ }
124
+ // ============================= PROXY END =============================
125
+ // make sure target action execute after all proxies
126
+ if (target) {
127
+ /*
128
+ const sourceMethod = wrappedActions.get ( action )
129
+
130
+ const middlewareNames = actionMiddlewares.get ( sourceMethod )
131
+
132
+ if ( middlewareNames && middlewareNames.length ) for ( const name of middlewareNames ) {
133
+
134
+ const middleware = middlewares.get ( name )
135
+
136
+ await middleware ( action, params, context )
137
+ }
138
+ */
139
+ return await target(...params);
140
+ }
141
+ }
142
+ exports.execute = execute;
package/bin/argv.js CHANGED
@@ -1,95 +1,70 @@
1
-
2
-
3
-
4
- exports.getAllEnvArgs = function ( ) {
5
-
6
- const args = process.argv.slice ( 2 )
7
-
8
- const env = { }
9
-
10
- for ( const arg of args ) {
11
-
12
- if ( arg.startsWith ( '--' ) ) {
13
-
14
- env [ arg.slice ( 2 ) ] = true
15
- } else if ( arg.startsWith ( '-' ) ) {
16
-
17
- env [ arg.slice ( 1 ) ] = true
18
- } else if ( !arg.includes ( '=' ) ) {
19
-
20
- env [ arg ] = true
21
- } else {
22
-
23
- const index = arg.indexOf ( '=' )
24
-
25
- const key = arg.slice ( 0, index )
26
-
27
- const val = arg.slice ( index + 1 )
28
-
29
- env [ key ] = exports.parseEnvArg ( val )
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseEnvArg = exports.getEnvArg = exports.getEnvArgs = exports.getAllEnvArgs = void 0;
4
+ function getAllEnvArgs() {
5
+ const args = process.argv.slice(2);
6
+ const env = {};
7
+ for (const arg of args) {
8
+ if (arg.startsWith('--')) {
9
+ env[arg.slice(2)] = true;
10
+ }
11
+ else if (arg.startsWith('-')) {
12
+ env[arg.slice(1)] = true;
13
+ }
14
+ else if (!arg.includes('=')) {
15
+ env[arg] = true;
16
+ }
17
+ else {
18
+ const index = arg.indexOf('=');
19
+ const key = arg.slice(0, index);
20
+ const val = arg.slice(index + 1);
21
+ env[key] = parseEnvArg(val);
30
22
  }
31
23
  }
32
-
33
- return env
24
+ return env;
34
25
  }
35
-
36
-
37
-
38
- exports.getEnvArgs = function ( names ) {
39
-
40
- const env = { }
41
-
42
- for ( let name of names ) {
43
-
44
- env [ name ] = exports.getEnvArg ( name )
26
+ exports.getAllEnvArgs = getAllEnvArgs;
27
+ function getEnvArgs(names) {
28
+ const env = {};
29
+ for (let name of names) {
30
+ env[name] = getEnvArg(name);
45
31
  }
46
-
47
- return env
32
+ return env;
48
33
  }
49
-
50
-
51
-
34
+ exports.getEnvArgs = getEnvArgs;
52
35
  // 从命令行参数列表中获取参数值
53
- exports.getEnvArg = function ( name ) {
54
-
55
- if (
56
- process.argv.includes ( name ) ||
57
- process.argv.includes ( '-' + name ) ||
58
- process.argv.includes ( '--' + name )
59
- ) {
60
-
61
- return true
62
- } else {
63
-
64
- const prefix = name + '='
65
-
66
- const [ argv ] = process.argv.filter ( arg => arg.startsWith ( prefix ) )
67
-
68
- if ( !argv ) return null
69
-
70
- const arg = argv.slice ( prefix.length )
71
-
72
- return exports.parseEnvArg ( arg )
36
+ function getEnvArg(name) {
37
+ if (process.argv.includes(name) ||
38
+ process.argv.includes('-' + name) ||
39
+ process.argv.includes('--' + name)) {
40
+ return true;
41
+ }
42
+ else {
43
+ const prefix = name + '=';
44
+ const [argv] = process.argv.filter(arg => arg.startsWith(prefix));
45
+ if (!argv)
46
+ return null;
47
+ const arg = argv.slice(prefix.length);
48
+ return parseEnvArg(arg);
73
49
  }
74
50
  }
75
-
76
-
77
-
78
- exports.parseEnvArg = function ( value ) {
79
-
80
- switch ( value ) {
81
- case 'no': return false
82
- case 'yes': return true
83
- case 'nil': return null
51
+ exports.getEnvArg = getEnvArg;
52
+ function parseEnvArg(value) {
53
+ switch (value) {
54
+ case 'no': return false;
55
+ case 'yes': return true;
56
+ case 'none':
57
+ case 'NULL':
58
+ case 'nil': return null;
84
59
  default:
85
- try {
86
-
87
- return JSON.parse ( value )
88
- } catch ( error ) {
89
-
90
- if ( value.includes ( ',' ) ) return value.split ( ',' )
91
-
92
- return value
93
- }
60
+ try {
61
+ return JSON.parse(value);
62
+ }
63
+ catch (error) {
64
+ if (value.includes(','))
65
+ return value.split(',');
66
+ return value;
67
+ }
94
68
  }
95
69
  }
70
+ exports.parseEnvArg = parseEnvArg;
package/bin/cli.js CHANGED
@@ -1,58 +1,43 @@
1
1
  #! /usr/bin/env node
2
-
3
- const chalk = require ( 'chalk' )
4
-
5
- const starter = require ( './starter' )
6
-
7
- const args = process.argv.slice ( 2 )
8
-
9
- const command = args [ 0 ]
10
-
11
- var startup = true
12
-
13
- if ( !command || [ 'help', '-h', '-help', '--help', 'version', '-v', '-version', '--version' ].includes ( command ) ) {
14
-
15
- startup = false
16
-
17
- const pkg = require ( '../package.json' )
18
-
19
- console.log ( )
20
- console.log ( 'OOX Service' )
21
- console.log ( chalk.bold`version`, chalk.bold.green`${pkg.version}` )
22
- console.log ( chalk.underline`${pkg.homepage}` )
23
- console.log ( )
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const chalk_1 = require("chalk");
5
+ const starter_1 = require("./starter");
6
+ const pkg = require("../package.json");
7
+ const args = process.argv.slice(2);
8
+ const command = args[0];
9
+ var isStartup = true;
10
+ if (!command || ['help', '-h', '-help', '--help', 'version', '-v', '-version', '--version'].includes(command)) {
11
+ isStartup = false;
12
+ console.log();
13
+ console.log('OOX Service');
14
+ console.log((0, chalk_1.bold) `version`, chalk_1.bold.green `${pkg.version}`);
15
+ console.log((0, chalk_1.underline) `${pkg.homepage}`);
16
+ console.log();
24
17
  }
25
-
26
- if ( [ 'help', '-h', '-help', '--help' ].includes ( command ) ) {
27
-
28
- console.log ( chalk.bold`Usage:` )
29
- console.log ( ' oox entry.js' )
30
- console.log ( )
31
- console.log ( ' oox entry.js port=8080' )
32
- console.log ( )
33
- console.log ( ' oox app/entry/index.js group=app/ env=envs/entry.js ignore=core' )
34
-
35
- console.log ( )
36
- console.log ( chalk.bold`Params:` )
37
-
18
+ if (['help', '-h', '-help', '--help'].includes(command)) {
19
+ console.log((0, chalk_1.bold) `Usage:`);
20
+ console.log(' oox entry.js');
21
+ console.log();
22
+ console.log(' oox entry.js port=8080');
23
+ console.log();
24
+ console.log(' oox app/entry/index.js group=app/ env=envs/entry.js ignore=core');
25
+ console.log();
26
+ console.log((0, chalk_1.bold) `Params:`);
38
27
  const params = [
39
- [ ' default-env [ file ] ', '.js or .json file, merge to global.oox' ],
40
- [ ' env [ file ] ', '.js or .json file, merge to global.oox', chalk.bold`(after default-env)` ],
41
- [ ' port [ int ] ', 'set', chalk.bold`0` ,'for random port, or any integer > 0' ],
42
- [ ' group [ dir ] ', 'service group directory, all LocalCall transform to RPC' ],
43
- [ ' ignore [ name ] ', 'set a name for LocalCall do not transform to RPC, support string | array<string>' ],
44
- [ ' http [ json ] ', 'HTTP server options, support flat name, ex: http.path=/api' ],
45
- [ ' socketio [ json ] ', 'SocketIO server options, support flat name' ],
46
- [ ' registry [ urls ] ', 'registry service url, support string | array<string>' ],
47
- [ ' template [ file ] ', 'custom Service class file path' ],
48
- [ ' origin [ urls ] ', 'set', chalk.bold`*`, 'allow any connections <Access-Control-Allow-Origin>' ],
49
- [ ' ... ', 'set params as', chalk.bold`foo=bar`+',', 'usage as', chalk.bold`global.oox.foo` ]
50
- ]
51
-
52
- params.forEach ( row => console.log ( ...row, '\n' ) )
53
-
54
- console.log ( )
28
+ [' default-env [ file ] ', '.js or .json file, merge to oox.config'],
29
+ [' env [ file ] ', '.js or .json file, merge to oox.config', (0, chalk_1.bold) `(after default-env)`],
30
+ [' port [ int ] ', 'set', (0, chalk_1.bold) `0`, 'for random port, or any integer > 0'],
31
+ [' group [ dir ] ', 'service group directory, all LocalCall transform to RPC'],
32
+ [' ignore [ name ] ', 'set a name for LocalCall do not transform to RPC, support string | array<string>'],
33
+ [' http [ json ] ', 'HTTP server options, support flat name, ex: http.path=/api'],
34
+ [' socketio [ json ] ', 'SocketIO server options, support flat name'],
35
+ [' registry [ urls ] ', 'registry service url, support string | array<string>'],
36
+ [' origin [ urls ] ', 'set', (0, chalk_1.bold) `*`, 'allow any connections <Access-Control-Allow-Origin>'],
37
+ [' ... ', 'set params as', (0, chalk_1.bold) `foo=bar` + ',', 'usage as', (0, chalk_1.bold) `oox.config.foo`]
38
+ ];
39
+ params.forEach(row => console.log(...row, '\n'));
40
+ console.log();
55
41
  }
56
-
57
-
58
- if ( startup ) starter.startup ( )
42
+ if (isStartup)
43
+ (0, starter_1.startup)();
package/bin/configurer.js CHANGED
@@ -1,78 +1,49 @@
1
-
2
- const fs = require ( 'fs' )
3
-
4
- const path = require ( 'path' )
5
-
6
- const argv = require ( './argv' )
7
-
8
-
9
-
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.configure = void 0;
4
+ const fs = require("node:fs");
5
+ const path = require("node:path");
6
+ const argv = require("./argv");
10
7
  /**
11
8
  * x.y=1 => { x: { y: 1 } }
12
- * @param {*} env
13
9
  */
14
- function mergeFlatEnv ( env ) {
15
-
16
- for ( const key of Object.keys ( env ) ) {
17
-
10
+ function mergeFlatEnv(env) {
11
+ for (const key of Object.keys(env)) {
18
12
  // x.y.z
19
- if ( key.includes ( '.' ) && !key.startsWith ( '.' ) && !key.endsWith ( '.' ) ) {
20
-
21
- const subKeys = key.split ( '.' )
22
-
23
- const valueKey = subKeys.pop ( )
24
-
25
- let tmpEnv = env
26
-
27
- for ( subKey of subKeys ) {
28
-
29
- if ( subKey in tmpEnv ) { } else {
30
-
31
- tmpEnv [ subKey ] = { }
13
+ if (key.includes('.') && !key.startsWith('.') && !key.endsWith('.')) {
14
+ const subKeys = key.split('.');
15
+ const valueKey = subKeys.pop();
16
+ let tmpEnv = env;
17
+ for (const subKey of subKeys) {
18
+ if (subKey in tmpEnv) { }
19
+ else {
20
+ tmpEnv[subKey] = {};
32
21
  }
33
-
34
- tmpEnv = tmpEnv [ subKey ]
22
+ tmpEnv = tmpEnv[subKey];
35
23
  }
36
-
37
- tmpEnv [ valueKey ] = env [ key ]
24
+ tmpEnv[valueKey] = env[key];
38
25
  }
39
26
  }
40
27
  }
41
-
42
-
43
-
44
- exports.configure = ( ) => {
45
-
46
- let env = Object.create ( null )
47
-
48
- const defaultEnvPath = argv.getEnvArg ( 'default-env' )
49
-
50
- if ( defaultEnvPath && fs.existsSync ( defaultEnvPath ) ) {
51
-
52
- Object.assign ( env, require ( path.resolve ( defaultEnvPath ) ) )
28
+ function configure() {
29
+ let env = Object.create(null);
30
+ const defaultEnvPath = argv.getEnvArg('default-env');
31
+ if (defaultEnvPath && fs.existsSync(defaultEnvPath)) {
32
+ Object.assign(env, require(path.resolve(defaultEnvPath)));
53
33
  }
54
-
55
-
56
-
57
- const envPath = argv.getEnvArg ( 'env' )
58
-
59
- if ( envPath && fs.existsSync ( envPath ) ) {
60
-
61
- Object.assign ( env, require ( path.resolve ( envPath ) ) )
34
+ const envPath = argv.getEnvArg('env');
35
+ if (envPath && fs.existsSync(envPath)) {
36
+ Object.assign(env, require(path.resolve(envPath)));
62
37
  }
63
-
64
- Object.assign ( env, argv.getAllEnvArgs ( ) )
65
-
66
- mergeFlatEnv ( env )
67
-
68
- if ( 'string' === typeof env.ignore ) env.ignore = env.ignore.split ( ',' )
69
-
70
- if ( 'string' === typeof env.registry ) env.registry = env.registry.split ( ',' )
71
-
72
- if ( 'string' === typeof env.origin && env.origin.includes ( ',' ) ) {
73
-
74
- env.origin = env.origin.split ( ',' )
38
+ Object.assign(env, argv.getAllEnvArgs());
39
+ mergeFlatEnv(env);
40
+ if ('string' === typeof env.ignore)
41
+ env.ignore = env.ignore.split(',');
42
+ if ('string' === typeof env.registry)
43
+ env.registry = env.registry.split(',');
44
+ if ('string' === typeof env.origin && env.origin.includes(',')) {
45
+ env.origin = env.origin.split(',');
75
46
  }
76
-
77
- return env
78
- }
47
+ return env;
48
+ }
49
+ exports.configure = configure;