UNPKG

@plugjs/plug

Version:
48 lines (47 loc) 1.57 kB
// utils/jsonc.ts import { EOL } from "node:os"; import { parse, printParseErrorCode } from "jsonc-parser"; import { $plur } from "../logging/colors.mjs"; var JsoncError = class extends Error { constructor(errors) { const message = [`Found ${$plur(errors.length, "error", "errors", false)} parsing`]; for (const { code, line, column } of errors) { message.push(` ${code} at line ${line}, column ${column}`); } super(message.join("\n")); this.errors = errors; } }; function parseJsonc(data, options = {}) { const { disallowComments = false, allowTrailingComma = true } = options; if (!data) return void 0; const errors = []; const result = parse(data, errors, { disallowComments, allowTrailingComma, allowEmptyContent: false }); if (errors.length === 0) return result; const offsets = data.split(EOL).reduce(({ offsets: offsets2, offset }, line) => { offset += line.length + EOL.length; offsets2.push(offset); return { offsets: offsets2, offset }; }, { offset: 0, offsets: [0] }).offsets; function resolveOffset(offset) { for (let i = offsets.length - 1; i > 0; i--) { const lineOffset = offsets[i]; if (offset < lineOffset) continue; return { line: i + 1, column: offset - lineOffset + 1 }; } return { line: 1, column: offset + 1 }; } throw new JsoncError(errors.map((error) => { const code = printParseErrorCode(error.error); return { code, ...resolveOffset(error.offset) }; })); } export { JsoncError, parseJsonc }; //# sourceMappingURL=jsonc.mjs.map