@makano/rew 1.2.3 → 1.2.4

Sign up to get free protection for your applications and to get access to all the features.
package/bin/rew CHANGED
@@ -1,2 +1,3 @@
1
1
  #!/usr/bin/env node
2
+ global.fileName = __filename;
2
3
  require("../lib/rew/cli/cli.js");
@@ -5,7 +5,7 @@ const path = require('path');
5
5
  const { hideBin } = require('yargs/helpers');
6
6
  const { execSync } = require('child_process');
7
7
  const utils = require('./utils');
8
- const { existsSync, readFileSync, writeFileSync, mkdirSync } = require('fs');
8
+ const { existsSync, readFileSync, writeFileSync, mkdirSync, statSync } = require('fs');
9
9
  const { log } = require('./log');
10
10
  const os = require('os');
11
11
  const crypto = require('crypto');
@@ -18,13 +18,22 @@ const colors = require('colors');
18
18
  const { req } = require('../misc/req');
19
19
  const { gen_key } = require('../misc/bin');
20
20
 
21
- if (!existsSync(CONFIG_PATH)) {
21
+ if (!existsSync(CONFIG_PATH) || !existsSync(CONFIG_PATH + '/repos.yaml')) {
22
22
  mkdirSync(CONFIG_PATH, { recursive: true });
23
23
  utils.initFirst();
24
24
  }
25
25
 
26
26
  const npm_package_name = '@makano/rew';
27
27
 
28
+ function isFileArgument(file) {
29
+ try {
30
+ return existsSync(file) && statSync(file).isFile();
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+
36
+ const isFileGiven = isFileArgument(hideBin(process.argv)[0]) || hideBin(process.argv)[0] == 'run';
28
37
  yargs(hideBin(process.argv))
29
38
  .command(
30
39
  '$0 <file>',
@@ -112,25 +121,25 @@ yargs(hideBin(process.argv))
112
121
  describe: 'Path of the app to run',
113
122
  type: 'string',
114
123
  })
115
- .option('dev', {
116
- describe: 'If your entry file is a .qrew, then just use the .coffee instead',
117
- type: 'boolean',
118
- })
119
- .option('entry', {
120
- alias: 'e',
121
- describe: 'Choose entry file from app.config.exec',
122
- type: 'string',
123
- })
124
- .option('build', {
125
- alias: 'b',
126
- describe: 'Builds to a .qrew before running',
127
- type: 'boolean',
128
- })
129
- .option('translate', {
130
- alias: 't',
131
- describe: 'Builds to a .js before running, only used when --build is passed',
132
- type: 'boolean',
133
- });
124
+ .option('dev', {
125
+ describe: 'If your entry file is a .qrew, then just use the .coffee instead',
126
+ type: 'boolean',
127
+ })
128
+ .option('entry', {
129
+ alias: 'e',
130
+ describe: 'Choose entry file from app.config.exec',
131
+ type: 'string',
132
+ })
133
+ .option('build', {
134
+ alias: 'b',
135
+ describe: 'Builds to a .qrew before running',
136
+ type: 'boolean',
137
+ })
138
+ .option('translate', {
139
+ alias: 't',
140
+ describe: 'Builds to a .js before running, only used when --build is passed',
141
+ type: 'boolean',
142
+ });
134
143
  },
135
144
  (argv) => {
136
145
  utils.runApp(argv.path, argv);
@@ -141,16 +150,16 @@ yargs(hideBin(process.argv))
141
150
  'Add secrets to the current path',
142
151
  (yargs) => {
143
152
  yargs
144
- .positional('command', {
145
- describe: 'Path of the app to run',
146
- type: 'string',
147
- })
148
- .option('file', {
149
- alias: 'f',
150
- describe: 'Set file name',
151
- type: 'string',
152
- default: 'secrets.qrew'
153
- })
153
+ .positional('command', {
154
+ describe: 'Path of the app to run',
155
+ type: 'string',
156
+ })
157
+ .option('file', {
158
+ alias: 'f',
159
+ describe: 'Set file name',
160
+ type: 'string',
161
+ default: 'secrets.qrew'
162
+ })
154
163
  },
155
164
  (argv) => {
156
165
  const appPath = findAppInfo(path.join(process.cwd(), 'app.yaml'));
@@ -214,11 +223,19 @@ yargs(hideBin(process.argv))
214
223
  alias: 'r',
215
224
  describe: 'Install requirements of the app',
216
225
  type: 'boolean',
226
+ }).option('update', {
227
+ alias: 'u',
228
+ describe: 'Update the app',
229
+ type: 'boolean',
230
+ }).option('yes', {
231
+ alias: 'y',
232
+ describe: 'Auto yes',
233
+ type: 'boolean',
217
234
  });
218
235
  },
