UNPKG

fava

Version:

A wannabe tiny largely-drop-in replacement for ava that works in the browser too.

93 lines (92 loc) 3.07 kB
/* IMPORT */ import isEqual from 'are-deeply-equal'; import Env from './env.js'; /* MAIN */ const Utils = { /* LANG API */ lang: { isEqual, escapeRegExp: (str) => { return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); }, keys: (object) => { return Object.keys(object); }, hang: () => { return new Promise(() => { }); }, isException: (value) => { return Utils.lang.isError(value) && value.hasOwnProperty('code'); }, isError: (value) => { return value instanceof Error; }, isLike: (value, partial) => { if (!Utils.lang.isPlainObject(value)) return false; if (partial === undefined) return true; if (!Utils.lang.isPlainObject(partial)) return false; const keys = Reflect.ownKeys(partial); for (const key of keys) { const val = partial[key]; if (Utils.lang.isPlainObject(val)) { const isLike = Utils.lang.isLike(value[key], val); if (!isLike) return false; } else { const isEqual = Object.is(value[key], val); if (!isEqual) return false; } } return true; }, isPlainObject: (value) => { if (typeof value !== 'object' || value === null) return false; if (Object.prototype.toString.call(value) !== '[object Object]') return false; const prototype = Object.getPrototypeOf(value); if (prototype === null) return true; return Object.getPrototypeOf(prototype) === null; }, isString: (value) => { return typeof value === 'string'; }, isUndefined: (value) => { return value === undefined; } }, /* API */ getErrorLines: async (error) => { const errorLines = []; if (!Env.is.cli || !error.stack) return errorLines; try { const fs = await import('node:fs'); const filePath = process.argv[1]; const fileContent = fs.readFileSync(filePath, 'utf8'); const lines = fileContent.split(/\r?\n|\r/g); const urlRe = new RegExp(`${Utils.lang.escapeRegExp(filePath)}:(\\d+)`, 'g'); for (const match of error.stack.matchAll(urlRe)) { const url = match[0]; const nr = Number(match[1]) - 1; const content = lines[nr].trim(); errorLines.push({ url, nr, content }); } } catch { } return errorLines; }, getStdoutColumns: () => { if (Env.is.cli) return process.stdout.columns; return 72; } }; /* EXPORT */ export default Utils;