pmex
Version:
Run dynamic NPM or YARN or PNPM
89 lines (88 loc) • 3.53 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
function args(defaults, options) {
var _a, _b, _c, _d, _e, _f;
const argv = (_b = (_a = process.argv) === null || _a === void 0 ? void 0 : _a.slice(2)) !== null && _b !== void 0 ? _b : [];
const { case: caseStyle, aliases = {} } = options || {};
// @ts-expect-error
const result = {
$: '',
_: [],
};
if (defaults) {
for (const attr in defaults) {
const finalAttr = (_c = aliases[attr]) !== null && _c !== void 0 ? _c : attr;
result[finalAttr] = defaults[attr];
}
}
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
const next = argv[i + 1];
if (!arg.startsWith('-')) {
result._.push(arg);
continue;
}
if (arg.startsWith('-')) {
const split = arg.split('=');
let attr = (_e = (_d = split.shift()) === null || _d === void 0 ? void 0 : _d.replace(/^-{1,2}/g, '')) !== null && _e !== void 0 ? _e : '';
let value = split.join('=');
if (!split.length && typeof next === 'string' && !next.startsWith('-')) {
value = next;
i++;
}
if (value === '' || value === 'true') {
value = true;
}
if (value === 'false') {
value = false;
}
// @ts-expect-error
if (typeof value === 'string' && !isNaN(value) && !isNaN(Number.parseFloat(value))) {
value = Number.parseFloat(value);
}
// Parse case
switch (caseStyle) {
case 'camel':
attr = attr
.replace(/^([a-zA-Z])/, (_, $1) => $1.toLowerCase())
.replace(/([^a-zA-Z])([a-zA-Z])/g, (_, $1, $2) => $2.toUpperCase());
break;
case 'pascal':
attr = attr
.replace(/^([a-zA-Z])/, (_, $1) => $1.toUpperCase())
.replace(/([^a-zA-Z])([a-zA-Z])/g, (_, $1, $2) => $2.toUpperCase());
break;
case 'snake':
attr = attr
.replace(/([a-z])([A-Z])/g, '$1-$2')
.toLowerCase()
.replace(/([^a-z_])/g, '_')
.replace(/^_/, '')
.replace(/_$/, '');
break;
case 'kebab':
attr = attr
.replace(/([a-z])([A-Z])/g, '$1-$2')
.toLowerCase()
.replace(/([^a-z\-])/g, '-')
.replace(/^-/, '')
.replace(/-$/, '');
break;
}
attr = (_f = aliases[attr]) !== null && _f !== void 0 ? _f : attr;
result[attr] = value;
}
}
for (const attr in result) {
if (attr === '_' || attr === '$')
continue;
const value = `${result[attr]}`;
const isExplicitVal = value !== 'true';
const prefix = isExplicitVal || attr.length > 1 ? '--' : '-';
const finalValue = /\s/.test(value) ? `"${value}"` : value;
result.$ += `${prefix}${attr}${isExplicitVal ? `=${finalValue}` : ''} `;
}
result.$ = `${result._.join(' ')} ${result.$.trim()}`.trim();
return result;
}
exports.default = args;