|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const INDENT = Symbol.for('indent') |
| 4 | +const NEWLINE = Symbol.for('newline') |
| 5 | + |
| 6 | +const DEFAULT_NEWLINE = '\n' |
| 7 | +const DEFAULT_INDENT = ' ' |
| 8 | +const BOM = /^\uFEFF/ |
| 9 | + |
| 10 | +// only respect indentation if we got a line break, otherwise squash it |
| 11 | +// things other than objects and arrays aren't indented, so ignore those |
| 12 | +// Important: in both of these regexps, the $1 capture group is the newline |
| 13 | +// or undefined, and the $2 capture group is the indent, or undefined. |
| 14 | +const FORMAT = /^\s*[{[]((?:\r?\n)+)([\s\t]*)/ |
| 15 | +const EMPTY = /^(?:\{\}|\[\])((?:\r?\n)+)?$/ |
| 16 | + |
| 17 | +// Node 20 puts single quotes around the token and a comma after it |
| 18 | +const UNEXPECTED_TOKEN = /^Unexpected token '?(.)'?(,)? /i |
| 19 | + |
| 20 | +const hexify = (char) => { |
| 21 | + const h = char.charCodeAt(0).toString(16).toUpperCase() |
| 22 | + return `0x${h.length % 2 ? '0' : ''}${h}` |
| 23 | +} |
| 24 | + |
| 25 | +// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) |
| 26 | +// because the buffer-to-string conversion in `fs.readFileSync()` |
| 27 | +// translates it to FEFF, the UTF-16 BOM. |
| 28 | +const stripBOM = (txt) => String(txt).replace(BOM, '') |
| 29 | + |
| 30 | +const makeParsedError = (msg, parsing, position = 0) => ({ |
| 31 | + message: `${msg} while parsing ${parsing}`, |
| 32 | + position, |
| 33 | +}) |
| 34 | + |
| 35 | +const parseError = (e, txt, context = 20) => { |
| 36 | + let msg = e.message |
| 37 | + |
| 38 | + if (!txt) { |
| 39 | + return makeParsedError(msg, 'empty string') |
| 40 | + } |
| 41 | + |
| 42 | + const badTokenMatch = msg.match(UNEXPECTED_TOKEN) |
| 43 | + const badIndexMatch = msg.match(/ position\s+(\d+)/i) |
| 44 | + |
| 45 | + if (badTokenMatch) { |
| 46 | + msg = msg.replace( |
| 47 | + UNEXPECTED_TOKEN, |
| 48 | + `Unexpected token ${JSON.stringify(badTokenMatch[1])} (${hexify(badTokenMatch[1])})$2 ` |
| 49 | + ) |
| 50 | + } |
| 51 | + |
| 52 | + let errIdx |
| 53 | + if (badIndexMatch) { |
| 54 | + errIdx = +badIndexMatch[1] |
| 55 | + } else /* istanbul ignore next - doesnt happen in Node 22 */ if ( |
| 56 | + msg.match(/^Unexpected end of JSON.*/i) |
| 57 | + ) { |
| 58 | + errIdx = txt.length - 1 |
| 59 | + } |
| 60 | + |
| 61 | + if (errIdx == null) { |
| 62 | + return makeParsedError(msg, `'${txt.slice(0, context * 2)}'`) |
| 63 | + } |
| 64 | + |
| 65 | + const start = errIdx <= context ? 0 : errIdx - context |
| 66 | + const end = errIdx + context >= txt.length ? txt.length : errIdx + context |
| 67 | + const slice = `${start ? '...' : ''}${txt.slice(start, end)}${end === txt.length ? '' : '...'}` |
| 68 | + |
| 69 | + return makeParsedError( |
| 70 | + msg, |
| 71 | + `${txt === slice ? '' : 'near '}${JSON.stringify(slice)}`, |
| 72 | + errIdx |
| 73 | + ) |
| 74 | +} |
| 75 | + |
| 76 | +class JSONParseError extends SyntaxError { |
| 77 | + constructor (er, txt, context, caller) { |
| 78 | + const metadata = parseError(er, txt, context) |
| 79 | + super(metadata.message) |
| 80 | + Object.assign(this, metadata) |
| 81 | + this.code = 'EJSONPARSE' |
| 82 | + this.systemError = er |
| 83 | + Error.captureStackTrace(this, caller || this.constructor) |
| 84 | + } |
| 85 | + |
| 86 | + get name () { |
| 87 | + return this.constructor.name |
| 88 | + } |
| 89 | + |
| 90 | + set name (n) {} |
| 91 | + |
| 92 | + get [Symbol.toStringTag] () { |
| 93 | + return this.constructor.name |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +const parseJson = (txt, reviver) => { |
| 98 | + const result = JSON.parse(txt, reviver) |
| 99 | + if (result && typeof result === 'object') { |
| 100 | + // get the indentation so that we can save it back nicely |
| 101 | + // if the file starts with {" then we have an indent of '', ie, none |
| 102 | + // otherwise, pick the indentation of the next line after the first \n If the |
| 103 | + // pattern doesn't match, then it means no indentation. JSON.stringify ignores |
| 104 | + // symbols, so this is reasonably safe. if the string is '{}' or '[]', then |
| 105 | + // use the default 2-space indent. |
| 106 | + const match = txt.match(EMPTY) || txt.match(FORMAT) || [null, '', ''] |
| 107 | + result[NEWLINE] = match[1] ?? DEFAULT_NEWLINE |
| 108 | + result[INDENT] = match[2] ?? DEFAULT_INDENT |
| 109 | + } |
| 110 | + return result |
| 111 | +} |
| 112 | + |
| 113 | +const parseJsonError = (raw, reviver, context) => { |
| 114 | + const txt = stripBOM(raw) |
| 115 | + try { |
| 116 | + return parseJson(txt, reviver) |
| 117 | + } catch (e) { |
| 118 | + if (typeof raw !== 'string' && !Buffer.isBuffer(raw)) { |
| 119 | + const msg = Array.isArray(raw) && raw.length === 0 ? 'an empty array' : String(raw) |
| 120 | + throw Object.assign( |
| 121 | + new TypeError(`Cannot parse ${msg}`), |
| 122 | + { code: 'EJSONPARSE', systemError: e } |
| 123 | + ) |
| 124 | + } |
| 125 | + throw new JSONParseError(e, txt, context, parseJsonError) |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +module.exports = parseJsonError |
| 130 | +parseJsonError.JSONParseError = JSONParseError |
| 131 | +parseJsonError.noExceptions = (raw, reviver) => { |
| 132 | + try { |
| 133 | + return parseJson(stripBOM(raw), reviver) |
| 134 | + } catch { |
| 135 | + // no exceptions |
| 136 | + } |
| 137 | +} |
0 commit comments