oox 0.3.0-beta9 → 0.3.1

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 (45) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +29 -32
  3. package/app.js +131 -143
  4. package/bin/argv.js +63 -70
  5. package/bin/cli.js +57 -43
  6. package/bin/configurer.js +60 -62
  7. package/bin/loader.mjs +392 -279
  8. package/bin/proxy-import.js +12 -0
  9. package/bin/proxy-require.js +88 -0
  10. package/bin/register.js +46 -55
  11. package/bin/starter.js +63 -66
  12. package/index.js +155 -168
  13. package/index.mjs +4 -4
  14. package/logger.js +25 -40
  15. package/modules/http/index.js +234 -192
  16. package/modules/http/utils.js +74 -73
  17. package/modules/index.js +86 -88
  18. package/modules/module.js +11 -16
  19. package/modules/socketio/client.js +97 -101
  20. package/modules/socketio/index.js +171 -168
  21. package/modules/socketio/server.js +188 -136
  22. package/modules/socketio/socket.js +1 -4
  23. package/package.json +14 -12
  24. package/types/app.d.ts +50 -51
  25. package/types/bin/argv.d.ts +8 -8
  26. package/types/bin/cli.d.ts +6 -2
  27. package/types/bin/configurer.d.ts +3 -1
  28. package/types/bin/proxy-import.d.ts +4 -0
  29. package/types/bin/proxy-require.d.ts +5 -0
  30. package/types/bin/register.d.ts +1 -1
  31. package/types/bin/starter.d.ts +5 -1
  32. package/types/index.d.ts +78 -76
  33. package/types/logger.d.ts +5 -4
  34. package/types/modules/http/index.d.ts +58 -47
  35. package/types/modules/http/utils.d.ts +14 -17
  36. package/types/modules/index.d.ts +24 -24
  37. package/types/modules/module.d.ts +11 -13
  38. package/types/modules/socketio/client.d.ts +23 -23
  39. package/types/modules/socketio/index.d.ts +37 -37
  40. package/types/modules/socketio/server.d.ts +44 -35
  41. package/types/modules/socketio/socket.d.ts +11 -11
  42. package/types/utils.d.ts +6 -6
  43. package/utils.js +57 -63
  44. package/bin/proxyer.js +0 -61
  45. package/types/bin/proxyer.d.ts +0 -1
