jsir 2.2.1 → 2.2.2

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
@@ -6,8 +6,12 @@ const {
6
6
  arrayDataFile, infoStr, warnStr, errorStack,
7
7
  getInfo, ei, pad, msgStr, getType,
8
8
  isArgsMatch, draftQuery, setConfig,
9
- $log, $draft, getTextComments, getOr, importG, requireG,
10
- clearConsole, trimText
9
+ getTextComments, importG, requireG,
10
+ clearConsole, trimText, getFnArgsStr,
11
+ createConsole, setTips, delTips,
12
+ getEditor, errorStr, getConfigDir,
13
+ getFullPath, parseUniqueName, toUniqueName, isJsirFileName, toJsirFileName,
14
+ fileJson, fileLock
11
15
  } = $lib;
12
16
  const _args = process.argv.slice(2).map(trim);
13
17
  const evalCode = require('../deps/evalCode')
@@ -15,23 +19,19 @@ const {evalVal} = require('../deps/cleanEval')
15
19
  const _chokidar = require('chokidar');
16
20
  const setting = require('../deps/setting')
17
21
  const fs = require('fs')
22
+ const fp = require('fs').promises
18
23
  const readline = require("readline");
19
24
  const packageJson = require("../package.json");
20
25
  const example = require("../deps/example");
21
26
  const _workspaceConfigFile = 'workspace.json';
22
27
  const _libDataDir = getLibDataDir()
23
- const _tipsOnRm = {}
24
28
  const _fileWatcherMap = {}
25
29
  const _types = {
26
30
  'e': "exe",
27
31
  'i': "init",
28
32
  'f': "file"
29
33
  }
30
- const $config = {
31
- get: getConfig,
32
- set: setConfig
33
- }
34
- const console = Object.assign({}, global.console);
34
+ const console = createConsole();
35
35
 
36
36
  let lastFilterArg = '';
37
37
  let _cmdMapFile = setting.name + 'CmdMap.json'
@@ -123,13 +123,12 @@ const $data = {
123
123
  keys: () => Object.keys(_data),
124
124
  have: (key) => vl(_data[key])
125
125
  }
126
+ const $file = {
127
+ json: fileJson,
128
+ lock: fileLock
129
+ }
126
130
  const $homeDir = getLibDataDir()
127
131
 
