jsir 2.2.2 → 2.2.4

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.
package/cmd/oaa.js CHANGED
@@ -3,15 +3,15 @@ const $lib = require('../deps/util');
3
3
  const {
4
4
  getLibDataDir, trim, regEach, getConfig, mkdir, reget,
5
5
  getCbText, e, sleep, objDataFile, vl, md5, BigNumber,
6
- arrayDataFile, infoStr, warnStr, errorStack,
6
+ arrayDataFile, infoStr, warnStr,
7
7
  getInfo, ei, pad, msgStr, getType,
8
- isArgsMatch, draftQuery, setConfig,
8
+ isMatch, draftQuery, setConfig,
9
9
  getTextComments, importG, requireG,
10
10
  clearConsole, trimText, getFnArgsStr,
11
11
  createConsole, setTips, delTips,
12
12
  getEditor, errorStr, getConfigDir,
13
13
  getFullPath, parseUniqueName, toUniqueName, isJsirFileName, toJsirFileName,
14
- fileJson, fileLock
14
+ fileJson, fileLock, getOr
15
15
  } = $lib;
16
16
  const _args = process.argv.slice(2).map(trim);
17
17
  const evalCode = require('../deps/evalCode')
@@ -42,8 +42,8 @@ let _haveWrapperInput = true
42
42
  let _noAppendNextLine = true
43
43
  let _onLazyTempCode = null
44
44
 
45
- const _onLazyGetMap = {}
46
- const _data = {}
45
+ const _onLazyGetMap = Object.create(null)
46
+ const _data = Object.create(null)
47
47
  const _lazyTime = 5 * 60 * 1000
