generated from shgysk8zer0/npm-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
executable file
·58 lines (49 loc) · 1.8 KB
/
cli.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
#!/usr/bin/env node
import '@shgysk8zer0/polyfills'; // Adds polyfills for eg `Promise.try()`, `URLPattern`, `URL.parse` and `URL.canParse`, etc... All new APIs in JS.
import { resolveModulePath } from './utils.js';
import { serve } from './server.js';
const args = process.argv.slice(2).map(arg => arg.split('=')).flat();
const importConfig = specifier => import(resolveModulePath(specifier))
.then(module => typeof module.default === 'object' ? module.default : module)
.catch(err => ({ signal: AbortSignal.abort(err)}));
/**
*
* @param {string|string[]} flag
* @param {string} defaultValue
* @returns {string|void}
*/
function getArg(flag, defaultValue) {
const index = Array.isArray(flag) ? args.findIndex(arg => flag.includes(arg)) : args.indexOf(flag);
return index === -1 ? defaultValue : args[index + 1] ?? defaultValue;
}
/**
*
* @param {string|string[]} flag
* @returns {boolean}
*/
function hasArg(flag) {
return Array.isArray(flag) ? flag.some(f => args.includes(f)) : args.includes(flag);
}
async function getConfig() {
return hasArg(['-c', '--config']) ? await importConfig(getArg(['-c', '--config'])) : {
hostname: getArg(['-h', '--hostname']),
port: parseInt(getArg(['-p', '--port'], '8000')),
pathname: getArg(['-a', '--path'], '/'),
open: hasArg(['-o', '--open']),
staticRoot: getArg(['-s', '--static'], '/'),
timeout: hasArg(['-t', '--timeout']) ? parseInt(getArg(['-t', '--timeout'], '0')) || 0 : undefined,
logger: hasArg(['-d', '--debug']) ? console.error : null,
};
}
async function start() {
const config = await getConfig();
if (config instanceof Error) {
throw config;
} else if (config.signal instanceof AbortSignal && config.signal.abort) {
throw config.signal.reason;
} else {
const { url } = await serve(config);
console.log(`Now serving on ${url}`);
}
}
start();