128
- global.$tips = {}
129
- global.$newInput = false
130
- global.$workspaceMap = {}
131
- global.$defaultSpace = 'local'
132
-
133
132
  function getFileOpenExe(fileName) {
134
133
  fileName = trim(fileName);
135
134
  let strs = fileName.split('.')
@@ -321,10 +320,17 @@ function initRl(callback, promptStr, hidden) {
321
320
  }
322
321
  origin_writeToOutput = _rl._writeToOutput
323
322
  if (promptStr !== '') {
324
- promptStr = (promptStr
325
- || ((callback && callback !== wrapperInput) ? "-> ":"")
326
- || defaultPromptStr())
327
- promptStr = infoStr(promptStr)
323
+ promptStr = promptStr || ((callback && callback !== wrapperInput) ? "-> ":"")
324
+ if (promptStr) {
325
+ promptStr = infoStr(promptStr);
326
+ } else {
327
+ if (global.$newError) {
328
+ global.$newError = false;
329
+ promptStr = errorStr(defaultPromptStr())
330
+ } else {
331
+ promptStr = infoStr(defaultPromptStr())
332
+ }
333
+ }
328
334
  }
329
335
  if (hidden) {
330
336
  _rl._writeToOutput = function _writeToOutput(stringToWrite){
@@ -346,7 +352,13 @@ function initRl(callback, promptStr, hidden) {
346
352
  function getTipStr(showKey = false) {
347
353
  let items = [];
348
354
  for (let key of Object.keys(global.$tips)) {
349
- let val = global.$tips[key].map(i => trim(i).replace(/,/g, '-')).join("|");
355
+ let val = global.$tips[key].map(i => {
356
+ let item = trim(i)
357
+ if (item.indexOf(',') !== -1) {
358
+ item = `[${item}]`;
359
+ }
360
+ return item;
361
+ }).join("|");
350
362
  key = trim(key)
351
363
 
352
364
  let item
@@ -470,6 +482,15 @@ function rename(dir, oldName, newName) {
470
482
  } else {
471
483
  fs.renameSync(old, _new)
472
484
  console.info(`${_new} renamed`)
485
+
486
+ let configDir = getConfigDir();
487
+ let uniqueOld = toUniqueName(old);
488
+ let uniqueNew = toUniqueName(_new);
489
+ let configFileOld = configDir + '/' + md5(uniqueOld) + '.json';
490
+ let configFileNew = configDir + '/' + md5(uniqueNew) + '.json';
491
+ if (fs.existsSync(configFileOld) && !fs.existsSync(configFileNew)) {
492
+ fs.renameSync(configFileOld, configFileNew)
493
+ }
473
494
  }
474
495
  resetCmdMap({
475
496
  1: toUniqueName(_new)
@@ -554,10 +575,6 @@ async function wrapperInput(str) {
554
575
  }
555
576
  }
556
577
 
557
- function getEditor() {
558
- return getConfig("defaultEditor", "vi")
559
- }
560
-
561
578
  async function _wrapperInput(str) {
562
579
  _haveWrapperInput = true;
563
580
  global.$newInput = true;
@@ -576,8 +593,7 @@ async function _wrapperInput(str) {
576
593
  if (fLine) {
577
594
  console.log(draftQuery(fLine).join("\n"))
578
595
  } else {
579
- let text = str.substr(1) + "\n" + await nextText(line => line, fstr)
580
- $draft(text)
596
+ console.$draft(await nextText(line => line, fstr))
581
597
  }
582
598
  }
583
599
  } else if (/^[$#*]/.test(str)) {
@@ -641,6 +657,7 @@ async function dealStar(text) {
641
657
  await dealStartGlobalMode(rows, items, text);
642
658
  }
643
659
  }
660
+ rows = rows.filter(i => !i.name.startsWith('_'));
644
661
  if (rows.length === 0) {
645
662
  console.warn("no items")
646
663
  } else {
@@ -664,6 +681,7 @@ function dealStarGlobal(items, text) {
664
681
 
665
682
  function dealStarCmd(rows, cmd, filterStr) {
666
683
  let content = String(fs.readFileSync(getFullPath(cmd)));
684
+ let lines = content.split('\n');
667
685
  let capturingFunction = false;
668
686
  let inMultiLineComment = false;
669
687
  let potentialComments = [];
@@ -682,7 +700,7 @@ function dealStarCmd(rows, cmd, filterStr) {
682
700
  comments = [];
683
701
  }
684
702
 
685
- for (let line of content.split('\n')) {
703
+ for (let [index, line] of lines.entries()) {
686
704
  // Handle multi-line comment start or continue
687
705
  if (line.trim().startsWith('/*') || inMultiLineComment) {
688
706
  inMultiLineComment = true;
@@ -701,12 +719,16 @@ function dealStarCmd(rows, cmd, filterStr) {
701
719
  }
702
720
 
703
721
  // Check for function start
704
- if ((line.startsWith('function') || line.startsWith('async function')) && isArgsMatch(line, [filterStr])) {
705
- fnName = reget(line, /function\s+(\w+)\s*\(/);
706
- fnType = line.startsWith('async') ? 'AsyncFunction' : 'Function';
707
- capturingFunction = true;
708
- comments = [...potentialComments]; // Confirm the comments are related to the function
709
- potentialComments = []; // Clear the potential comments as they are now confirmed
722
+ if ((line.startsWith('function') || line.startsWith('async function'))) {
723
+ let _fnName = reget(line, /function\s+(\w+)\s*\(/);
724
+ let matchKey = _fnName + "(" + getFnArgsStr(lines.slice(index, index + 9).join("\n")) + ")"
725
+ if (isArgsMatch(matchKey, [filterStr])) {
726
+ fnName = _fnName;
727
+ fnType = line.startsWith('async') ? 'AsyncFunction' : 'Function';
728
+ capturingFunction = true;
729
+ comments = [...potentialComments]; // Confirm the comments are related to the function
730
+ potentialComments = []; // Clear the potential comments as they are now confirmed
731
+ }
710
732
  }
711
733
 
712
734
  // Capture function lines
@@ -739,7 +761,13 @@ async function dealStarCase(result, matchStrs, cmd) {
739
761
  rows.push(getInfo(result))
740
762
  } else {
741
763
  for (let key of Object.keys(result)) {
742
- if (matchStrs.length === 0 || isArgsMatch(key, [matchStrs.join(' ')])){
764
+ let obj = result[key];
765
+ let type = getType(obj);
766
+ let matchKey = key;
767
+ if (type === 'Function' || type === 'AsyncFunction') {
768
+ matchKey = key + "(" + getFnArgsStr(String(obj)) + ")";
769
+ }
770
+ if (matchStrs.length === 0 || isArgsMatch(matchKey, [matchStrs.join(' ')])){
743
771
  rows.push(getInfo(result[key], key))
744
772
  }
745
773
  }
@@ -994,18 +1022,39 @@ const keywordDef = {
994
1022
  setting: {
995
1023
  comment: 'Global settings',
996
1024
  exeFn: async (args) => {
997
- ei(getEditor(), [`${getLibDataDir()}/config.json`])
1025
+ let uniqueName = _cmdMap[args[0]];
1026
+ if (uniqueName) {
1027
+ let isExe = uniqueName &&uniqueName.split("/")[1].startsWith('e ');
1028
+ if (!isExe) {
1029
+ console.warn("not exe file")
1030
+ return;
1031
+ }
1032
+ let configDir = `${getLibDataDir()}/config`;
1033
+ mkdir(configDir)
1034
+ ei(getEditor(), [`${configDir}/${md5(uniqueName)}.json`])
1035
+ } else {
1036
+ ei(getEditor(), [`${getLibDataDir()}/config.json`])
1037
+ }
998
1038
  },
999
1039
  short: 's'
1000
1040
  },
1001
1041
  open: {
1002
1042
  comment: 'open file',
1003
1043
  exeFn: async (args) => {
1004
- let uniqueName = _cmdMap[args[0]]
1044
+ let uniqueName = _cmdMap[args[0]] || args.join(" ");
1005
1045
  if (!uniqueName) {
1006
1046
  console.warn("no items")
1007
1047
  } else {
1008
1048
  let path = getFullPath(uniqueName)
1049
+ if (!fs.existsSync(path)) {
1050
+ let cmds = filterCmd(uniqueName);
1051
+ if (cmds.length === 1) {
1052
+ path = getFullPath(cmds[0])
1053
+ } else {
1054
+ console.warn("no items")
1055
+ return;
1056
+ }
1057
+ }
1009
1058
  await e(`"${getFileOpenExe(parseUniqueName(uniqueName)[1])}" "${path}"`)
1010
1059
  }
1011
1060
  },
@@ -1241,6 +1290,30 @@ const keywordDef = {
1241
1290
  ei(`cd "${$workspaceMap[global.$defaultSpace]}";npm ${args.join(' ')}`, [], true)
1242
1291
  },
1243
1292
  short: 'N'
1293
+ },
1294
+ log: {
1295
+ comment: 'View log',
1296
+ exeFn: (args) => {
1297
+ 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])])}`
1305
+ } else {
1306
+ type = args[0]
1307
+ }
1308
+ }
1309
+ path = path + '.' + type;
1310
+ if (!fs.existsSync(path)) {
1311
+ console.warn('log file not found')
1312
+ return;
1313
+ }
1314
+ ei('less', [path])
1315
+ },
1316
+ short: 'L'
1244
1317
  }
1245
1318
  }
1246
1319
 
@@ -1267,11 +1340,11 @@ function preLoad(text, fnNameMatch, fn, packages = []) {
1267
1340
  let result = fn(packageName)
1268
1341
  if (getType(result) === 'Promise') {
1269
1342
  result.catch(e => {
1270
- $log(e)
1343
+ console.$error(e)
1271
1344
  })
1272
1345
  }
1273
1346
  } catch (e) {
1274
- $log(e)
1347
+ console.$error(e)
1275
1348
  }
1276
1349
  }
1277
1350
  });
@@ -1420,57 +1493,6 @@ function getComments(i, cmdName, text, cols = [], col) {
1420
1493
  }
1421
1494
  }
1422
1495
 
1423
- function getFullPath(name) {
1424
- name = trim(name)
1425
- if (!name) {
1426
- return name;
1427
- }
1428
- let uniqueName = toUniqueName(name)
1429
- let pair = parseUniqueName(uniqueName)
1430
- let space = $workspaceMap[pair[0]]
1431
- if (!space) {
1432
- return ''
1433
- }
1434
- return `${space}/${pair[1]}`
1435
- }
1436
-
1437
- function toUniqueName(name, space) {
1438
- name = trim(name)
1439
- if (!name) {
1440
- throw `invalid name '${name}'`
1441
- }
1442
- let uniqueName
1443
- if (name.startsWith('/')) {
1444
- let items = name.split('/').map(trim).filter(i => i).reverse()
1445
- uniqueName = items[1] + '/' + items[0]
1446
- } else if (name.indexOf('/') !== -1) {
1447
- uniqueName = name;
1448
- } else {
1449
- uniqueName = (space || $defaultSpace) + '/' + name;
1450
- }
1451
- let pair = parseUniqueName(uniqueName);
1452
- return (pair[0] || space || $defaultSpace) + '/' + toJsirFileName(pair[1])
1453
- }
1454
-
1455
- function toJsirFileName(name) {
1456
- name = trim(name)
1457
- if (!name) {
1458
- throw `invalid name '${name}'`
1459
- }
1460
- if (isJsirFileName(name)) {
1461
- return name;
1462
- }
1463
- name = name + '.js'
1464
- if (!isJsirFileName(name)) {
1465
- throw `invalid name '${name}'`
1466
- }
1467
- return name
1468
- }
1469
-
1470
- function isJsirFileName(name) {
1471
- return /^[^./]*[^./\s]\.[^./\s]+$/.test(name)
1472
- }
1473
-
1474
1496
  function trimJsirFileName(name) {
1475
1497
  name = trim(name)
1476
1498
  if (isJsirFileName(name)) {
@@ -1551,12 +1573,6 @@ function getSpaceFromDir(dirPath) {
1551
1573
  return trim(trim(dirPath).split('/').map(trim).filter(i => i).reverse()[0])
1552
1574
  }
1553
1575
 
1554
- function parseUniqueName(uniqueName) {
1555
- let pair = uniqueName.split('/').map(trim).filter(i => i)
1556
- let len = pair.length;
1557
- return [pair[len - 2], pair[len - 1]]
1558
- }
1559
-
1560
1576
  function getArgComments(argDef, showShort = false) {
1561
1577
  let comments = []
1562
1578
  let keys = Object.keys(argDef)
@@ -1569,13 +1585,13 @@ function getArgComments(argDef, showShort = false) {
1569
1585
  }
1570
1586
  if (keys.length > 0) {
1571
1587
  for (let k of keys) {
1572
- let item = warnStr(k) + (shortMap[k] ? ` ${warnStr(shortMap[k])}`:'') + (argDef[k] ? ` <${argDef[k]}>`:'')
1588
+ let item = warnStr(k) + (shortMap[k] ? ` ${warnStr(shortMap[k])}`:'') + (argDef[k] ? ` ${argDef[k]}`:'')
1573
1589
  comments.push(item)
1574
1590
  }
1575
- comments[0] = '$args: ' + comments[0]
1591
+ comments[0] = comments[0]
1576
1592
  if (comments.length > 1) {
1577
1593
  for(let i = 1; i< comments.length; i++) {
1578
- comments[i] = ' ' + comments[i]
1594
+ comments[i] = comments[i]
1579
1595
  }
1580
1596
  }
1581
1597
  }
@@ -1680,7 +1696,8 @@ async function getScriptArgs(argDef, oriArgs) {
1680
1696
  }
1681
1697
  if (arg.startsWith(":") || arg.startsWith("_") && !arg.endsWith(' ')) {
1682
1698
  arg = arg.replace(/^:/, '')
1683
- if (oriArgs[i+1] && (oriArgs[i+1].endsWith(' ') || !(oriArgs[i+1].startsWith(":") || oriArgs[i+1].startsWith("_") || oriArgs[i+1].startsWith("-")))) {
1699
+ if (oriArgs[i+1] &&
1700
+ (oriArgs[i+1].endsWith(' ') || !(oriArgs[i+1].startsWith(":") || oriArgs[i+1].startsWith("_") || oriArgs[i+1].startsWith("-")))) {
1684
1701
  pair = [arg, oriArgs[i+1]]
1685
1702
  i++
1686
1703
  } else {
@@ -1776,19 +1793,41 @@ function parseArgDef(inputString) {
1776
1793
  if (!preStr) {
1777
1794
  return result;
1778
1795
  }
1779
- let ss = preStr.split(/[,\n]|(?<!\/)\/(?=\/)/g).map(trim).filter(i => i);
1780
- for (let i = 0; i < ss.length; i++) {
1781
- let s1 = trim(ss[i]);
1796
+ let ss = preStr.split(/\n|(?<!\/)\/(?=\/)/g).map(trim).filter(i => i);
1797
+ let items = []
1798
+ for (let s of ss) {
1799
+ if (s.startsWith("/")) {
1800
+ items.push(s);
1801
+ } else {
1802
+ items.push(...s.split(/,/))
1803
+ }
1804
+ }
1805
+ items = items.map(trim).filter(i => i);
1806
+ for (let i = 0; i < items.length; i++) {
1807
+ let s1 = trim(items[i]);
1782
1808
  if (s1.startsWith("/")) {
1783
1809
  continue;
1784
1810
  }
1785
- if (ss[i+1] && ss[i+1].startsWith("/")) {
1786
- result[s1] = trim(ss[i+1].replace(/^\//, ""));
1811
+ if (items[i+1] && items[i+1].startsWith("/")) {
1812
+ result[s1] = trim(items[i+1].replace(/^\//, ""));
1787
1813
  i++;
1788
1814
  } else {
1789
1815
  result[s1] = '';
1790
1816
  }
1791
1817
  }
1818
+ for (let key of Object.keys(result)) {
1819
+ let comment = result[key];
1820
+ let defaultValStr = ''
1821
+ if (key.indexOf("=") !== -1) {
1822
+ delete result[key];
1823
+ let ss = key.split('=').map(trim);
1824
+ key = ss[0]
1825
+ defaultValStr = ss[1]
1826
+ }
1827
+ if (defaultValStr) {
1828
+ result[key] = ['<' + warnStr(defaultValStr) + '>', comment].join(' ')
1829
+ }
1830
+ }
1792
1831
  return result;
1793
1832
  }
1794
1833
 
@@ -1810,7 +1849,6 @@ function getArgDef(text, uniqueName) {
1810
1849
  }
1811
1850
  }
1812
1851
  } catch (e) {
1813
- $log(errorStack(e))
1814
1852
  argDef = {'[ParseError]': String(e)}
1815
1853
  }
1816
1854
  if (typeof argDef !== 'object') {
@@ -1831,45 +1869,6 @@ function getArgDef(text, uniqueName) {
1831
1869
  return Object.assign(temp, tempOpt)
1832
1870
  }
1833
1871
 
1834
- function setTips(key, value, onRm) {
1835
- getOr(global.$tips, key, []).push(value);
1836
- if (onRm) {
1837
- getOr(_tipsOnRm, key, []).push(onRm)
1838
- }
1839
- }
1840
-
1841
- function delTips(...keys) {
1842
- for (let key of Object.keys($tips)) {
1843
- if (keys.length === 0) {
1844
- delete $tips[key]
1845
- tipsOnRmCallback(key)
1846
- } else if (keys.indexOf(key) !== -1) {
1847
- delete $tips[key]
1848
- tipsOnRmCallback(key)
1849
- }
1850
- }
1851
- if (keys.length === 0) {
1852
- for (let key of Object.keys(_tipsOnRm)) {
1853
- tipsOnRmCallback(key)
1854
- }
1855
- }
1856
- }
1857
-
1858
- function tipsOnRmCallback(key) {
1859
- let callbacks = _tipsOnRm[key]
1860
- delete _tipsOnRm[key]
1861
- if (callbacks && callbacks.length > 0) {
1862
- for (let callback of callbacks) {
1863
- try {
1864
- callback()
1865
- } catch (e) {
1866
- $log(errorStack(e))
1867
- console.error(`[${key}] OnRmCallback: ${String(e)}`)
1868
- }
1869
- }
1870
- }
1871
- }
1872
-
1873
1872
  function getCmdMd5Key(str) {
1874
1873
  return '0x' + md5(str).substr(0, 8);
1875
1874
  }
@@ -1913,7 +1912,7 @@ async function _requireSource(currSpace, cmdMatchStr) {
1913
1912
  let result
1914
1913
  let uniqueName = filterRequire(currSpace, cmdMatchStr);
1915
1914
  let path = getFullPath(uniqueName)
1916
- let text = String(fs.readFileSync(path))
1915
+ let text = String(await fp.readFile(path))
1917
1916
  let pair = parseUniqueName(uniqueName)
1918
1917
  if (pair[1].startsWith('i ')) {
1919
1918
  result = await evalText(text, uniqueName)
@@ -1973,10 +1972,9 @@ async function evalText($text = '', $cmdName = '', $args = []) {
1973
1972
  return await _requireSource(currSpace, matchItem)
1974
1973
  }
1975
1974
  return await evalCode(addErrorTag($text), $cmdName, $args,
1976
- $data, $config,
1975
+ $data, $file,
1977
1976
  $require, $requires,
1978
1977
  nextLine, nextText,
1979
- setTips, delTips,
1980
1978
  wrapperInput, filterCmd,
1981
1979
  currSpace,
1982
1980
  $homeDir, $lib, _cmdMap);
package/deps/evalCode.js CHANGED
@@ -1,25 +1,27 @@
1
- const {errorTag: $errorTag, importG: $import, $log, $draft} = require("./util");
1
+ const {errorTag: $errorTag, importG: $import,
2
+ setTips: $setTips, delTips: $delTips,
3
+ } = require("./util");
2
4
  require = require("./util").requireG
3
5
  module.exports = async ($text = '', $cmdName = '', $args = [],
4
- $data, $config,
6
+ $data, $file,
5
7
  $require, $requires,
6
8
  $nextLine, $nextText,
7
- $setTips, $delTips,
8
9
  $enter, $filterCmd,
9
10
  $currentSpace,
10
11
  $homeDir, $lib,
11
12
  $cmdMap) => {
12
13
  const $defArgs = () => $args;
14
+ const $config = $lib.createConfig($cmdName);
13
15
  const $context = {
14
- global, $data, $config,
16
+ $data, $config, $file,
15
17
  $require, $requires, $import, $errorTag,
16
18
  $text, $cmdName, $args,
17
19
  $nextLine, $nextText,
18
20
  $setTips, $delTips,
19
21
  $enter, $filterCmd,
20
- $currentSpace, $log,
21
- $draft, $homeDir, $lib, $cmdMap
22
+ $currentSpace, $homeDir, $lib, $cmdMap
22
23
  }
24
+ const console = $lib.createConsole($cmdName);
23
25
  return await eval(`(async ()=>{${$text};
24
26
  })()`)
25
27
  }