github-pages-deploy-action/node_modules/parse-json/index.js

51 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-03-07 11:45:40 +08:00
'use strict';
2020-03-31 20:57:48 +08:00
const errorEx = require('error-ex');
const fallback = require('json-parse-better-errors');
const {default: LinesAndColumns} = require('lines-and-columns');
const {codeFrameColumns} = require('@babel/code-frame');
2020-03-07 11:45:40 +08:00
2020-03-31 20:57:48 +08:00
const JSONError = errorEx('JSONError', {
fileName: errorEx.append('in %s'),
codeFrame: errorEx.append('\n\n%s\n')
2020-03-07 11:45:40 +08:00
});
2020-03-31 20:57:48 +08:00
module.exports = (string, reviver, filename) => {
2020-03-07 11:45:40 +08:00
if (typeof reviver === 'string') {
filename = reviver;
reviver = null;
}
try {
try {
2020-03-31 20:57:48 +08:00
return JSON.parse(string, reviver);
} catch (error) {
fallback(string, reviver);
throw error;
2020-03-07 11:45:40 +08:00
}
2020-03-31 20:57:48 +08:00
} catch (error) {
error.message = error.message.replace(/\n/g, '');
const indexMatch = error.message.match(/in JSON at position (\d+) while parsing near/);
2020-03-07 11:45:40 +08:00
2020-03-31 20:57:48 +08:00
const jsonError = new JSONError(error);
2020-03-07 11:45:40 +08:00
if (filename) {
2020-03-31 20:57:48 +08:00
jsonError.fileName = filename;
2020-03-07 11:45:40 +08:00
}
2020-03-31 20:57:48 +08:00
if (indexMatch && indexMatch.length > 0) {
const lines = new LinesAndColumns(string);
const index = Number(indexMatch[1]);
const location = lines.locationForIndex(index);
const codeFrame = codeFrameColumns(
string,
{start: {line: location.line + 1, column: location.column + 1}},
{highlightCode: true}
);
jsonError.codeFrame = codeFrame;
}
throw jsonError;
2020-03-07 11:45:40 +08:00
}
};