parseJson.js 3.1 KB

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