verror-0
Version:
VError without dependencies on top of nodejs standart library
64 lines (63 loc) • 2.32 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseArgs = parseArgs;
const node_util_1 = require("node:util");
const is_error_js_1 = require("./is-error.js");
function parseArgs(args) {
let argv;
if (typeof args !== 'object' || args === null || !('argv' in args)) {
throw new Error('args should be object');
}
if (!Array.isArray(args.argv)) {
throw new Error('argv should be array');
}
argv = args.argv;
const options = {};
let sprintfArgs = [];
// Определим какая форма вызова используется.
if (argv.length === 0) {
// Тут ничего делать не нужно.
}
else if ((0, is_error_js_1.isError)(argv[0])) {
options.cause = argv[0];
// Слайсим все элементы как аргументы sprintf после причины/ошибки.
sprintfArgs = argv.slice(1);
}
else if (typeof argv[0] === 'object' && argv[0] !== null) {
for (const k in argv[0]) {
options[k] = argv[0][k];
}
sprintfArgs = argv.slice(1);
}
else {
if (typeof argv[0] !== 'string') {
throw new Error('first argument to VError or WError constructor must be a string, object, or Error');
}
// В случае когда передана строка - все аргументы идут для sprintf.
sprintfArgs = argv;
}
let shortmessage;
if (sprintfArgs.length === 0) {
shortmessage = '';
}
else {
// 1й - message, остальные - параметры.
shortmessage = (0, node_util_1.format)(...sprintfArgs);
}
if (args.strict) {
options.strict = true;
}
if (options.strict) {
if (sprintfArgs.some((v) => v === null || v === undefined)) {
throw new Error('strict mode violation: one or more arguments in sprintf args are null or undefined');
}
}
if ('maxCauseDepth' in options && (typeof options.maxCauseDepth !== 'number' || options.maxCauseDepth <= 0)) {
throw new Error('maxCauseDepth must be a positive number');
}
options.maxCauseDepth = options.maxCauseDepth ?? 3;
return {
options,
shortmessage
};
}