-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.future.js
552 lines (480 loc) · 15.9 KB
/
index.future.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
(()=> {
const _util = {}
if (module && module.exports != undefined) {
module.exports = _util
} else if (typeof window !== 'undefined') {
window.util = _util
}
// 11
// sql 验证
var SqlString = {};
var ID_GLOBAL_REGEXP = /`/g;
var QUAL_GLOBAL_REGEXP = /\./g;
var CHARS_GLOBAL_REGEXP = /[\0\b\t\n\r\x1a\"\'\\]/g; // eslint-disable-line no-control-regex
var CHARS_ESCAPE_MAP = {
'\0' : '\\0',
'\b' : '\\b',
'\t' : '\\t',
'\n' : '\\n',
'\r' : '\\r',
'\x1a' : '\\Z',
'"' : '\\"',
'\'' : '\\\'',
'\\' : '\\\\'
};
SqlString.escapeId = function escapeId(val, forbidQualified) {
if (Array.isArray(val)) {
var sql = '';
for (var i = 0; i < val.length; i++) {
sql += (i === 0 ? '' : ', ') + SqlString.escapeId(val[i], forbidQualified);
}
return sql;
} else if (forbidQualified) {
return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``') + '`';
} else {
return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``').replace(QUAL_GLOBAL_REGEXP, '`.`') + '`';
}
};
SqlString.escape = function escape(val, stringifyObjects, timeZone) {
if (val === undefined || val === null) {
return 'NULL';
}
switch (typeof val) {
case 'boolean': return (val) ? 'true' : 'false';
case 'number': return val + '';
case 'object':
if (val instanceof Date) {
return SqlString.dateToString(val, timeZone || 'local');
} else if (Array.isArray(val)) {
return SqlString.arrayToList(val, timeZone);
} else if (Buffer.isBuffer(val)) {
return SqlString.bufferToString(val);
} else if (typeof val.toSqlString === 'function') {
return String(val.toSqlString());
} else if (stringifyObjects) {
return escapeString(val.toString());
} else {
return SqlString.objectToValues(val, timeZone);
}
default: return escapeString(val);
}
};
SqlString.arrayToList = function arrayToList(array, timeZone) {
var sql = '';
for (var i = 0; i < array.length; i++) {
var val = array[i];
if (Array.isArray(val)) {
sql += (i === 0 ? '' : ', ') + '(' + SqlString.arrayToList(val, timeZone) + ')';
} else {
sql += (i === 0 ? '' : ', ') + SqlString.escape(val, true, timeZone);
}
}
return sql;
};
SqlString.format = function format(sql, values, stringifyObjects, timeZone) {
if (values == null) {
return sql;
}
if (!(values instanceof Array || Array.isArray(values))) {
values = [values];
}
var chunkIndex = 0;
var placeholdersRegex = /\?+/g;
var result = '';
var valuesIndex = 0;
var match;
while (valuesIndex < values.length && (match = placeholdersRegex.exec(sql))) {
var len = match[0].length;
if (len > 2) {
continue;
}
var value = len === 2
? SqlString.escapeId(values[valuesIndex])
: SqlString.escape(values[valuesIndex], stringifyObjects, timeZone);
result += sql.slice(chunkIndex, match.index) + value;
chunkIndex = placeholdersRegex.lastIndex;
valuesIndex++;
}
if (chunkIndex === 0) {
// Nothing was replaced
return sql;
}
if (chunkIndex < sql.length) {
return result + sql.slice(chunkIndex);
}
return result;
};
SqlString.dateToString = function dateToString(date, timeZone) {
var dt = new Date(date);
if (isNaN(dt.getTime())) {
return 'NULL';
}
var year;
var month;
var day;
var hour;
var minute;
var second;
var millisecond;
if (timeZone === 'local') {
year = dt.getFullYear();
month = dt.getMonth() + 1;
day = dt.getDate();
hour = dt.getHours();
minute = dt.getMinutes();
second = dt.getSeconds();
millisecond = dt.getMilliseconds();
} else {
var tz = convertTimezone(timeZone);
if (tz !== false && tz !== 0) {
dt.setTime(dt.getTime() + (tz * 60000));
}
year = dt.getUTCFullYear();
month = dt.getUTCMonth() + 1;
day = dt.getUTCDate();
hour = dt.getUTCHours();
minute = dt.getUTCMinutes();
second = dt.getUTCSeconds();
millisecond = dt.getUTCMilliseconds();
}
// YYYY-MM-DD HH:mm:ss.mmm
var str = zeroPad(year, 4) + '-' + zeroPad(month, 2) + '-' + zeroPad(day, 2) + ' ' +
zeroPad(hour, 2) + ':' + zeroPad(minute, 2) + ':' + zeroPad(second, 2) + '.' +
zeroPad(millisecond, 3);
return escapeString(str);
};
SqlString.bufferToString = function bufferToString(buffer) {
return 'X' + escapeString(buffer.toString('hex'));
};
SqlString.objectToValues = function objectToValues(object, timeZone) {
var sql = '';
for (var key in object) {
var val = object[key];
if (typeof val === 'function') {
continue;
}
sql += (sql.length === 0 ? '' : ', ') + SqlString.escapeId(key) + ' = ' + SqlString.escape(val, true, timeZone);
}
return sql;
};
SqlString.raw = function raw(sql) {
if (typeof sql !== 'string') {
throw new TypeError('argument sql must be a string');
}
return {
toSqlString: function toSqlString() { return sql; }
};
};
function escapeString(val) {
var chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex = 0;
var escapedVal = '';
var match;
while ((match = CHARS_GLOBAL_REGEXP.exec(val))) {
escapedVal += val.slice(chunkIndex, match.index) + CHARS_ESCAPE_MAP[match[0]];
chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex;
}
if (chunkIndex === 0) {
// Nothing was escaped
return "'" + val + "'";
}
if (chunkIndex < val.length) {
return "'" + escapedVal + val.slice(chunkIndex) + "'";
}
return "'" + escapedVal + "'";
}
function zeroPad(number, length) {
number = number.toString();
while (number.length < length) {
number = '0' + number;
}
return number;
}
function convertTimezone(tz) {
if (tz === 'Z') {
return 0;
}
var m = tz.match(/([\+\-\s])(\d\d):?(\d\d)?/);
if (m) {
return (m[1] === '-' ? -1 : 1) * (parseInt(m[2], 10) + ((m[3] ? parseInt(m[3], 10) : 0) / 60)) * 60;
}
return false;
}
// 其他类型验证
let errTypes = [
undefined,
null,
''
]
let okTypes = [
'string',
'number',
'boolean'
]
const verify = {
int (data) {
data = parseInt(data)
if (isNaN(data)) return [false, 0]
return [true, data]
},
str (data) {
data = data.toString()
if (data === '') return [false, '']
return [true, data]
},
bool (data) {
if (typeof data !== 'boolean') {
if (['true', 'false'].includes(data)) {
return [true, data === 'true' ? true : false]
}
return [false, false]
}
return [true, data]
},
arr (data) {
if (!Array.isArray(data) || data.length === 0) return [false, []]
return [true, data]
},
obj (data) {
if (typeof data !== 'object' || Array.isArray(data) || Object.keys(data).length === 0) return [false, {}]
return [true, data]
},
db (data) {
let [done, value] = verify.any(data)
return [done, SqlString.escape(value)]
},
any (data) {
// 0, false 是有效值
// 判断是否是无效类型, 即值不能设为 undefined, null, NaN, '' // isNaN('a') = true, obj !== obj 为 NaN
if (errTypes.includes(data) || data !== data) return [false, null]
if (!okTypes.includes(typeof data)) {
if (Object.keys(data).length === 0) return [false, null] // 判断是否是 空对象 {} []
}
return [true, data]
}
}
// conf 设置默认值
// TODO 设置其他限制,如长度等
_util.paramProxy = (obj, conf = {}) => {
let _err = [] // 错误堆栈
let _get = function (target, key) {
//console.log(key)
let _self = this
if (key === 'RESULT') {
_self.must = false
return _err.pop() // 出栈
}
if (typeof verify[key] === 'function' && _self.index === 0) { // 是验证类型 且为第一层
return new Proxy(obj, {
get: _get.bind({...this, type: key, index: 1})
})
} else {
let func = verify[_self.type]
let [done, value] = func(target[key]) // 改函数除了验证处理外,还设置了默认值
if (_self.must) {
if (!done) {
if (conf[_self.type] !== undefined) { // 有默认值则不报错
return conf[_self.type]
} else {
_err.push(`${typeof key === 'string' ? key : 'PARAM'} is null or TYPE err`) // 入栈
}
}
}
return value
}
}
// 异步清空错误信息
setImmediate(() => _err = [])
return new Proxy(obj, {
get: _get.bind({must: true, type: 'any', index: 0})
})
}
// 总概念,利用 proxy+解构 完成参数验证 let {a,b,c} = new Proxy({},{get(){}})
_util.hotReload = function (ROOT) {
if (typeof require === 'undefined') throw new Error('this is nodejs function')
// 只执行一次
if (global.HAS_WATCH) return
global.HAS_WATCH = true
const fs = require('fs')
const path = require('path')
const Module = require('module')
// 重写定时器
const _time_func = {
1: [setTimeout, clearTimeout],
2: [setInterval, clearInterval],
3: [setImmediate, clearImmediate]
}
const _timer = {}
const _p_time = (key) => {
const _obj_time = {}
let _func = (...param) => {
Error.captureStackTrace(_obj_time, _func) // 传入当前函数,就不会打印当前 函数调用堆栈
let _line = _obj_time.stack.split('at ')[1].split(' ')
if (_line[0].length > _line[1].length) {
if (_line[3].length > _line[0].length) {
_line = _line[3]
} else {
_line = '(' + _line[0].replace(/\s/, ')\n')
}
} else {
_line = _line[1]
}
_line = _line.substring(0, _line.length - 2).substring(1, _line.length - 2).split(':')
// 注意平台兼容性
if (process.platform === 'win32') {
_line = `${_line[0]}:${_line[1]}`
} else if (process.platform === 'linux') {
_line = _line[0]
}
let [create, clear] = _time_func[key]
let _t = create(...param)
let _data = {clear, time: _t}
if (_timer[_line]) {
_timer[_line].push(_data)
} else {
_timer[_line] = [_data]
}
return _t
}
return _func
}
global.setTimeout = _p_time(1)
global.setInterval = _p_time(2)
global.setImmediate = _p_time(3)
const r1 = require
const r2 = Module.prototype.require
const require_mmap = {}
const _getSelf = (_path) => {
let _self = r1.cache[_path]
if (_self === undefined) { // 该对象是原生对象
_self = r2(_path)
} else {
_self = _self.exports
}
return _self
}
const _require = function (_path, types) {
/*let oo = {}
Error.captureStackTrace(oo, _require) // 传入当前函数,就不会打印当前 函数调用堆栈
let _line = oo.stack.split('at ')[2].split(' ')
if (_line[0].length > _line[1].length) {
if (_line[3].length > _line[0].length) {
_line = _line[3]
} else {
_line = '(' + _line[0].replace(/\s/, ')\n')
}
} else {
_line = _line[1]
}
_line = _line.substring(0, _line.length - 2).substring(1, _line.length - 2).split(':')
// 注意平台兼容性
if (process.platform === 'win32') {
_line = `${_line[0]}:${_line[1]}`
} else if (process.platform === 'linux') {
_line = _line[0]
}
*/
_path = Module._resolveFilename(_path, this)
if (_path.substring(0, ROOT.length) !== ROOT) { // 非指定目录直接返回
return r2(_path)
}
if (types === undefined) { // 第一次加载
let file_obj = r2(_path)
types = typeof file_obj === 'function' ? ()=>{} : file_obj // proxy 代理 原对象 分函数 和 {}
} else {
_time_func[1][0](() => { // 为啥要异步加载?
let file_obj = r2(_path) // 每次热加载 都需重新 require
})
}
// TODO 需要重新代理对象,是改变了导出类型,proxy 代理 需要根据 原始对象类型来操作
// 注意代理 类型, {}, function(){}
let _proxy = require_mmap[_path]
if (_proxy !== undefined) {
_proxy.time = Date.now() // 刷新限制
return _proxy.value
}
let _origin = ()=>{}
let _p = new Proxy(_origin, {
get (target, key) {
return _getSelf(_path)[key]
},
set (target, key, value) {
let _self = _getSelf(_path)
// if (_self[key] === undefined) return false
return (_self[key] = value)
},
ownKeys (target) {
// 这样代理必须设置 代理对象为当前值
// TODO 注意类型问题
let _self = _getSelf(_path)
let _key = []
for (let _k1 in _self) {
_key.push(_k1)
_origin[_k1] = _self[_k1]
}
return _key
},
apply (target, thisArg, argumentsList) {
// TODO 可以获得调用该函数的文件地址, 然后该函数提供一个 热重载时执行的回调方法 来清除 events 类似的东西 或继承当前引用
let _self = _getSelf(_path)
if (typeof _self === 'function') return _self.bind(thisArg)(...argumentsList)
},
construct (target, args) {
let _self = _getSelf(_path)
if (typeof _self === 'function') return new _self(...args)
}
})
require_mmap[_path] = {
time: Date.now(),
value: _p
}
return _p
}
Module.prototype.require = _require
fs.watch(ROOT, {
recursive: true
}, (event, filename) => {
let _path = path.join(ROOT, filename)
// 热函数所在的目录更新不执行
if (event === 'change' && _path !== __filename && r1.cache[_path]) {
// 50 ms 内重复改动无效
let _proxy = require_mmap[_path]
if (_proxy !== undefined && _proxy.time + 500 > Date.now()) return
// 清空定时器
if (_timer[_path]) {
_timer[_path].map((f1) => f1.clear(f1.time))
_timer[_path] = []
}
let type = r1.cache[_path].exports === 'function' ? ()=>{} : {}
Reflect.deleteProperty(r1.cache, _path)
_require(_path, type)
}
})
}
// 总概念,利用 fs.watch + require + proxy 来实现 热更新,监听改变的文件,修改require.cache ,调用时 通过proxy 动态引用
_util.infoProxy = () => {
if (typeof require === 'undefined') throw new Error('this is nodejs function')
// 只执行一次
if (global.HAS_INFO_PROXY) return
global.HAS_INFO_PROXY = true
global.log = console.log
log = global.log
const obj1 = {}
const util = require('util')
console.log = function (...param) {
Error.captureStackTrace(obj1, console.log) // 传入当前函数,就不会打印当前 函数调用堆栈
let line = obj1.stack.split('at ')[1].split(' ')
if (line[0].length > line[1].length) {
if (line[3].length > line[0].length) {
line = line[3]
} else {
line = '(' + line[0].replace(/\s/, ')\n')
}
} else {
line = line[1]
}
// util.inspect(p1, {depth: null}) // depth 对象递归深度,默认2, 无限则为null
global.log(...param.map((p1) => util.inspect(p1)), `\nat ${line} `)
}
}
// 总概念,利用 Error 拿取错误堆栈,处理后得到 行数
})()