jsir 2.0.4 → 2.0.6

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
@@ -1,41 +1,58 @@
1
1
  #!/usr/bin/env node
2
+ const path = require('path');
3
+ const {spawnSync} = require('child_process');
4
+ const globalDirectories = require('global-dirs');
5
+ let nodePath = process.env.NODE_PATH ? process.env.NODE_PATH.trim():'';
6
+ let avoidFlag = path.delimiter + path.delimiter + path.delimiter;
7
+ if (!nodePath.endsWith(avoidFlag) && nodePath.indexOf(globalDirectories.npm.packages) === -1) {
8
+ process.env.NODE_PATH = [globalDirectories.npm.packages, nodePath].filter(i => i).join(path.delimiter) + avoidFlag
9
+ process.on('SIGINT', function () {});
10
+ spawnSync(process.argv[0], process.argv.slice(1), {stdio:"inherit"});
11
+ return;
12
+ }
13
+
14
+ const $lib = require('../util');
2
15
  const {
3
16
  getLibDataDir, trim, regEach, getConfig, mkdir, reget,
4
17
  getCbText, e, sleep, objDataFile, vl, md5, BigNumber,
5
18
  info, warn, error, arrayDataFile, infoStr, warnStr, errorStack,
6
19
  getInfo, ei, pad, msgStr, getType,
7
20
  errorTag, isArgsMatch, draftQuery, setConfig,
8
- $log, $draft, $config, getTextComments
9
- } = require('../util')
21
+ $log, $draft, getTextComments
22
+ } = $lib;
23
+ const _args = process.argv.slice(2).map(trim);
10
24
  const evalCode = require('../evalCode')
25
+ const _chokidar = require('chokidar');
26
+ const setting = require('../setting')
27
+ const _fs = require('fs')
28
+ const readline = require("readline");
11
29
 
30
+ const _workspaceConfigFile = 'workspace.json';
31
+ const _libDataDir = getLibDataDir()
32
+ const _tipsOnRm = {}
33
+ const _fileWatcherMap = {}
12
34
  const _types = {
13
35
  'e': "exe",
14
36
  'i': "init",
15
37
  'f': "file"
16
38
  }
17
- const _chokidar = require('chokidar');
18
- const _fs = require('fs')
19
- const _libDataDir = getLibDataDir()
20
- const _args = process.argv.slice(2).map(trim)
21
- const _history9 = []
22
- const _tipsOnRm = {}
23
- const readline = require("readline");
24
- const _fileWatcherMap = {}
25
- const setting = require('../setting')
39
+ const $config = {
40
+ get: getConfig,
41
+ set: setConfig
42
+ }
43
+
26
44
  let _cmdMapFile = setting.name + 'CmdMap.json'
27
45
  let _cmdMap = {}
28
46
  let _rl
29
47
  let _rlHistory = []
30
48
  let _haveWrapperInput = true
31
- let _workspaceConfigFile = 'workspace.json';
32
49
  let _exit = false
33
50
 
34
51
  const _data = {}
