|
| 1 | +/* |
| 2 | + MIT License http://www.opensource.org/licenses/mit-license.php |
| 3 | +*/ |
| 4 | + |
| 5 | +"use strict"; |
| 6 | + |
| 7 | +/** @typedef {import("../util/fs").JsonValue} JsonValue */ |
| 8 | + |
| 9 | +// Inspired by https://github.com/npm/json-parse-even-better-errors |
| 10 | + |
| 11 | +// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) |
| 12 | +// because the buffer-to-string conversion in `fs.readFileSync()` |
| 13 | +// translates it to FEFF, the UTF-16 BOM. |
| 14 | +/** |
| 15 | + * @param {string | Buffer} txt text |
| 16 | + * @returns {string} text without BOM |
| 17 | + */ |
| 18 | +const stripBOM = (txt) => String(txt).replace(/^\uFEFF/, ""); |
| 19 | + |
| 20 | +class JSONParseError extends SyntaxError { |
| 21 | + /** |
| 22 | + * @param {Error} err err |
| 23 | + * @param {EXPECTED_ANY} raw raw |
| 24 | + * @param {string} txt text |
| 25 | + * @param {number=} context context |
| 26 | + * @param {EXPECTED_FUNCTION=} caller caller |
| 27 | + */ |
| 28 | + constructor(err, raw, txt, context = 20, caller = parseJson) { |
| 29 | + let originalMessage = err.message; |
| 30 | + /** @type {string} */ |
| 31 | + let message; |
| 32 | + /** @type {number} */ |
| 33 | + let position; |
| 34 | + |
| 35 | + if (typeof raw !== "string") { |
| 36 | + message = `Cannot parse ${Array.isArray(raw) && raw.length === 0 ? "an empty array" : String(raw)}`; |
| 37 | + position = 0; |
| 38 | + } else if (!txt) { |
| 39 | + message = `${originalMessage} while parsing empty string`; |
| 40 | + position = 0; |
| 41 | + } else { |
| 42 | + // Node 20 puts single quotes around the token and a comma after it |
| 43 | + const UNEXPECTED_TOKEN = /^Unexpected token '?(.)'?(,)? /i; |
| 44 | + const badTokenMatch = originalMessage.match(UNEXPECTED_TOKEN); |
| 45 | + const badIndexMatch = originalMessage.match(/ position\s+(\d+)/i); |
| 46 | + |
| 47 | + if (badTokenMatch) { |
| 48 | + const h = badTokenMatch[1].charCodeAt(0).toString(16).toUpperCase(); |
| 49 | + const hex = `0x${h.length % 2 ? "0" : ""}${h}`; |
| 50 | + |
| 51 | + originalMessage = originalMessage.replace( |
| 52 | + UNEXPECTED_TOKEN, |
| 53 | + `Unexpected token ${JSON.stringify(badTokenMatch[1])} (${hex})$2 ` |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + /** @type {number | undefined} */ |
| 58 | + let errIdx; |
| 59 | + |
| 60 | + if (badIndexMatch) { |
| 61 | + errIdx = Number(badIndexMatch[1]); |
| 62 | + } else if ( |
| 63 | + // doesn't happen in Node 22+ |
| 64 | + /^Unexpected end of JSON.*/i.test(originalMessage) |
| 65 | + ) { |
| 66 | + errIdx = txt.length - 1; |
| 67 | + } |
| 68 | + |
| 69 | + if (errIdx === undefined) { |
| 70 | + message = `${originalMessage} while parsing '${txt.slice(0, context * 2)}'`; |
| 71 | + position = 0; |
| 72 | + } else { |
| 73 | + const start = errIdx <= context ? 0 : errIdx - context; |
| 74 | + const end = |
| 75 | + errIdx + context >= txt.length ? txt.length : errIdx + context; |
| 76 | + const slice = `${start ? "..." : ""}${txt.slice(start, end)}${end === txt.length ? "" : "..."}`; |
| 77 | + |
| 78 | + message = `${originalMessage} while parsing ${txt === slice ? "" : "near "}${JSON.stringify(slice)}`; |
| 79 | + position = errIdx; |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + super(message); |
| 84 | + |
| 85 | + this.name = "JSONParseError"; |
| 86 | + this.systemError = err; |
| 87 | + this.position = position; |
| 88 | + |
| 89 | + Error.captureStackTrace(this, caller || this.constructor); |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +/** |
| 94 | + * @template [R=JsonValue] |
| 95 | + * @callback ParseJsonFn |
| 96 | + * @param {string} raw text |
| 97 | + * @param {(this: EXPECTED_ANY, key: string, value: EXPECTED_ANY) => EXPECTED_ANY=} reviver reviver |
| 98 | + * @returns {R} parsed JSON |
| 99 | + */ |
| 100 | + |
| 101 | +/** @type {ParseJsonFn} */ |
| 102 | +const parseJson = (raw, reviver) => { |
| 103 | + const txt = stripBOM(raw); |
| 104 | + |
| 105 | + try { |
| 106 | + return JSON.parse(txt, reviver); |
| 107 | + } catch (err) { |
| 108 | + throw new JSONParseError(/** @type {Error} */ (err), raw, txt); |
| 109 | + } |
| 110 | +}; |
| 111 | + |
| 112 | +module.exports = parseJson; |
0 commit comments