48
48
  const _dealOnLazyGet = (key, onLazyTempCode) => {
49
49
  if (_noAppendNextLine || !_onLazyGetMap[key]) {
@@ -120,8 +120,8 @@ const $data = {
120
120
  delete _data[key]
121
121
  return val
122
122
  },
123
- keys: () => Object.keys(_data),
124
- have: (key) => vl(_data[key])
123
+ key: () => Object.keys(_data),
124
+ has: (key) => vl(_data[key])
125
125
  }
126
126
  const $file = {
127
127
  json: fileJson,
@@ -534,7 +534,7 @@ function listCmd(tmpMap) {
534
534
  let suffix = getJsirFileSuffix(pair[1])
535
535
  let item = {
536
536
  key: ' ' + i,
537
- name: pair[0] + '/' + name.replace(/^[eif]\s+/, ''),
537
+ name: pair[0] + '/' + name,
538
538
  type: [_types[name.split(/\s+/)[0]] || 'note', suffix].map(trim).join(".")
539
539
  }
540
540
  items.push(item)
@@ -645,8 +645,8 @@ async function dealStar(text) {
645
645
  }
646
646
  let items = text.split(/\s+/);
647
647
  let rows = []
648
- if (_cmdMap[items[0]]) {
649
- rows.push(...await dealStarCmd([], _cmdMap[items[0]], '.'))
648
+ if (_cmdMap.hasOwnProperty(items[0])) {
649
+ rows.push(...await dealStarCmd([], _cmdMap[items[0]], items.slice(1).join(' ')))
650
650
  } else if (items[0].indexOf("/") !== -1) {
651
651
  await dealStartGlobalMode(rows, items, text);
652
652
  } else {
@@ -657,7 +657,7 @@ async function dealStar(text) {
657
657
  await dealStartGlobalMode(rows, items, text);
658
658
  }
659
659
  }
660
- rows = rows.filter(i => !i.name.startsWith('_'));
660
+ rows = rows.filter(i => !i.name || (!i.name.startsWith('_') && i.name.indexOf('._') === -1));
661
661
  if (rows.length === 0) {
662
662
  console.warn("no items")
663
663
  } else {
@@ -679,9 +679,60 @@ function dealStarGlobal(items, text) {
679
679
  return rows;
680
680
  }
681
681
 
682
+ function wrapperClassLine(className, classLines) {
683
+ let str = trimText(classLines.join('\n'))
684
+ let results = []
685
+ for (let line of str.split('\n')) {
686
+ let asyncMethod = false;
687
+ if (line.startsWith("async ")) {
688
+ // 检查是否为异步方法
689
+ asyncMethod = true;
690
+ line = line.replace("async ", "").trim(); // 去除 'async ' 前缀
691
+ }
692
+ const methodMatch = line.match(/^\w+\s*\(/);
693
+ if (methodMatch) {
694
+ let prefix = `function ${className}.`;
695
+ if (asyncMethod) {
696
+ prefix = "async " + prefix;
697
+ }
698
+ results.push(prefix + line.trim());
699
+ continue;
700
+ }
701
+ results.push(line)
702
+ }
703
+ return results;
704
+ }
705
+
706
+ function wrapperClass(lines) {
707
+ let results = [];
708
+ let className = null;
709
+ let inClass = false;
710
+
711
+ let classLines = []
712
+ for (let line of lines) {
713
+ if (line.startsWith("class ")) {
714
+ inClass = true;
715
+ className = reget(line, /^class\s+(\w+)/);
716
+ continue
717
+ } else if (inClass && line.startsWith("}")) {
718
+ inClass = false
719
+ results.push(...wrapperClassLine(className, classLines));
720
+ classLines = []
721
+ continue;
722
+ }
723
+
724
+ if (inClass) {
725
+ classLines.push(line)
726
+ } else {
727
+ results.push(line);
728
+ }
729
+ }
730
+ return results;
731
+ }
732
+
682
733
  function dealStarCmd(rows, cmd, filterStr) {
683
734
  let content = String(fs.readFileSync(getFullPath(cmd)));
684
- let lines = content.split('\n');
735
+ let lines = wrapperClass(content.split('\n'));
685
736
  let capturingFunction = false;
686
737
  let inMultiLineComment = false;
687
738
  let potentialComments = [];
@@ -719,10 +770,10 @@ function dealStarCmd(rows, cmd, filterStr) {
719
770
  }
720
771
 
721
772
  // Check for function start
722
- if ((line.startsWith('function') || line.startsWith('async function'))) {
723
- let _fnName = reget(line, /function\s+(\w+)\s*\(/);
773
+ if ((line.startsWith('function ') || line.startsWith('async function '))) {
774
+ let _fnName = reget(line, /function\s+([\w.]+)\s*\(/);
724
775
  let matchKey = _fnName + "(" + getFnArgsStr(lines.slice(index, index + 9).join("\n")) + ")"
725
- if (isArgsMatch(matchKey, [filterStr])) {
776
+ if (isMatch(matchKey, filterStr)) {
726
777
  fnName = _fnName;
727
778
  fnType = line.startsWith('async') ? 'AsyncFunction' : 'Function';
728
779
  capturingFunction = true;
@@ -741,7 +792,9 @@ function dealStarCmd(rows, cmd, filterStr) {
741
792
  let functionContent = functionLines.join('\n');
742
793
  let commentContent = trimText(comments.join('\n'));
743
794
  let row = getInfo(functionContent, fnName, fnType);
744
- row.value = infoStr(cmd) + ' ' + getCmdMd5Key(parseUniqueName(cmd)[1]) + '\n' + [commentContent, row.value].filter(i => trim(i)).join("\n");
795
+ let pair = parseUniqueName(cmd);
796
+ row.value = infoStr(pair[0] + '/' + trimJsirFileName(pair[1])) + ' ' +
797
+ getCmdMd5Key(parseUniqueName(cmd)[1]) + '\n' + [commentContent, row.value].filter(i => trim(i)).join("\n");
745
798
  rows.push(row);
746
799
 
747
800
  resetState();
@@ -767,7 +820,7 @@ async function dealStarCase(result, matchStrs, cmd) {
767
820
  if (type === 'Function' || type === 'AsyncFunction') {
768
821
  matchKey = key + "(" + getFnArgsStr(String(obj)) + ")";
769
822
  }
770
- if (matchStrs.length === 0 || isArgsMatch(matchKey, [matchStrs.join(' ')])){
823
+ if (matchStrs.length === 0 || isMatch(matchKey, matchStrs.join(' '))){
771
824
  rows.push(getInfo(result[key], key))
772
825
  }
773
826
  }
@@ -914,7 +967,7 @@ const keywordDef = {
914
967
  args: {
915
968
  queryParams: 'string matching, [,] represents all, keywords can be omitted'
916
969
  },
917
- short: 'l'
970
+ short: 'L'
918
971
  },
919
972
  clear: {
920
973
  comment: 'Clear task',
@@ -1024,11 +1077,6 @@ const keywordDef = {
1024
1077
  exeFn: async (args) => {
1025
1078
  let uniqueName = _cmdMap[args[0]];
1026
1079
  if (uniqueName) {
1027
- let isExe = uniqueName &&uniqueName.split("/")[1].startsWith('e ');
1028
- if (!isExe) {
1029
- console.warn("not exe file")
1030
- return;
1031
- }
1032
1080
  let configDir = `${getLibDataDir()}/config`;
1033
1081
  mkdir(configDir)
1034
1082
  ei(getEditor(), [`${configDir}/${md5(uniqueName)}.json`])
@@ -1172,8 +1220,10 @@ const keywordDef = {
1172
1220
  comment: 'Workspace Management',
1173
1221
  exeFn: async (args) => {
1174
1222
  let newWorkspace = args.join(' ')
1223
+ let isSwitch = false
1175
1224
  if (newWorkspace) {
1176
1225
  if ($workspaceMap[newWorkspace]) {
1226
+ isSwitch = true;
1177
1227
  initWorkspace(newWorkspace)
1178
1228
  } else if (newWorkspace.startsWith('-')) {
1179
1229
  let name = newWorkspace.replace(/^-\s*/, '');
@@ -1194,7 +1244,9 @@ const keywordDef = {
1194
1244
  path
1195
1245
  }
1196
1246
  })
1197
- console.table(items)
1247
+ if (!isSwitch) {
1248
+ console.table(items)
1249
+ }
1198
1250
  },
1199
1251
  args: {
1200
1252
  workspacePath: 'New workspace path'
@@ -1277,43 +1329,61 @@ const keywordDef = {
1277
1329
  },
1278
1330
  short: 'p'
1279
1331
  },
1280
- npm: {
1281
- comment: 'Node npm',
1332
+ exe: {
1333
+ comment: 'System execute',
1282
1334
  exeFn: (args) => {
1283
- let packageFile = $workspaceMap[global.$defaultSpace] + '/package.json';
1284
- if(!fs.existsSync(packageFile)) {
1285
- let jsonObj = {
1286
- "dependencies": {}
1287
- }
1288
- fs.writeFileSync(packageFile, JSON.stringify(jsonObj, null, 2));
1335
+ let cmd = ''
1336
+ let _args = []
1337
+ if (args.length > 0) {
1338
+ cmd = args[0]
1339
+ }
1340
+ if (args.length > 1) {
1341
+ _args = args.slice(1)
1289
1342
  }
1290
- ei(`cd "${$workspaceMap[global.$defaultSpace]}";npm ${args.join(' ')}`, [], true)
1343
+ ei(`cd "${$workspaceMap[global.$defaultSpace]}";${cmd}`, _args, true)
1291
1344
  },
1292
- short: 'N'
1345
+ short: 'E'
1293
1346
  },
1294
1347
  log: {
1295
- comment: 'View log',
1348
+ comment: 'View log (type[[lt][le]], index)',
1296
1349
  exeFn: (args) => {
1297
1350
  let path = `${getLibDataDir()}/log/jsir`
1298
- let type = 'log';
1299
- if (args.length > 1) {
1300
- path = `${getLibDataDir()}/log/${md5(_cmdMap[trim(args[0])])}`
1301
- type = trim(args[1])
1302
- } else if (args.length > 0) {
1303
- if (_cmdMap[args[0]]) {
1304
- path = `${getLibDataDir()}/log/${md5(_cmdMap[trim(args[0])])}`
1351
+ let type = '';
1352
+ for (let arg of args) {
1353
+ if (_cmdMap[arg]) {
1354
+ path = `${getLibDataDir()}/log/${md5(_cmdMap[trim(arg)])}`
1305
1355
  } else {
1306
- type = args[0]
1356
+ type = arg;
1307
1357
  }
1308
1358
  }
1309
- path = path + '.' + type;
1359
+ let suffix = 'log'
1360
+ let cmdStr = 'less -R'
1361
+ if (type.indexOf("e") !== -1) {
1362
+ suffix = 'error'
1363
+ }
1364
+ if (type.indexOf("t") !== -1) {
1365
+ cmdStr = 'tail -n 50 -f'
1366
+ }
1367
+ path = path + '.' + suffix;
1310
1368
  if (!fs.existsSync(path)) {
1311
1369
  console.warn('log file not found')
1312
1370
  return;
1313
1371
  }
1314
- ei('less', [path])
1372
+ ei(cmdStr, [path], true)
1315
1373
  },
1316
- short: 'L'
1374
+ short: 'l'
1375
+ },
1376
+ debug: {
1377
+ comment: 'debug mode',
1378
+ exeFn: (args) => {
1379
+ if (global.$DEBUG) {
1380
+ delTips("DEBUG")
1381
+ } else {
1382
+ global.$DEBUG = true;
1383
+ setTips("DEBUG", "DEBUG", () => delete global.$DEBUG);
1384
+ }
1385
+ },
1386
+ short: 'D'
1317
1387
  }
1318
1388
  }
1319
1389
 
@@ -1562,7 +1632,7 @@ function _filterCmd(dirPath, arg) {
1562
1632
  for (let file of files) {
1563
1633
  file = trim(file)
1564
1634
  let uniqueName = toUniqueName(dirPath + '/' + file)
1565
- isArgsMatch(file, [arg], () => {
1635
+ isMatch(file, arg, () => {
1566
1636
  cmdMap[uniqueName] = null;
1567
1637
  }, true)
1568
1638
  }
@@ -1668,7 +1738,6 @@ async function runCmd(str = '', uniqueName = '', text = '') {
1668
1738
  }
1669
1739
 
1670
1740
  let scriptArgs = await getScriptArgs(argDef, enrichArgs(str.replace(/^\d+\s*/, '')));
1671
- process.argv = [process.argv[0], path, ...(scriptArgs.map(String))]
1672
1741
  return await evalText(text, uniqueName, scriptArgs)
1673
1742
  }
1674
1743
 
@@ -1677,7 +1746,6 @@ async function runScript(uniqueName, oriArgs) {
1677
1746
  let text = String(fs.readFileSync(path))
1678
1747
  let argDef = getArgDef(text)
1679
1748
  let scriptArgs = await getScriptArgs(argDef, oriArgs);
1680
- process.argv = [process.argv[0], path, ...(scriptArgs.map(String))]
1681
1749
  return await evalText(text, uniqueName, scriptArgs)
1682
1750
  }
1683
1751
 
@@ -1686,7 +1754,7 @@ async function getScriptArgs(argDef, oriArgs) {
1686
1754
  oriArgs = oriArgs.map(i => shortDefMap[i] ? shortDefMap[i]:i)
1687
1755
  let argNames = Object.keys(argDef)
1688
1756
  let exactArgs = {}
1689
- let scriptArgs = []
1757
+ let scriptArgs = {}
1690
1758
  for (let i = 0; i<oriArgs.length; i++) {
1691
1759
  let arg = oriArgs[i]
1692
1760
  let needTrans
@@ -1718,9 +1786,7 @@ async function getScriptArgs(argDef, oriArgs) {
1718
1786
  }
1719
1787
  pair[1] = needTrans ? await evalText( 'return ' + pair[1]):pair[1]
1720
1788
 
1721
- let curIdx = scriptArgs.length
1722
- scriptArgs[curIdx] = pair[1]
1723
-
1789
+ let curIdx = Object.keys(scriptArgs).length
1724
1790
  if (argNames[curIdx]) {
1725
1791
  scriptArgs[argNames[curIdx]] = pair[1]
1726
1792
  }
@@ -1747,7 +1813,7 @@ async function getScriptArgs(argDef, oriArgs) {
1747
1813
  }
1748
1814
  if (scriptArgKeys.indexOf(name) === -1 || (reg && !reg.test(scriptArgs[name]))) {
1749
1815
  argAbsent = true
1750
- console.warn(`require ${warnStr(name)}` + (defStr ? ` <${defStr}>`:''))
1816
+ console.warn(`require ${warnStr(name)}` + (defStr ? ` ${defStr}`:''))
1751
1817
  }
1752
1818
  }
1753
1819
  if (argAbsent) {
@@ -1842,9 +1908,8 @@ function getArgDef(text, uniqueName) {
1842
1908
  let argDef = {}
1843
1909
  try {
1844
1910
  argDef = (exeStr ? evalVal(exeStr) : parseArgDef(text)) || {}
1845
- let array = []
1846
1911
  for (let key of Object.keys(argDef)) {
1847
- if (/\s/.test(key) || array.hasOwnProperty(key)) {
1912
+ if (/\s/.test(key)) {
1848
1913
  throw `invalid argName ${warnStr(key)}`
1849
1914
  }
1850
1915
  }
@@ -1887,8 +1952,8 @@ function filterRequire(currSpace, cmdMatchStr) {
1887
1952
  let uName = toUniqueName(cmdMatchStr, currSpace)
1888
1953
  let pr = parseUniqueName(uName)
1889
1954
  let fullPath;
1890
- if (!/^[eif]\s+/.test(pr[1])) {
1891
- uName = pr[0] + "/i " + pr[1]
1955
+ if (!/^[ef]\s+/.test(pr[1])) {
1956
+ uName = pr[0] + "/i " + pr[1].replace(/^f\s+/, '')
1892
1957
  fullPath = getFullPath(uName)
1893
1958
  }
1894
1959
  if (fullPath && fs.existsSync(fullPath)) {
@@ -1980,6 +2045,24 @@ async function evalText($text = '', $cmdName = '', $args = []) {
1980
2045
  $homeDir, $lib, _cmdMap);
1981
2046
  }
1982
2047
 
2048
+ function clearFileLock() {
2049
+ let fileLockMap = getOr(global, `$fileLock`, {})
2050
+ for (let file of Object.keys(fileLockMap)) {
2051
+ fp.rmdir(file)
2052
+ delete fileLockMap[file]
2053
+ }
2054
+ }
2055
+
2056
+ function sigExit() {
2057
+ if (_noAppendNextLine) {
2058
+ delTips();
2059
+ clearFileLock();
2060
+ process.exit(0);
2061
+ } else {
2062
+ nextLine();
2063
+ }
2064
+ }
2065
+
1983
2066
  process.on('uncaughtException',function(err){
1984
2067
  console.error('uncaughtException', err)
1985
2068
  _noAppendNextLine || nextLine()
@@ -1992,14 +2075,8 @@ process.on('rejectionHandled',function(err){
1992
2075
  console.error('rejectionHandled', err)
1993
2076
  _noAppendNextLine || nextLine()
1994
2077
  })
1995
- process.on('SIGINT', function () {
1996
- if (_noAppendNextLine) {
1997
- delTips();
1998
- process.exit(0);
1999
- } else {
2000
- nextLine();
2001
- }
2002
- });
2078
+ process.on('SIGINT', sigExit);
2079
+ process.on('SIGTERM', sigExit);
2003
2080
  process.on('beforeExit', function () {
2004
2081
  if (_noAppendNextLine) {
2005
2082
  delTips();
package/deps/evalCode.js CHANGED
@@ -21,7 +21,7 @@ module.exports = async ($text = '', $cmdName = '', $args = [],
21
21
  $enter, $filterCmd,
22
22
  $currentSpace, $homeDir, $lib, $cmdMap
23
23
  }
24
- const console = $lib.createConsole($cmdName);
24
+ let console = $lib.createConsole($cmdName);
25
25
  return await eval(`(async ()=>{${$text};
26
26
  })()`)
27
27
  }
package/deps/util.js CHANGED
@@ -29,9 +29,9 @@ class SyncQueue {
29
29
  this.isProcessing = false;
30
30
  }
31
31
  // 添加任务到队列
32
- enqueue(task) {
32
+ async enqueue(task) {
33
33
  this.queue.push(task);
34
- this.processQueue();
34
+ await this.processQueue();
35
35
  }
36
36
  // 处理队列
37
37
  async processQueue() {
@@ -55,10 +55,10 @@ function syncQueue(task, key) {
55
55
  同步队列分发器
56
56
  task: function
57
57
  key: 根据key值区分不同队列, 可选
58
- return void
58
+ return Promise
59
59
  `
60
60
  let queue = getOrFn(syncQueues, trim(key), () => new SyncQueue())
61
- queue.enqueue(task)
61
+ return queue.enqueue(task)
62
62
  }
63
63
 
64
64
  const $log = createLimitLogger(`${setting.name}.log`, {
@@ -85,9 +85,12 @@ const draftLog = str => {
85
85
  _globalDraft(`---------${now.getTime()} ${timeStr(null, now)}\n${trimEmptyLine(str)}`)
86
86
  }
87
87
  }
88
- const $fnCache = {}
89
88
 
90
89
  // fix console begin
90
+ function debugStr(str) {
91
+ return `\x1B[2m${str}\x1B[0m`
92
+ }
93
+
91
94
  function infoStr(str) {
92
95
  return `\x1B[32m${str}\x1B[39m`
93
96
  }
@@ -106,10 +109,10 @@ function errorStr(str) {
106
109
 
107
110
  function tableStr(...args) {
108
111
  return args.map(i => {
109
- if (Array.isArray(i)) {
112
+ if (typeof i === 'object') {
110
113
  return trim(table.getTable(i))
111
114
  } else {
112
- return i
115
+ return i;
113
116
  }
114
117
  }).join("\n")
115
118
  }
@@ -143,48 +146,35 @@ const _console =Object.assign({}, global.console);
143
146
  const _consoleFns= {
144
147
  log: {
145
148
  fn: _console.log,
146
- args: args => args,
147
- $args: args => args
149
+ args: args => args
148
150
  },
149
151
  table: {
150
152
  fn: _console.log,
151
- args: args => [tableStr(...args)],
152
- $args: args => [tableStr(...args)]
153
+ args: args => [tableStr(...args)]
153
154
  },
154
155
  nable: {
155
156
  fn: _console.log,
156
- args: args => [nableStr(...args)],
157
- $args: args => [nableStr(...args)]
157
+ args: args => [nableStr(...args)]
158
158
  },
159
159
  info: {
160
160
  fn: _console.info,
161
- args: args => [infoStr('[info]'), ...dealLevelArgs(infoStr, args)],
162
- $args: args => ['[info]', ...args]
161
+ args: args => [infoStr('[info]'), ...dealLevelArgs(infoStr, args)]
163
162
  },
164
163
  msg: {
165
164
  fn: _console.log,
166
- args: args => [msgStr('[msg]'), ...dealLevelArgs(msgStr, args)],
167
- $args: args => ['[msg]', ...args]
165
+ args: args => [msgStr('[msg]'), ...dealLevelArgs(msgStr, args)]
168
166
  },
169
167
  warn: {
170
168
  fn: _console.warn,
171
169
  args: args => [warnStr('[warn]'), ...dealLevelArgs(warnStr, args)],
172
- $args: args => ['[warn]', ...args]
173
170
  },
174
171
  error: {
175
172
  fn: _console.error,
176
- args: args => [errorStr('[error]'), ...dealLevelArgs(errorStr, args)],
177
- $args: args => ['[error]', ...args]
178
- },
179
- dir: {
180
- fn: _console.dir,
181
- args: args => args,
182
- $args: args => args
173
+ args: args => [errorStr('[error]'), ...dealLevelArgs(errorStr, args)]
183
174
  },
184
175
  debug: {
185
176
  fn: _console.debug,
186
- args: args => args,
187
- $args: args => args
177
+ args: args => [debugStr('[debug]'), ...dealLevelArgs(debugStr, args)]
188
178
  }
189
179
  }
190
180
 
@@ -193,7 +183,7 @@ function createConfig(uniqueName) {
193
183
  get: getConfig,
194
184
  local: getConfig
195
185
  }
196
- if (uniqueName && uniqueName.split("/")[1].startsWith('e ')) {
186
+ if (uniqueName) {
197
187
  result.local = (key, defaultVal) => {
198
188
  return _getConfig(key, defaultVal, uniqueName);
199
189
  }
@@ -206,8 +196,7 @@ function createConsole(uniqueName) {
206
196
  result.$log = $log;
207
197
  result.$error = $error;
208
198
  result.$draft = draftLog;
209
- let logAble = uniqueName &&uniqueName.split("/")[1].startsWith('e ');
210
- if (logAble) {
199
+ if (uniqueName) {
211
200
  result.$log = createLimitLogger(md5(uniqueName) + '.log', {
212
201
  logInfo: false
213
202
  });
@@ -217,7 +206,7 @@ function createConsole(uniqueName) {
217
206
  });
218
207
  }
219
208
  let quite = false
220
- if (logAble) {
209
+ if (uniqueName) {
221
210
  global.$newInput = false;
222
211
  }
223
212
  for (let key of Object.keys(_consoleFns)) {
@@ -225,8 +214,14 @@ function createConsole(uniqueName) {
225
214
  if (global.$newInput) {
226
215
  quite = true;
227
216
  }
228
- if (logAble && quite) {
229
- let _args = _consoleFns[key].$args(args);
217
+ if ('debug' === key && !global.$DEBUG) {
218
+ return;
219
+ }
220
+ if (uniqueName && quite) {
221
+ if ((key === 'table' || key === 'nable') && typeof args[0] === "object") {
222
+ args = ['', ...args]
223
+ }
224
+ let _args = _consoleFns[key].args(args);
230
225
  if ("error" === key) {
231
226
  result.$log(..._args)
232
227
  result.$error(..._args)
@@ -304,19 +299,37 @@ function isJsirFileName(name) {
304
299
  return /^[^./]*[^./\s]\.[^./\s]+$/.test(name)
305
300
  }
306
301
 
307
- function isArgsMatch(text, args, callback, useMd5) {
302
+ function isMatch(text,
303
+ matchStr, // reg,reg;reg
304
+ callback, // invoke when matched, no args
305
+ useMd5 // '0x' + md5(text).substring(0, 8)) === matchStr
306
+ ) {
308
307
  let match = false
309
- for (let arg of args) {
308
+ let orStrs = matchStr.split(';').map(trim).filter(i => i);
309
+ for (let arg of orStrs) {
310
310
  let r = true
311
311
  for (let str of arg.split(',').map(trim).filter(i => i)) {
312
+ let not = false;
313
+ if (str.startsWith("!")) {
314
+ not = true;
315
+ str = str.substring(1);
316
+ }
312
317
  let reg = new RegExp(str.split(/\s+/).join('\\s+'), 'i')
313
318
  if (useMd5 && /^0x[a-z\d]{8}$/.test(str)) {
314
- if (('0x' + md5(text).substr(0, 8)) !== str) {
319
+ let flag = ('0x' + md5(text).substring(0, 8)) !== str;
320
+ if (not) {
321
+ flag = !flag;
322
+ }
323
+ if (flag) {
315
324
  r = false
316
325
  break
317
326
  }
318
327
  } else {
319
- if (!reg.test(text)) {
328
+ let flag = !reg.test(text);
329
+ if (not) {
330
+ flag = !flag;
331
+ }
332
+ if (flag) {
320
333
  r = false
321
334
  break
322
335
  }
@@ -327,6 +340,9 @@ function isArgsMatch(text, args, callback, useMd5) {
327
340
  break
328
341
  }
329
342
  }
343
+ if (orStrs.length === 0) {
344
+ match = true;
345
+ }
330
346
  if (match && callback) {
331
347
  callback()
332
348
  }
@@ -341,9 +357,10 @@ function parseDraftLog(draftPath) {
341
357
  let temp = [];
342
358
  let startIndex = 0;
343
359
  let head;
360
+ let splitReg = /^---------\d+/;
344
361
 
345
362
  allLines.forEach((line, i) => {
346
- if (line.startsWith("---------")) {
363
+ if (splitReg.test(line)) {
347
364
  if (temp.length > 0) {
348
365
  let fullText = temp.join('\n');
349
366
  lines.push(fullText);
@@ -353,7 +370,7 @@ function parseDraftLog(draftPath) {
353
370
  temp = [];
354
371
  head = line;
355
372
  }
356
- temp.push(line.startsWith("---------") ? warnStr(line) : line);
373
+ temp.push(splitReg.test(line) ? warnStr(line) : line);
357
374
  });
358
375
 
359
376
  if (temp.length > 0) {
@@ -401,7 +418,7 @@ function draftQuery(fLine) {
401
418
  results = lines.slice(- parseInt(filterKeywords));
402
419
  } else {
403
420
  lines.forEach(line => {
404
- if (isArgsMatch(line, [filterKeywords])) {
421
+ if (isMatch(line, filterKeywords)) {
405
422
  results.push(line);
406
423
  }
407
424
  });
@@ -475,12 +492,13 @@ function getEditor() {
475
492
  }
476
493
 
477
494
  function timeStr(fmt, date) {
478
- return dayJs(date || new Date()).format(fmt || 'YYYY/MM/DD HH:mm:ss')
495
+ return dayJs(date || new Date()).format(fmt || 'YYYY-MM-DD HH:mm:ss')
479
496
  }
480
497
 
481
498
  function vl(obj) {
482
- if (typeof obj === 'number') {
483
- return !Number.isNaN(obj)
499
+ let type= typeof obj;
500
+ if (type === 'number') {
501
+ return !Number.isNaN(obj) && Number.isFinite(obj);
484
502
  }
485
503
  if (typeof obj === 'string') {
486
504
  obj = obj.trim()
@@ -496,31 +514,29 @@ function getVl(...obj) {
496
514
  }
497
515
  }
498
516
 
499
- const cacheFnRespMap = {};
500
- async function cacheFn(key, fn, validMs, awaitRefresh = true) {
517
+ const $fnCache = {}
518
+ async function cacheFn(key, fn, validMs = 0, awaitRefresh = true) {
501
519
  getOr($fnCache, key, {
502
520
  validMsTime: 0
503
521
  });
504
522
  if (Date.now() <= $fnCache[key].validMsTime) {
505
523
  // do nothing
506
524
  } else {
507
- $fnCache[key].validMsTime = Date.now() * 3;
508
- cacheFnRespMap[key] = (async () => {
525
+ $fnCache[key].validMsTime = Infinity;
526
+ $fnCache[key].promise = (async () => {
509
527
  let val;
510
528
  try {
511
529
  val = await fn()
512
530
  } finally {
513
531
  $fnCache[key].validMsTime = 0
514
532
  }
515
- $fnCache[key] = {
516
- val,
517
- valInit: true,
518
- validMsTime: Date.now() + (validMs || Date.now())
519
- }
533
+ $fnCache[key].val = val;
534
+ $fnCache[key].valInit = true;
535
+ $fnCache[key].validMsTime = Date.now() + validMs;
520
536
  })();
521
537
  }
522
538
  if (awaitRefresh || !$fnCache[key].valInit) {
523
- await cacheFnRespMap[key];
539
+ await $fnCache[key].promise;
524
540
  }
525
541
  return $fnCache[key].val
526
542
  }
@@ -582,7 +598,7 @@ function getLogDir() {
582
598
  }
583
599
 
584
600
  function createLimitLogger(fileName, {
585
- maxChars,
601
+ maxChars = 49 * 1024 * 1024,
586
602
  logInfo = true,
587
603
  time = true,
588
604
  error = false
@@ -609,7 +625,7 @@ function createLimitLogger(fileName, {
609
625
  global.$newError = true;
610
626
  }
611
627
  if (time) {
612
- text = `[${timeStr()}] ${text}`
628
+ text = `${timeStr('YYYY-MM-DD HH:mm:ss.SSS')} ${text}`
613
629
  }
614
630
  syncQueue(() => fp.appendFile(logPath, text + '\n'), logPath)
615
631
  let _minNum = (Date.now()/(1000 * 60 * 10)).toFixed(0)
@@ -736,8 +752,8 @@ function requireG(moduleName){
736
752
  let moduleDir = $workspaceMap[global.$defaultSpace] + '/node_modules'
737
753
  if (module.paths.indexOf(moduleDir) === -1) {
738
754
  module.paths.splice(0, module.paths.length)
739
- module.paths.push(...initModulePaths)
740
755
  module.paths.push(moduleDir)
756
+ module.paths.push(...initModulePaths)
741
757
  }
742
758
  try {
743
759
  let result = require(moduleName);
@@ -757,8 +773,8 @@ async function importG(moduleName) {
757
773
  let moduleDir = $workspaceMap[global.$defaultSpace] + '/node_modules'
758
774
  if (module.paths.indexOf(moduleDir) === -1) {
759
775
  module.paths.splice(0, module.paths.length)
760
- module.paths.push(...initModulePaths)
761
776
  module.paths.push(moduleDir)
777
+ module.paths.push(...initModulePaths)
762
778
  }
763
779
  try {
764
780
  let result = await import(moduleName);
@@ -771,7 +787,7 @@ async function importG(moduleName) {
771
787
  console.log(warnStr(`.npm install ${moduleName}`))
772
788
  throw `${moduleName} not found, use .npm install to add it`;
773
789
  }
774
- return await import(path);
790
+ return await import(require.resolve(path));
775
791
  }
776
792
 
777
793
  function validStr(str, name) {
@@ -966,17 +982,22 @@ async function _fileLock(key, fn) {
966
982
  } catch (e) {
967
983
  return false;
968
984
  }
985
+ let fileLockMap = getOr(global, `$fileLock`, {})
986
+ fileLockMap[file] = true;
969
987
  try {
970
988
  await fn();
971
- try {await fp.rmdir(file)} catch (_){}
972
989
  return true;
973
990
  } catch (e) {
974
- try {await fp.rmdir(file)} catch (_){}
975
991
  throw e;
992
+ } finally {
993
+ try {
994
+ await fp.rmdir(file)
995
+ delete fileLockMap[file]
996
+ } catch (_){}
976
997
  }
977
998
  }
978
999
 
979
- async function fileLock(key, fn, wait = false) {
1000
+ async function fileLock(key, fn, wait = true) {
980
1001
  `
981
1002
  文件锁, 默认一直等待,直到加锁成功执行fn
982
1003
  wait = false, 加锁失败则不执行fn
@@ -987,7 +1008,7 @@ async function fileLock(key, fn, wait = false) {
987
1008
  if (await _fileLock(key, fn)) {
988
1009
  break;
989
1010
  }
990
- await sleep(9);
1011
+ await sleep(49);
991
1012
  }
992
1013
  } else {
993
1014
  await _fileLock(key, fn);
@@ -1098,7 +1119,7 @@ function fileCleaner(path, maxChars) {
1098
1119
  }
1099
1120
  }
1100
1121
 
1101
- function cleanFile(path, maxChars) {
1122
+ function cleanFile(path, maxChars = 9 * 1024 * 1024) {
1102
1123
  `
1103
1124
  进入文件操作队列,不会同步去做
1104
1125
  `
@@ -1123,7 +1144,7 @@ function cleanFile(path, maxChars) {
1123
1144
  }
1124
1145
  await fileLock(path, async () => {
1125
1146
  let content = String(await fp.readFile(path))
1126
- let newContext = content.substr(- (maxChars * 0.9))
1147
+ let newContext = content.slice(-Math.floor(maxChars * 0.7));
1127
1148
  await fp.writeFile(path, newContext)
1128
1149
  }, false)
1129
1150
  }, path)
@@ -1307,11 +1328,7 @@ async function setCbText(str) {
1307
1328
  }
1308
1329
 
1309
1330
  async function sleep(milliseconds) {
1310
- return new Promise(resolve => {
1311
- setTimeout(() => {
1312
- resolve()
1313
- }, milliseconds)
1314
- })
1331
+ return new Promise(resolve => setTimeout(resolve, milliseconds));
1315
1332
  }
1316
1333
 
1317
1334
  function splitArray(items, size) {
@@ -1367,14 +1384,14 @@ function range(start, end, step) {
1367
1384
  }
1368
1385
 
1369
1386
  function getOr(obj, key, defaultVal) {
1370
- if (!obj[key]) {
1387
+ if (!vl(obj[key])) {
1371
1388
  obj[key] = defaultVal
1372
1389
  }
1373
1390
  return obj[key]
1374
1391
  }
1375
1392
 
1376
1393
  function getOrFn(obj, key, defaultValFn) {
1377
- if (!obj[key]) {
1394
+ if (!vl(obj[key])) {
1378
1395
  obj[key] = defaultValFn()
1379
1396
  }
1380
1397
  return obj[key]
@@ -1520,7 +1537,6 @@ function getInfo(obj, name, type) {
1520
1537
  }
1521
1538
  info.type = type || getType(obj)
1522
1539
  if (!vl(obj)) {
1523
- info.type = type
1524
1540
  info.value = String(obj);
1525
1541
  return info;
1526
1542
  }
@@ -1564,8 +1580,8 @@ function getInfo(obj, name, type) {
1564
1580
  function getFnArgsStr(str){
1565
1581
  let fnStr = trim(str.split(/=\s*>|(?<=\))\s*{/)[0])
1566
1582
  let argsStr
1567
- if (/[()]/.test(fnStr)) {
1568
- argsStr = fnStr.split(/[()]/)[1]
1583
+ if (fnStr.endsWith(')')) {
1584
+ argsStr = fnStr.substring(fnStr.indexOf("(") + 1, fnStr.length - 1)
1569
1585
  } else {
1570
1586
  argsStr = fnStr
1571
1587
  }
@@ -1793,7 +1809,7 @@ module.exports = {
1793
1809
  errorTag,
1794
1810
  iobjDataFile,
1795
1811
  iarrayDataFile,
1796
- isArgsMatch,
1812
+ isMatch,
1797
1813
  draftQuery,
1798
1814
  getTextComments,
1799
1815
  trimText,
@@ -1814,5 +1830,6 @@ module.exports = {
1814
1830
  toUniqueName,
1815
1831
  isJsirFileName,
1816
1832
  toJsirFileName,
1817
- fileJson
1833
+ fileJson,
1834
+ debugStr
1818
1835
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsir",
3
- "version": "2.2.2",
3
+ "version": "2.2.4",
4
4
  "description": "JavaScript Script Management Tool",
5
5
  "main": "index.js",
6
6
  "scripts": {