@@ -1,192 +1,234 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HTTPConfig = void 0;
4
- const http = require("node:http");
5
- const node_querystring_1 = require("node:querystring");
6
- const utils_1 = require("./utils");
7
- const oox = require("../../index");
8
- const module_1 = require("../module");
9
- class HTTPConfig extends module_1.ModuleConfig {
10
- // listen port
11
- port = 0;
12
- // service path
13
- path = '/';
14
- // browser cross origin
15
- origin = '';
16
- }
17
- exports.HTTPConfig = HTTPConfig;
18
- class HTTPModule extends module_1.default {
19
- name = 'http';
20
- config = new HTTPConfig;
21
- server = null;
22
- setConfig(config) {
23
- Object.assign(this.config, config);
24
- if (!config.hasOwnProperty('port')) {
25
- this.config.port = oox.config.port;
26
- }
27
- if (!config.hasOwnProperty('origin')) {
28
- this.config.origin = oox.config.origin;
29
- }
30
- }
31
- getConfig() {
32
- return this.config;
33
- }
34
- /**
35
- * start http service
36
- */
37
- async serve() {
38
- await this.stop();
39
- const { port } = this.config;
40
- this.server = http.createServer(this.call.bind(this));
41
- this.server.listen(port);
42
- const address = this.server.address();
43
- if (!address || 'object' !== typeof address)
44
- throw new Error('Cannot read http server port');
45
- this.config.port = address.port;
46
- }
47
- /**
48
- * stop http service
49
- */
50
- stop() {
51
- if (this.server && this.server.listening)
52
- return new Promise((resolve, reject) => {
53
- this.server.close(function (error) {
54
- if (error)
55
- reject(error);
56
- else
57
- resolve();
58
- });
59
- });
60
- }
61
- /**
62
- * browser cross origin
63
- */
64
- cors(request, response) {
65
- // origin checking
66
- const origin = this.config.origin;
67
- const requestOrigin = request.headers.origin;
68
- if (origin && requestOrigin) {
69
- if (origin === '*' || origin === requestOrigin || Array.isArray(origin) && origin.includes(requestOrigin)) {
70
- response.setHeader('Access-Control-Allow-Origin', requestOrigin);
71
- response.setHeader('Vary', 'Origin');
72
- }
73
- else {
74
- response.statusCode = 403;
75
- response.end();
76
- return false;
77
- }
78
- response.setHeader('Access-Control-Max-Age', 3600);
79
- response.setHeader('Access-Control-Allow-Headers', 'x-caller,content-type');
80
- response.setHeader('Access-Control-Allow-Methods', '*');
81
- }
82
- if (request.method === 'OPTIONS') {
83
- response.statusCode = 204;
84
- response.end();
85
- return false;
86
- }
87
- return true;
88
- }
89
- /**
90
- * HTTP-RPC服务器请求监听方法
91
- */
92
- async call(request, response) {
93
- if (request.url !== this.config.path) {
94
- const error = {
95
- message: 'Invalid URL',
96
- stack: ''
97
- };
98
- Error.captureStackTrace(error);
99
- return this.respond(request, response, {
100
- success: false,
101
- error
102
- });
103
- }
104
- if (!this.cors(request, response))
105
- return;
106
- let body = Object.create(null);
107
- try {
108
- if ('GET' === request.method) {
109
- body = (0, node_querystring_1.parse)(request.url.split('?').pop());
110
- }
111
- else {
112
- body = await (0, utils_1.parseHTTPBody)(request);
113
- }
114
- if (!body || 'object' !== typeof body)
115
- throw new Error('Content Invalid');
116
- }
117
- catch (error) {
118
- return this.respond(request, response, {
119
- success: false,
120
- error: {
121
- message: error.message,
122
- stack: error.stack
123
- }
124
- });
125
- }
126
- // global unique id
127
- const traceId = String(request.headers['x-trace-id'] || '');
128
- // service name, required
129
- const caller = String(request.headers['x-caller'] || 'anonymous');
130
- // client ip or caller service ip
131
- const ip = String(request.headers['x-ip'] || request.socket.remoteAddress || '');
132
- // startup client ip
133
- const sourceIP = String(request.headers['x-real-ip'] || '');
134
- const { action = 'index', params = [] } = body;
135
- const context = oox.genContext({ traceId, caller, sourceIP, ip, callerId: '' });
136
- const format = await oox.call(action, params, context);
137
- this.respond(request, response, format);
138
- }
139
- /**
140
- * HTTP Response Catch
141
- */
142
- respond(request, response, format) {
143
- let formatString = '';
144
- try {
145
- formatString = JSON.stringify(format);
146
- }
147
- catch ({ message, stack }) {
148
- delete format.body;
149
- format.success = false;
150
- format.error = {
151
- message,
152
- stack
153
- };
154
- formatString = JSON.stringify(format);
155
- }
156
- response.setHeader('Content-Type', 'application/json');
157
- response.setHeader('Content-Length', Buffer.byteLength(formatString));
158
- response.end(formatString);
159
- }
160
- /**
161
- * HTTP RPC
162
- */
163
- async rpc(url, action, params, context) {
164
- if (!context || !context.traceId) {
165
- context = oox.getContext();
166
- }
167
- const { traceId, caller, sourceIP } = context;
168
- const headers = {
169
- 'Content-Type': 'application/json',
170
- 'x-trace-id': String(traceId),
171
- };
172
- if (caller)
173
- headers['x-caller'] = String(caller);
174
- if (sourceIP)
175
- headers['x-real-ip'] = sourceIP;
176
- // headers [ 'x-ip' ] = getIPAddress ( 4 ) [ 0 ]
177
- const format = await (0, utils_1.httpRequest)(url, {
178
- headers
179
- }, JSON.stringify({ action, params }));
180
- if ('string' === typeof format)
181
- throw new Error(format);
182
- const { error, body } = format;
183
- if (error) {
184
- const asyncError = new Error(error.message);
185
- throw asyncError;
186
- }
187
- else {
188
- return body;
189
- }
190
- }
191
- }
192
- exports.default = HTTPModule;
1
+ import * as http from 'node:http';
2
+ import * as https from 'node:https';
3
+ import { httpRequest, parseHTTPBody } from './utils.js';
4
+ import * as oox from '../../index.js';
5
+ import Module, { ModuleConfig } from '../module.js';
6
+ export class HTTPConfig extends ModuleConfig {
7
+ // listen port
8
+ port = 0;
9
+ // service path
10
+ path = '/';
11
+ // browser cross origin
12
+ origin = '';
13
+ // https options
14
+ ssl = {
15
+ // enable https
16
+ enabled: false,
17
+ // ssl certificate path
18
+ cert: '',
19
+ // ssl private key path
20
+ key: '',
21
+ // ssl ca path
22
+ ca: ''
23
+ };
24
+ }
25
+ export default class HTTPModule extends Module {
26
+ name = 'http';
27
+ config = new HTTPConfig;
28
+ server = null;
29
+ getUrl() {
30
+ const { host } = oox.config;
31
+ const { port, path } = this.config;
32
+ const protocol = this.config.ssl.enabled ? `https:` : `http:`;
33
+ return `${protocol}//${host}:${port}${path}`;
34
+ }
35
+ setConfig(config) {
36
+ Object.assign(this.config, config);
37
+ if (!config.hasOwnProperty('port')) {
38
+ this.config.port = oox.config.port;
39
+ }
40
+ if (!config.hasOwnProperty('origin')) {
41
+ this.config.origin = oox.config.origin;
42
+ }
43
+ }
44
+ getConfig() {
45
+ return this.config;
46
+ }
47
+ /**
48
+ * start http service
49
+ */
50
+ async serve() {
51
+ await this.stop();
52
+ const { port, ssl } = this.config;
53
+ if (ssl.enabled) {
54
+ const fs = await import('node:fs');
55
+ const options = {
56
+ key: ssl.key ? fs.readFileSync(ssl.key) : null,
57
+ cert: ssl.cert ? fs.readFileSync(ssl.cert) : null,
58
+ ca: ssl.ca ? fs.readFileSync(ssl.ca) : null
59
+ };
60
+ if (!options.key || !options.cert) {
61
+ throw new Error('HTTPS enabled but missing key or cert');
62
+ }
63
+ this.server = https.createServer(options, this.requestHandler.bind(this));
64
+ }
65
+ else {
66
+ this.server = http.createServer(this.requestHandler.bind(this));
67
+ }
68
+ this.server.listen(port);
69
+ const address = this.server.address();
70
+ if (!address || 'object' !== typeof address)
71
+ throw new Error('Cannot read http server port');
72
+ this.config.port = address.port;
73
+ }
74
+ /**
75
+ * stop http service
76
+ */
77
+ stop() {
78
+ if (this.server && this.server.listening)
79
+ return new Promise((resolve, reject) => {
80
+ this.server.close(function (error) {
81
+ if (error)
82
+ reject(error);
83
+ else
84
+ resolve();
85
+ });
86
+ });
87
+ }
88
+ /**
89
+ * browser cross origin
90
+ */
91
+ cors(request, response) {
92
+ // origin checking
93
+ const origin = this.config.origin;
94
+ const requestOrigin = request.headers.origin;
95
+ if (origin && requestOrigin) {
96
+ if (origin === '*' ||
97
+ origin === requestOrigin ||
98
+ (Array.isArray(origin) && origin.includes(requestOrigin))) {
99
+ response.setHeader('Access-Control-Allow-Origin', requestOrigin);
100
+ response.setHeader('Vary', 'Origin');
101
+ }
102
+ else {
103
+ response.statusCode = 403;
104
+ response.end();
105
+ return false;
106
+ }
107
+ response.setHeader('Access-Control-Max-Age', 3600);
108
+ response.setHeader('Access-Control-Allow-Headers', 'x-caller,content-type');
109
+ response.setHeader('Access-Control-Allow-Methods', '*');
110
+ }
111
+ if (request.method === 'OPTIONS') {
112
+ response.statusCode = 204;
113
+ response.end();
114
+ return false;
115
+ }
116
+ return true;
117
+ }
118
+ async requestHandler(request, response) {
119
+ if (!this.cors(request, response))
120
+ return;
121
+ const url = new URL(request.url, request.headers.origin || 'http://localhost');
122
+ if (url.pathname === this.config.path) {
123
+ await this.call(request, response);
124
+ }
125
+ else {
126
+ const error = new Error('Invalid URL');
127
+ return this.respond(request, response, {
128
+ success: false,
129
+ error: {
130
+ message: error.message,
131
+ stack: error.stack
132
+ }
133
+ });
134
+ }
135
+ }
136
+ /**
137
+ * 从请求里获取调用的接口和参数
138
+ */
139
+ async getCallArgsFromRequest(request) {
140
+ const args = await parseHTTPBody(request);
141
+ if (!args || 'object' !== typeof args || !args.action)
142
+ throw new Error('Content Invalid');
143
+ else
144
+ return args;
145
+ }
146
+ /**
147
+ * HTTP-RPC服务器请求监听方法
148
+ */
149
+ async call(request, response) {
150
+ let callArgs = Object.create(null);
151
+ try {
152
+ callArgs = await this.getCallArgsFromRequest(request);
153
+ }
154
+ catch (error) {
155
+ return this.respond(request, response, {
156
+ success: false,
157
+ error: {
158
+ message: error.message,
159
+ stack: error.stack
160
+ }
161
+ });
162
+ }
163
+ // global unique id
164
+ const traceId = String(request.headers['x-trace-id'] || '');
165
+ // service name, required
166
+ const caller = String(request.headers['x-caller'] || 'anonymous');
167
+ // client ip or caller service ip
168
+ const ip = String(request.headers['x-ip'] || request.socket.remoteAddress || '');
169
+ // startup client ip
170
+ const sourceIP = String(request.headers['x-real-ip'] || '');
171
+ const { action, params = [] } = callArgs;
172
+ const context = oox.genContext({ traceId, caller, sourceIP, ip, callerId: '' });
173
+ const format = await oox.call(action, params, context);
174
+ this.respond(request, response, format);
175
+ }
176
+ /**
177
+ * HTTP Response Catch
178
+ */
179
+ respond(_request, response, returns) {
180
+ let returnsString = '';
181
+ if (!oox.config.errorStack && returns.error) {
182
+ // 不返回错误调用栈信息
183
+ delete returns.error.stack;
184
+ }
185
+ try {
186
+ returnsString = JSON.stringify(returns);
187
+ }
188
+ catch ({ message, stack }) {
189
+ delete returns.body;
190
+ returns.success = false;
191
+ returns.error = {
192
+ message
193
+ };
194
+ if (oox.config.errorStack) {
195
+ // 返回错误调用栈信息
196
+ returns.error.stack = stack;
197
+ }
198
+ returnsString = JSON.stringify(returns);
199
+ }
200
+ response.setHeader('Content-Type', 'application/json');
201
+ response.setHeader('Content-Length', Buffer.byteLength(returnsString));
202
+ response.end(returnsString);
203
+ }
204
+ /**
205
+ * HTTP RPC
206
+ */
207
+ async rpc(url, action, params, context) {
208
+ if (!context || !context.traceId) {
209
+ context = oox.getContext();
210
+ }
211
+ const { traceId, caller, sourceIP } = context;
212
+ const headers = {
213
+ 'Content-Type': 'application/json',
214
+ 'x-trace-id': String(traceId),
215
+ };
216
+ if (caller)
217
+ headers['x-caller'] = String(caller);
218
+ if (sourceIP)
219
+ headers['x-real-ip'] = sourceIP;
220
+ // headers [ 'x-ip' ] = getIPAddress ( 4 ) [ 0 ]
221
+ const format = await httpRequest(url, {
222
+ headers
223
+ }, JSON.stringify({ action, params }));
224
+ if ('string' === typeof format)
225
+ throw new Error(format);
226
+ const { success, error, body } = format;
227
+ if (success)
228
+ return body;
229
+ else if (error)
230
+ throw new Error(error.message);
231
+ else
232
+ throw new Error('[RPC] Unknown Error');
233
+ }
234
+ }
@@ -1,73 +1,74 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.httpRequest = exports.parseHTTPBody = exports.stream2buffer = void 0;
4
- const http = require("node:http");
5
- /**
6
- * Stream => Buffer
7
- */
8
- function stream2buffer(stream, totalLength = 0) {
9
- return new Promise(function (resolve, reject) {
10
- let buffers = [];
11
- stream.on('error', reject);
12
- if (totalLength) {
13
- stream.on('data', function (data) { buffers.push(data); });
14
- }
15
- else {
16
- stream.on('data', function (data) {
17
- buffers.push(data);
18
- totalLength += data.length;
19
- });
20
- }
21
- stream.on('end', function () { resolve(Buffer.concat(buffers, totalLength)); });
22
- });
23
- }
24
- exports.stream2buffer = stream2buffer;
25
- /**
26
- * Request => JSONObject
27
- */
28
- async function parseHTTPBody(request) {
29
- if (request.method === 'GET')
30
- return null;
31
- let contentType = request.headers['content-type'];
32
- // application/json; charset=utf-8
33
- if (contentType)
34
- contentType = contentType.split(';')[0].trim();
35
- const contentSize = request.headers['content-length'];
36
- const buffer = await stream2buffer(request, +contentSize || 0);
37
- if (contentSize && buffer.length !== +contentSize)
38
- throw new Error('Content-Length Incorrect');
39
- const bodyString = buffer.toString();
40
- if ('application/json' === contentType) {
41
- return JSON.parse(bodyString);
42
- }
43
- else {
44
- return bodyString;
45
- }
46
- }
47
- exports.parseHTTPBody = parseHTTPBody;
48
- /**
49
- * http request
50
- */
51
- function httpRequest(url, options, body) {
52
- return new Promise(function (resolve, reject) {
53
- const request = http.request(url, options, async function (response) {
54
- try {
55
- const result = await parseHTTPBody(response);
56
- resolve(result);
57
- }
58
- catch (error) {
59
- const decoration = new Error(`${response.statusCode} - ${error.message}`);
60
- reject(decoration);
61
- }
62
- });
63
- request.on('error', reject);
64
- if (body) {
65
- request.method = 'POST';
66
- request.setHeader('Content-Type', 'application/json');
67
- request.setHeader('Content-Length', Buffer.byteLength(body));
68
- request.write(body);
69
- }
70
- request.end();
71
- });
72
- }
73
- exports.httpRequest = httpRequest;
1
+ import * as http from 'node:http';
2
+ import * as https from 'node:https';
3
+ /**
4
+ * Stream => Buffer
5
+ */
6
+ export function stream2buffer(stream, totalLength = 0) {
7
+ return new Promise(function (resolve, reject) {
8
+ let buffers = [];
9
+ stream.on('error', reject);
10
+ if (totalLength) {
11
+ stream.on('data', function (data) { buffers.push(data); });
12
+ }
13
+ else {
14
+ stream.on('data', function (data) {
15
+ buffers.push(data);
16
+ totalLength += data.length;
17
+ });
18
+ }
19
+ stream.on('end', function () { resolve(Buffer.concat(buffers, totalLength)); });
20
+ });
21
+ }
22
+ /**
23
+ * Request => JSONObject
24
+ */
25
+ export async function parseHTTPBody(request) {
26
+ if (request.method === 'GET')
27
+ return null;
28
+ let contentType = request.headers['content-type'];
29
+ // application/json; charset=utf-8
30
+ if (contentType)
31
+ contentType = contentType.split(';')[0].trim();
32
+ const contentSize = request.headers['content-length'];
33
+ if (!contentSize)
34
+ return null;
35
+ const buffer = await stream2buffer(request, +contentSize || 0);
36
+ if (contentSize && buffer.length !== +contentSize)
37
+ throw new Error('Content-Length Incorrect');
38
+ switch (contentType) {
39
+ case 'application/json':
40
+ return JSON.parse(buffer.toString());
41
+ case 'text/plain':
42
+ return buffer.toString();
43
+ default:
44
+ return buffer;
45
+ }
46
+ }
47
+ /**
48
+ * http request
49
+ */
50
+ export function httpRequest(url, options, body) {
51
+ return new Promise(function (resolve, reject) {
52
+ const urlObj = typeof url === 'string' ? new URL(url) : url;
53
+ const protocol = urlObj.protocol;
54
+ const client = protocol === 'https:' ? https : http;
55
+ const request = client.request(url, options, async function (response) {
56
+ try {
57
+ const result = await parseHTTPBody(response);
58
+ resolve(result);
59
+ }
60
+ catch (error) {
61
+ const decoration = new Error(`${response.statusCode} - ${error.message}`);
62
+ reject(decoration);
63
+ }
64
+ });
65
+ request.on('error', reject);
66
+ if (body) {
67
+ request.method = 'POST';
68
+ request.setHeader('Content-Type', 'application/json');
69
+ request.setHeader('Content-Length', Buffer.byteLength(body));
70
+ request.write(body);
71
+ }
72
+ request.end();
73
+ });
74
+ }