35
52
  const $data = {
36
- get: (key, val) => {
37
- if (!(key in _data) && val !== undefined) {
38
- _data[key] = val
53
+ get: (key, defaultVal) => {
54
+ if (!(key in _data) && defaultVal !== undefined) {
55
+ _data[key] = defaultVal
39
56
  }
40
57
  return _data[key]
41
58
  },
@@ -48,7 +65,6 @@ const $data = {
48
65
  keys: () => Object.keys(_data)
49
66
  }
50
67
  const $homeDir = getLibDataDir()
51
- const $lib = {...require('../util')}
52
68
 
53
69
  global.$tips = {}
54
70
  global.$newInput = false
@@ -95,10 +111,8 @@ function checkWorkspaces() {
95
111
  async function start() {
96
112
  checkWorkspaces()
97
113
 
114
+ _cmdMap = objDataFile(_cmdMapFile)
98
115
  if (_args[0]) {
99
- if (_noAppendNextLine) {
100
- _cmdMap = objDataFile(_cmdMapFile)
101
- }
102
116
  let line = _args.map(i => {
103
117
  if (/\s+/.test(i) || !i) {
104
118
  i = `"${i}"`
@@ -107,8 +121,12 @@ async function start() {
107
121
  }).join(' ')
108
122
  await wrapperInput(line)
109
123
  } else {
110
- _noAppendNextLine = false
111
- console.log(warnStr("You can start with .help, use * to expand context"))
124
+ let defaultAction = getConfig("defaultAction", "repl");
125
+ if (defaultAction && keywordDef[defaultAction]) {
126
+ await wrapperInput('.' + defaultAction)
127
+ } else {
128
+ await wrapperInput('.repl')
129
+ }
112
130
  }
113
131
  }
114
132
 
@@ -247,7 +265,7 @@ function initRl(callback, preStr, hidden) {
247
265
  if (promptStr !== '') {
248
266
  promptStr = (preStr
249
267
  || ((callback && callback !== wrapperInput) ? "-> ":"")
250
- || [Object.values(global.$tips).filter(i => String(i)).join(','), $defaultSpace].filter(i => i).join(':') + `> `)
268
+ || [Object.values(global.$tips).map(String).filter(i => i).map(i => i.replace(/,/g, '-')).join(','), $defaultSpace].filter(i => i).join(':') + `> `)
251
269
  promptStr = infoStr(promptStr)
252
270
  }
253
271
  if (hidden) {
@@ -396,26 +414,6 @@ function rename(dir, oldName, newName) {
396
414
  listCmd()
397
415
  }
398
416
 
399
- function putHis(x) {
400
- if (_history9.indexOf(x) !== -1) {
401
- _history9.splice(_history9.indexOf(x), 1)
402
- }
403
- _history9.push(x)
404
- if (_history9.length > 9) {
405
- _history9.shift()
406
- }
407
- }
408
-
409
- function hisToCmdMap() {
410
- let i = 1
411
- let cmdMap = {}
412
- for (let item of _history9) {
413
- cmdMap[i] = item
414
- i ++
415
- }
416
- _cmdMap = cmdMap
417
- }
418
-
419
417
  function listCmd() {
420
418
  let items = Object.values(_cmdMap)
421
419
  .filter(item => _fs.existsSync(getFullPath(item)))
@@ -527,18 +525,14 @@ async function _wrapperInput(str) {
527
525
  if (!text) {
528
526
  text = '$context';
529
527
  }
530
- let items = text.split(/\s+/).map(trim).filter(i => i)
531
- let result = await evalText('return ' + items[0])
528
+ let result = await evalText('return ' + text)
532
529
  if (!result || typeof result === 'string' || Object.keys(result).length === 0) {
533
530
  console.nable([getInfo(result)])
534
531
  return
535
532
  }
536
533
  let rows = []
537
- let matchs = items.slice(1)
538
534
  for (let key of Object.keys(result)) {
539
- if (matchs.length === 0 || isArgsMatch(key, [matchs.join(' ')])){
540
- rows.push(getInfo(result[key], key))
541
- }
535
+ rows.push(getInfo(result[key], key))
542
536
  }
543
537
  if (rows.length === 0) {
544
538
  warn("no items")
@@ -549,9 +543,9 @@ async function _wrapperInput(str) {
549
543
  await evalText(text)
550
544
  }
551
545
  } else if (str.match(/^\./)) {
552
- let argsStr = trim(str.substring(1))
553
- if (argsStr) {
554
- await dealKeyword(argsStr)
546
+ let items = enrichArgs(trim(str.substring(1))).map(trim)
547
+ if (items.length > 0) {
548
+ await dealKeyword(items[0], items.slice(1))
555
549
  } else {
556
550
  help()
557
551
  }
@@ -561,7 +555,6 @@ async function _wrapperInput(str) {
561
555
  } else {
562
556
  let strs = str.split(/\s+/)
563
557
  if (_cmdMap[strs[0]]) {
564
- putHis(_cmdMap[strs[0]])
565
558
  let path = getFullPath(_cmdMap[strs[0]])
566
559
  let uniqueName = trim(_cmdMap[strs[0]]);
567
560
  let fileName = parseUniqueName(uniqueName)[1]
@@ -699,7 +692,7 @@ const keywordDef = {
699
692
  exeFn: (args) => {
700
693
  help()
701
694
  },
702
- short: 'H'
695
+ short: 'h'
703
696
  },
704
697
  list: {
705
698
  comment: '查看文件列表',
@@ -710,7 +703,7 @@ const keywordDef = {
710
703
  listCmd()
711
704
  },
712
705
  args: {
713
- queryParams: '条件参数(param1,param2 param3 ...), [,]代表全部'
706
+ queryParams: '字符串匹配,[,]代表全部,关键字可以省略'
714
707
  },
715
708
  short: 'l'
716
709
  },
@@ -873,14 +866,6 @@ const keywordDef = {
873
866
  // },
874
867
  // short: 'd'
875
868
  // },
876
- history: {
877
- comment: '查看执行记录',
878
- exeFn: (args) => {
879
- hisToCmdMap()
880
- listCmd()
881
- },
882
- short: 'h'
883
- },
884
869
  file: {
885
870
  comment: '工作文件模式',
886
871
  exeFn: async (args) => {
@@ -1009,20 +994,28 @@ const keywordDef = {
1009
994
  process.exit(0)
1010
995
  },
1011
996
  short: 'q'
997
+ },
998
+ repl: {
999
+ comment: '交互式界面',
1000
+ exeFn: (args) => {
1001
+ _noAppendNextLine = false
1002
+ console.log(warnStr("You can start with .help, use * to expand context"))
1003
+ if (Object.keys(_cmdMap).length > 0) {
1004
+ listCmd()
1005
+ }
1006
+ },
1007
+ short: 'p'
1012
1008
  }
1013
1009
  }
1014
1010
 
1015
- async function dealKeyword(str) {
1011
+ async function dealKeyword(keyword, args) {
1016
1012
  let unMatched = true;
1017
1013
  for (let key of Object.keys(keywordDef)) {
1018
1014
  let item = keywordDef[key]
1019
- let currStr = str === key ? item.short : str.replace(new RegExp(`^${key}\\s+`), item.short + ' ')
1020
- let strs = trim(currStr).split(/\s+/)
1021
- let fstr = strs[0]
1022
- let ostr = strs.slice(1)
1023
- if (item.short === fstr) {
1015
+ let shortKey = keyword === key ? item.short : keyword;
1016
+ if (item.short === shortKey) {
1024
1017
  unMatched = false;
1025
- await item.exeFn(ostr);
1018
+ await item.exeFn(args);
1026
1019
  break;
1027
1020
  }
1028
1021
  }
@@ -1167,7 +1160,9 @@ function initWorkspace(space) {
1167
1160
  if (!$workspaceMap[current]) {
1168
1161
  workspace = 'local'
1169
1162
  }
1170
- setConfig("workspace", workspace)
1163
+ if (workspace !== current) {
1164
+ setConfig("workspace", workspace)
1165
+ }
1171
1166
  global.$defaultSpace = workspace;
1172
1167
  }
1173
1168
 
@@ -1499,6 +1494,8 @@ async function _requireSource(currSpace, cmdMatchStr, printLog = false) {
1499
1494
  result = async (argsStr) => {
1500
1495
  return await runCmd(trim(argsStr), uniqueName, text)
1501
1496
  }
1497
+ } else {
1498
+ result = text;
1502
1499
  }
1503
1500
  if (!vl(result)) {
1504
1501
  if (nullable) {
@@ -1575,9 +1572,15 @@ async function evalText($text = '', $cmdName = '', $args = []) {
1575
1572
  return (await _requireSources(currSpace, matchItem, printLog))[0]
1576
1573
  }
1577
1574
  try {
1578
- return await evalCode($text, $cmdName, $args, $data, $require, $requires,
1579
- nextLine, nextText, setTips, delTips, wrapperInput, filterCmd,
1580
- currSpace, $log, $draft, $config, $homeDir, $lib)
1575
+ return await evalCode($text, $cmdName, $args,
1576
+ $data, $config,
1577
+ $require, $requires,
1578
+ nextLine, nextText,
1579
+ setTips, delTips,
1580
+ wrapperInput, filterCmd,
1581
+ currSpace,
1582
+ $log, $draft,
1583
+ $homeDir, $lib)
1581
1584
  } catch(e) {
1582
1585
  throw errorTag(e, $cmdName);
1583
1586
  }
package/evalCode.js CHANGED
@@ -1,32 +1,25 @@
1
- const {info: $info, msg: $msg, warn: $warn, error: $error,
2
- infoStr: $infoStr, msgStr: $msgStr, warnStr: $warnStr, errorStr: $errorStr,
3
- tableStr: $tableStr, nableStr: $nableStr,
4
- errorMsg: $errorMsg, errorStack: $errorStack} = require("./util");
5
- require = require("./util").requireG;
1
+ const {info: $info, msg: $msg, warn: $warn, error: $error, importG: $import} = require("./util");
2
+ require = require("./util").requireG
6
3
  module.exports = async ($text = '', $cmdName = '', $args = [],
7
- $data,
4
+ $data, $config,
8
5
  $require, $requires,
9
6
  $nextLine, $nextText,
10
7
  $setTips, $delTips,
11
8
  $enter, $filterCmd,
12
- $currentSpace, $log,
13
- $draft, $config,
9
+ $currentSpace,
10
+ $log, $draft,
14
11
  $homeDir, $lib) => {
15
12
  const $defArgs = () => $args;
16
13
  const $context = {
17
- global, $data,
18
- $require, $requires,
14
+ global, $data, $config,
15
+ $require, $requires, $import,
19
16
  $info, $msg, $warn, $error,
20
- $infoStr, $msgStr, $warnStr, $errorStr,
21
- $tableStr, $nableStr,
22
- $errorMsg, $errorStack,
23
17
  $text, $cmdName, $args,
24
18
  $nextLine, $nextText,
25
19
  $setTips, $delTips,
26
20
  $enter, $filterCmd,
27
21
  $currentSpace, $log,
28
- $draft, $config,
29
- $homeDir, $lib
22
+ $draft, $homeDir, $lib
30
23
  }
31
24
  return await eval(`(async ()=>{${$text};
32
25
  })()`)
package/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
 
2
2
  module.exports = {
3
- ...require('util'),
4
- ...require('sol')
3
+ ...require('util')
5
4
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsir",
3
- "version": "2.0.4",
3
+ "version": "2.0.6",
4
4
  "description": "js script manager tool",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/util.js CHANGED
@@ -37,57 +37,6 @@ const $draft = str => {
37
37
  }
38
38
  const $fnCache = {}
39
39
 
40
- const $config = {
41
- _buildId: null,
42
- build: async function () {
43
- if ($config._buildId == null) {
44
- await _buildConfig()
45
- }
46
- },
47
- close: () => {
48
- clearTimeout($config._buildId)
49
- $config._buildId = null
50
- },
51
- localConfig: {},
52
- remoteConfig: {},
53
- getLocal: (key, defaultVal) => {
54
- if (key && Object.keys($config.localConfig).indexOf(key) === -1) {
55
- getConfig(key)
56
- }
57
- return getVl($config.localConfig[key], defaultVal)
58
- },
59
- getRemote: (key, defaultVal) => {
60
- let machine = $config.getLocal('machine')
61
- let remoteKey = `${machine}${machine ? '-':''}${key}`
62
- return getVl($config.remoteConfig[remoteKey], $config.remoteConfig[key], defaultVal)
63
- },
64
- get: (key, defaultVal) => {
65
- return getFnVl(() => $config.getRemote(key),
66
- () => $config.getLocal(key), defaultVal)
67
- },
68
- set: (key, val) => {
69
- $config.localConfig[key] = val
70
- setConfig(key, val)
71
- }
72
- }
73
-
74
- async function _buildConfig() {
75
- try {
76
- $config.localConfig = getConfig()
77
- let remoteConfigIp = getConfig('remoteConfigIp')
78
-
79
- if (remoteConfigIp) {
80
- if (remoteConfigIp.indexOf(":") === -1) {
81
- remoteConfigIp = remoteConfigIp+":9563"
82
- }
83
- $config.remoteConfig = (await got.get(`http://${remoteConfigIp}`)).data || $config.remoteConfig
84
- } else {
85
- $config.remoteConfig = {}
86
- }
87
- } catch (e) {}
88
- $config._buildId = setTimeout(_buildConfig, 3000);
89
- }
90
-
91
40
  function isArgsMatch(text, args, callback, useMd5, md5Str) {
92
41
  let match = false
93
42
  for (let arg of args) {
@@ -389,11 +338,27 @@ function requireG(module){
389
338
  } catch (e) {}
390
339
  let path = globalDirectories.npm.packages + '/' + module;
391
340
  if (!fs.existsSync(path)) {
392
- throw `ERROR: ${module} not found, use [npm install -g ${module}] to install it`;
341
+ console.log(warnStr(`npm install -g ${module}`))
342
+ throw `${module} not found, use above cmd to install it`;
393
343
  }
394
344
  return require(path);
395
345
  }
396
346
 
347
+ async function importG(module) {
348
+ try {
349
+ let result = await import(module);
350
+ if (result) {
351
+ return result
352
+ }
353
+ } catch (e) {}
354
+ let path = globalDirectories.npm.packages + '/' + module;
355
+ if (!fs.existsSync(path)) {
356
+ console.log(warnStr(`npm install -g ${module}`))
357
+ throw `${module} not found, use above cmd to install it`;
358
+ }
359
+ return await import(path);
360
+ }
361
+
397
362
  function validStr(str, name) {
398
363
  if (!vl(str) || typeof str !== 'string') {
399
364
  throw "invalid cipher " + name;
@@ -434,11 +399,11 @@ function aesDecipher(str, key){
434
399
  }
435
400
  }
436
401
 
437
- function getConfig(key, defaultVal = '') {
438
- let configInit = {}
439
- if (key) {
440
- configInit[key] = ''
402
+ function getConfig(key, defaultVal = null) {
403
+ if (typeof defaultVal === "string") {
404
+ defaultVal = trim(defaultVal)
441
405
  }
406
+ let configInit = {}
442
407
  let configFile = getLibDataDir() + '/config.json';
443
408
  if (!fs.existsSync(configFile)) {
444
409
  fs.writeFileSync(configFile, JSON.stringify(configInit, null, 2));
@@ -448,23 +413,15 @@ function getConfig(key, defaultVal = '') {
448
413
  if (key === undefined) {
449
414
  return config
450
415
  }
451
- let actConfigKeys = Object.keys(config);
452
416
  let writeFlag = false
453
- for (let k of Object.keys(configInit)) {
454
- if (actConfigKeys.indexOf(k) === -1) {
455
- writeFlag = true
456
- config[k] = ''
457
- }
417
+ if (!(key in config)) {
418
+ writeFlag = true
419
+ config[key] = defaultVal
458
420
  }
459
421
  if (writeFlag) {
460
422
  fs.writeFileSync(configFile, JSON.stringify(config, null, 2))
461
423
  }
462
- let val
463
- if (!(key in config)) {
464
- val = defaultVal
465
- } else {
466
- val = config[key]
467
- }
424
+ let val = config[key]
468
425
  if (typeof val === "string") {
469
426
  val = trim(val)
470
427
  }
@@ -491,25 +448,6 @@ function setConfig(key, val) {
491
448
  return val
492
449
  }
493
450
 
494
- async function getUniConfig(key, defaultVal) {
495
- let remoteConfigIp = getConfig('remoteConfigIp')
496
- let val
497
- if (remoteConfigIp) {
498
- if (remoteConfigIp.indexOf(":") === -1) {
499
- remoteConfigIp = remoteConfigIp+":9563"
500
- }
501
- let machine = getConfig('machine')
502
- val = (await got.get(`http://${remoteConfigIp}/${machine}${machine ? '-':''}${key}`)).data;
503
- if (!vl(val)) {
504
- val = (await got.get(`http://${remoteConfigIp}/${key}`)).data;
505
- }
506
- }
507
- if (!vl(val)) {
508
- val = getConfig(key, defaultVal)
509
- }
510
- return val;
511
- }
512
-
513
451
  function bAdd(str1, str2) {
514
452
  return new BigNumber(String(str1)).plus(new BigNumber(String(str2))).toString()
515
453
  }
@@ -1246,6 +1184,7 @@ module.exports = {
1246
1184
  aesCipher,
1247
1185
  aesDecipher,
1248
1186
  requireG,
1187
+ importG,
1249
1188
  toBigNum,
1250
1189
  objDataFile,
1251
1190
  appendLog,
@@ -1258,7 +1197,6 @@ module.exports = {
1258
1197
  eFn,
1259
1198
  removeFirst,
1260
1199
  sleep,
1261
- getUniConfig,
1262
1200
  timeLimit,
1263
1201
  dayJs,
1264
1202
  setCbText,
@@ -1266,7 +1204,6 @@ module.exports = {
1266
1204
  vl,
1267
1205
  getVl,
1268
1206
  getFnVl,
1269
- $config,
1270
1207
  timeStr,
1271
1208
  splitArray,
1272
1209
  BigNumber,
@@ -1310,5 +1247,6 @@ module.exports = {
1310
1247
  iarrayDataFile,
1311
1248
  isArgsMatch,
1312
1249
  draftQuery,
1313
- getTextComments
1250
+ getTextComments,
1251
+ globalModulesPath: globalDirectories.npm.packages
1314
1252
  }
@@ -1,31 +0,0 @@
1
- #!/usr/bin/env node
2
- let {$config, run, lisPid} = require('../util')
3
-
4
- const server = require('server');
5
- let address = require('address');
6
- const { get } = server.router;
7
- const {send} = server.reply
8
-
9
- let port = Number(process.argv[2] || 9563 )
10
- let router = [
11
- get('/', () => {
12
- return send($config.localConfig)
13
- }),
14
- get('/:key', (ctx) => {
15
- if (!$config.localConfig.hasOwnProperty(ctx.params.key)) {
16
- return send(null)
17
- }
18
- return send($config.getLocal(ctx.params.key))
19
- })
20
- ]
21
-
22
- lisPid('configServer_' + port)
23
-
24
- run(async () => {
25
- await $config.build()
26
- await server({
27
- port
28
- },router);
29
- console.log("http://localhost:"+port);
30
- console.log("http://" + address.ip()+":"+port);
31
- })
package/cmd/dirServer.js DELETED
@@ -1,61 +0,0 @@
1
- #!/usr/bin/env node
2
- let http = require('http');
3
- let url=require('url');
4
- let fs=require('fs');
5
- let mine=require('../source/mine').types;
6
- let path=require('path');
7
- let address = require('address');
8
- let urlencode = require('urlencode');
9
- let {lisPid} = require('../util')
10
-
11
- let server = http.createServer(function (request, response) {
12
- let pathname = urlencode.decode(url.parse(request.url).pathname, "utf8");
13
- let realPath = process.cwd() + pathname;
14
- let ext = path.extname(realPath);
15
- ext = ext ? ext.slice(1) : 'unknown';
16
- if (fs.existsSync(realPath)) {
17
- if (fs.statSync(realPath).isFile()) {
18
- fs.readFile(realPath, "binary", function (err, file) {
19
- if (err) {
20
- response.writeHead(500, {
21
- 'Content-Type': 'text/plain'
22
- });
23
- response.end(err);
24
- } else {
25
- let contentType = mine[ext] || "text/plain";
26
- response.writeHead(200, {
27
- 'Content-Type': contentType
28
- });
29
- response.write(file, "binary");
30
- response.end();
31
- }
32
- });
33
- } else {
34
- let paths = fs.readdirSync(realPath)
35
- response.writeHead(200, {
36
- 'Content-Type': 'text/html'
37
- });
38
- response.write('<head><meta charset="utf-8"/></head>');
39
- paths.forEach(path => {
40
- response.write(`
41
- <a href="/${(request.url + '/').replace(/^\/+/, '')}${path}">${path}</a><br/>
42
- `)
43
- })
44
- response.end();
45
- }
46
- } else {
47
- response.writeHead(404, {
48
- 'Content-Type': 'text/plain'
49
- });
50
- response.write("This request URL " + pathname + " was not found on this server.");
51
- response.end();
52
- }
53
- });
54
-
55
- let port = process.argv[2] || 8088;
56
- server.listen(port);
57
-
58
- console.log("http://localhost:"+port);
59
- console.log("http://" + address.ip()+":"+port);
60
-
61
- lisPid('dirServer_' + port)