219
236
  async (argv) => {
220
- if(argv.requirements) utils.installReq(argv.path);
221
- else utils.installAppFrom(argv.path);
237
+ if (argv.requirements) utils.installReq(argv.path, argv);
238
+ else utils.installAppFrom(argv.path, argv);
222
239
  },
223
240
  )
224
241
  .command(
@@ -246,9 +263,9 @@ yargs(hideBin(process.argv))
246
263
  async (argv) => {
247
264
  const pkg = JSON.parse(readFileSync(path.resolve(__dirname, '../../../package.json'), { encoding: 'utf-8' }));
248
265
  const getLatest = async () => {
249
- try{
266
+ try {
250
267
  return (await req(`https://registry.npmjs.org/${pkg.name}`)).data['dist-tags'].latest
251
- } catch(e) {
268
+ } catch (e) {
252
269
  return `(${'!err'.blue.bgRed}, see ${`https://npmjs.com/package/${pkg.name}`.blue.underline})`;
253
270
  }
254
271
  }
@@ -257,7 +274,7 @@ yargs(hideBin(process.argv))
257
274
  const latest = await getLatest();
258
275
  const isLatest = latest === pkg.version;
259
276
  log(`Latest: ${pkg.name.cyan.bold}@${latest.yellow.bold}`.green.bold, isLatest ? ':end' : '');
260
- if(!isLatest){
277
+ if (!isLatest) {
261
278
  log(`There is an update available`.cyan.bold);
262
279
  log('Update With:'.yellow, `npm i -g ${npm_package_name}`.green.bold, ':end');
263
280
  }
@@ -279,9 +296,13 @@ yargs(hideBin(process.argv))
279
296
  describe: 'url of the repo',
280
297
  type: 'string',
281
298
  });
299
+ yargs.option('json', {
300
+ describe: 'Return a json output',
301
+ type: 'boolean',
302
+ });
282
303
  },
283
304
  async (argv) => {
284
- utils.repo(argv.command, argv.name, argv.url);
305
+ utils.repo(argv.command, argv.name, argv.url, argv);
285
306
  },
286
307
  )
287
308
  .command(
@@ -318,4 +339,4 @@ yargs(hideBin(process.argv))
318
339
  utils.build(argv);
319
340
  },
320
341
  )
321
- .help().argv;
342
+ .help(!isFileGiven).argv;
@@ -16,6 +16,7 @@ const { watch } = require('chokidar');
16
16
  const { execRewFile } = require('./run');
17
17
 
18
18
  const binpath = path.join(conf({}).create('').root, '.bin');
19
+ const logspath = path.join(conf({}).create('').root, '.logs');
19
20
  const localBinPath = path.join(binpath, '../../../', 'bin');
20
21
 
21
22
  module.exports = {
@@ -176,7 +177,7 @@ module.exports = {
176
177
  }
177
178
  }
178
179
  },
179
- installApp(pathname, rmidir, rmidiri) {
180
+ installApp(pathname, opts, rmidir, rmidiri) {
180
181
  if (!pathname) {
181
182
  return;
182
183
  }
@@ -197,8 +198,8 @@ module.exports = {
197
198
  if (p.descriptiondescription) {
198
199
  log(' Description'.blue + ': ' + p.description);
199
200
  }
200
- rl.question(logget('Install '.blue + pname.green.bold + '? (y/N) '), (f) => {
201
- if (f.toLowerCase() == 'y') {
201
+ const done = (f) => {
202
+ if (f.toLowerCase() == 'y' || f.toLowerCase() == 'yes') {
202
203
  if (fs.existsSync(installPath)) {
203
204
  execSync(`rm -r ${installPath}`);
204
205
  }
@@ -218,7 +219,13 @@ module.exports = {
218
219
  }
219
220
  if (c.install.commands) {
220
221
  for (let command of c.install.commands) {
221
- execSync(command.replace(/\$installPath/g, installPath));
222
+ try{
223
+ execSync(command.replace(/\$installPath/g, installPath), { stdio: 'inherit' });
224
+ } catch(e){
225
+ const logFile = path.join(logspath, 'logs-'+Date.now()+'.log');
226
+ fs.writeFileSync(logFile, e.toString() +'\n'+ e.stack);
227
+ log(` Command Failed: ${command}, check logs at ${logFile}`, ':end');
228
+ }
222
229
  }
223
230
  }
224
231
  if (c.install.file) {
@@ -250,12 +257,19 @@ module.exports = {
250
257
  log(' Canceled install'.red.bold, ':end');
251
258
  rl.close();
252
259
  }
253
- });
260
+ };
261
+ if (fs.existsSync(installPath) && !opts.update) {
262
+ rl.close();
263
+ log(` App Already Installed`.green.bold);
264
+ return log(` Run With --update or -u to update.`.green.bold, ':end');
265
+ }
266
+ if(opts.yes) done('y');
267
+ else rl.question(logget('Install '.blue + pname.green.bold + '? (y/N) '), done);
254
268
  } else {
255
269
  log(' Path is not a rew app'.red.bold, ':end');
256
270
  }
257
271
  },
258
- installReq(config) {
272
+ installReq(config, opts) {
259
273
  if (typeof config !== "object") {
260
274
  const confPath = path.join(config, './app.yaml');
261
275
  if (!fs.existsSync(confPath)) return log(' Path is not a rew app'.red.bold, ':end');
@@ -265,7 +279,7 @@ module.exports = {
265
279
  if (!Array.isArray(config.install.requirements)) return log(' Requirements must be an array'.red.bold, ':end');
266
280
  config.install.requirements.forEach(req => {
267
281
  log('Finding '.cyan + req.green);
268
- this.installAppFrom(req);
282
+ this.installAppFrom(req, opts);
269
283
  });
270
284
  }
271
285
  },
@@ -362,10 +376,10 @@ module.exports = {
362
376
  const repos = conf({}).create('').optionCenter('repos');
363
377
  return repos.get(repo);
364
378
  },
365
- async installAppFrom(path) {
366
- if (path.startsWith('github:')) this.installApp(await this.cloneGit(path), true, true);
367
- else if (path.startsWith('@')) this.fromRepo(path);
368
- else this.installApp(path);
379
+ async installAppFrom(path, opts) {
380
+ if (path.startsWith('github:')) this.installApp(await this.cloneGit(path), opts, true, true);
381
+ else if (path.startsWith('@')) this.fromRepo(path, opts);
382
+ else this.installApp(path, opts, null, null);
369
383
  },
370
384
  uninstall(packageName, all) {
371
385
  const confPath = path.join(CONFIG_PATH, packageName);
@@ -409,7 +423,7 @@ module.exports = {
409
423
  return {};
410
424
  }
411
425
  },
412
- async fromRepo(repoAndPkg) {
426
+ async fromRepo(repoAndPkg, opts) {
413
427
  const [repo, pkg] = repoAndPkg.slice(1).split('/');
414
428
  const repoUrl = this.findRepo(repo);
415
429
  if (!repoUrl) {
@@ -418,13 +432,13 @@ module.exports = {
418
432
  } else {
419
433
  const repoJson = await this.getRepoJson(repoUrl);
420
434
  if (repoJson?.packages?.[pkg]) {
421
- await this.installAppFrom(repoJson.packages[pkg]);
435
+ await this.installAppFrom(repoJson.packages[pkg], opts);
422
436
  } else {
423
437
  log(` Package "${pkg.cyan}" is not in repo "${repo.green}"`.red.bold, ":end");
424
438
  }
425
439
  }
426
440
  },
427
- async repo(command, key, value) {
441
+ async repo(command, key, value, options) {
428
442
  const confInstance = conf({}).create('').optionCenter('repos') || {};
429
443
 
430
444
  if (command === 'add' || command === 'set') {
@@ -433,6 +447,7 @@ module.exports = {
433
447
  if (key) {
434
448
  console.log(confInstance.get(key) || 'Not found');
435
449
  } else {
450
+ if(options.json) return console.log(JSON.stringify(confInstance.getAll()));
436
451
  console.log(Object.keys(confInstance.getAll()).join('\n'));
437
452
  }
438
453
  } else if (command === 'view') {
@@ -440,11 +455,13 @@ module.exports = {
440
455
  const url = confInstance.get(key);
441
456
  if (!url) return log(' Repo not found'.red.bold, ':end');
442
457
  const json = await this.getRepoJson(url);
458
+ if(options.json) return console.log(JSON.stringify(json));
443
459
  if (json.name) log(json.name);
444
460
  log('Packages:'.yellow)
445
461
  if (json.packages) Object.keys(json.packages).forEach(name => log(name)) || log(`${Object.keys(json.packages).length} Packages in ${key}`, ':end');
446
462
  else log('None'.blue, ':end')
447
463
  } else {
464
+ if(options.json) return JSON.stringify(confInstance.getAll());
448
465
  console.log(Object.keys(confInstance.getAll()).join('\n'));
449
466
  }
450
467
  } else if (command === 'delete') {
@@ -454,7 +471,9 @@ module.exports = {
454
471
  }
455
472
  },
456
473
  initFirst() {
474
+ log('First time init')
457
475
  conf({}).create('').optionCenter('repos').set('rewpkgs', '//raw.githubusercontent.com/kevinJ045/rewpkgs/main/main.yaml');
458
476
  fs.mkdirSync(binpath, { recursive: true });
477
+ fs.mkdirSync(logspath, { recursive: true });
459
478
  }
460
479
  };
@@ -11,6 +11,7 @@ const { print, input, clear } = require('../functions/stdout');
11
11
  const { curl } = require('../functions/curl');
12
12
  const { wait } = require('../functions/wait');
13
13
  const { scheduleFrame } = require('../functions/misc');
14
+ const { jsons, yaml, json, yamls } = require('../functions/json');
14
15
 
15
16
  module.exports = {
16
17
  cenum,
@@ -43,6 +44,11 @@ module.exports = {
43
44
  compose,
44
45
  curry,
45
46
 
47
+ json,
48
+ jsons,
49
+ yaml,
50
+ yamls,
51
+
46
52
  curl,
47
53
 
48
54
  print,
@@ -17,7 +17,7 @@ module.exports.curl = function curl(options, url){
17
17
  }).then(async r => {
18
18
  if(options.o) fs.writeFileSync(options.o, Buffer.from(await r.clone().arrayBuffer()));
19
19
  return r;
20
- }).then(r => options.json ? r.clone().json() : r));
20
+ }).then(r => options.json ? r.clone().json() : options.text ? r.clone().text() : r));
21
21
  if(options.a) return f.wait();
22
22
  else return f;
23
23
  }
@@ -0,0 +1,27 @@
1
+ const jsYaml = require("js-yaml");
2
+
3
+
4
+
5
+ function json(thing){
6
+ return JSON.parse(thing);
7
+ }
8
+
9
+ function jsons(thing){
10
+ return JSON.stringify(thing);
11
+ }
12
+
13
+
14
+ function yaml(thing){
15
+ return jsYaml.loadAll(thing)[0];
16
+ }
17
+
18
+ function yamls(thing){
19
+ return jsYaml.dump(thing);
20
+ }
21
+
22
+ module.exports = {
23
+ yaml,
24
+ yamls,
25
+ json,
26
+ jsons
27
+ }
@@ -3,6 +3,7 @@ const path = require('path');
3
3
 
4
4
  module.exports.customRequire = function customRequire(modulePath, filePath) {
5
5
  const resolvedPath = resolveModulePath(modulePath, filePath);
6
+ if(!resolvedPath) throw new Error('Module '+modulePath+' not found');
6
7
  return require(resolvedPath);
7
8
  };
8
9
 
@@ -20,21 +21,40 @@ function resolveModulePath(modulePath, filePath) {
20
21
  if (fs.existsSync(fullPath + '.json')) {
21
22
  return fullPath + '.json';
22
23
  }
24
+
23
25
  if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
24
- const packageJsonPath = path.join(fullPath, 'package.json');
25
- if (fs.existsSync(packageJsonPath)) {
26
- const main = require(packageJsonPath).main || 'index.js';
27
- const mainPath = path.join(fullPath, main);
28
- if (fs.existsSync(mainPath)) {
29
- return mainPath;
30
- }
31
- }
32
- const indexPath = path.join(fullPath, 'index.js');
33
- if (fs.existsSync(indexPath)) {
34
- return indexPath;
35
- }
26
+ return searchInPath(fullPath);
36
27
  }
37
- }
38
28
 
39
- throw new Error(`Cannot find module '${modulePath}'`);
29
+ const rootPath = modulePath.split('/').shift();
30
+ const halfFullPath = path.join(basePath, rootPath);
31
+ if (fs.existsSync(halfFullPath) && fs.statSync(halfFullPath).isDirectory()) {
32
+ return searchInPath(halfFullPath, ['.'].concat(fullPath.split('/').slice(1)).join('/'));
33
+ }
34
+ }
40
35
  }
36
+
37
+ function searchInPath(fullPath, exportses){
38
+ const packageJsonPath = path.join(fullPath, 'package.json');
39
+ if (fs.existsSync(packageJsonPath)) {
40
+ const packageJson = require(packageJsonPath);
41
+ let main = packageJson.main || 'index.js';
42
+ if(exportses){
43
+ if(packageJson.exports){
44
+ if(exportses in packageJson.exports) main = packageJson.exports[exportses];
45
+ }
46
+ }
47
+ if(typeof main == "object"){
48
+ if(Array.isArray(main)) main = main[0].require;
49
+ else main = main.require;
50
+ }
51
+ const mainPath = path.join(fullPath, main);
52
+ if (fs.existsSync(mainPath)) {
53
+ return mainPath;
54
+ }
55
+ }
56
+ const indexPath = path.join(fullPath, 'index.js');
57
+ if (fs.existsSync(indexPath)) {
58
+ return indexPath;
59
+ }
60
+ }
@@ -42,19 +42,6 @@ module.exports.prepareContext = function (
42
42
  ...defaultContext,
43
43
  ...pathLib(filepath),
44
44
  ...execLib(filepath),
45
- require: (package) => {
46
- try {
47
- return execOptions.nativeRequire || package.startsWith("node:")
48
- ? require(
49
- package.startsWith("node:")
50
- ? package.split("node:")[1]
51
- : package,
52
- )
53
- : customRequire(package, filepath);
54
- } catch (e) {
55
- throw new Error("Module " + package + " not found");
56
- }
57
- },
58
45
  ...custom_context,
59
46
  };
60
47
  }
@@ -66,6 +53,7 @@ module.exports.prepareContext = function (
66
53
  off: (event, listener) => process.off(event, listener),
67
54
  emit: (event, code) => process.emit(event, code),
68
55
  },
56
+ __execFile: global.fileName,
69
57
  env: process.env,
70
58
  cwd: () => process.cwd(),
71
59
  arch: process.arch,
@@ -74,6 +62,21 @@ module.exports.prepareContext = function (
74
62
  context.global = context;
75
63
  context.imports.assert = options.import ?? {};
76
64
  context.imp = imp(runPath, context);
65
+ context.require = (package) => {
66
+ try {
67
+ const search = execOptions.nativeRequire || package.startsWith("node:")
68
+ ? require(
69
+ package.startsWith("node:")
70
+ ? package.split("node:")[1]
71
+ : package,
72
+ )
73
+ : customRequire(package, filepath);
74
+ if(!search) throw new Error("Module " + package + " not found");
75
+ return search;
76
+ } catch (e) {
77
+ throw e;
78
+ }
79
+ };
77
80
  context.inc = (package, asserts) => {
78
81
  try {
79
82
  if (package.startsWith("node:") || package.startsWith("pkg:"))
@@ -22,7 +22,7 @@ function yamlFile(file) {
22
22
  }),
23
23
  ]);
24
24
 
25
- return yaml.load(file.content, { schema });
25
+ return file.content.startsWith('---') ? yaml.loadAll(file.content, { schema })[0] : yaml.load(file.content, { schema });
26
26
  }
27
27
 
28
28
  const importYaml = (module.exports.importYaml = function importYaml(filepath, file) {
@@ -14,7 +14,7 @@ module.exports = (context) => ({
14
14
  CONFIG_PATH,
15
15
  _onImport() {
16
16
  if (context.app) {
17
- return this.create(context.app.config.package);
17
+ return this.create(context.app.config.manifest.package);
18
18
  } else {
19
19
  return this.create(seededID(path.basename(context.module.filepath).replace(/[-_/\.]/g, '')));
20
20
  }
@@ -101,6 +101,7 @@ module.exports = (context) => ({
101
101
  remove: (key) => defaultCenter.remove(key),
102
102
  root: rootPath,
103
103
  package: packageName,
104
+ loadYaml: (file) => jsYaml.load(fs.readFileSync(file, { encoding: 'utf-8' }))
104
105
  };
105
106
  },
106
107
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@makano/rew",
3
- "version": "1.2.3",
3
+ "version": "1.2.4",
4
4
  "description": "A simple coffescript runtime and app manager",
5
5
  "main": "main.js",
6
6
  "directories": {