@stryke/json
Version:
A package containing JSON parsing/stringify utilities used by Storm Software.
59 lines (58 loc) • 1.77 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parse = parse;
exports.safeParse = safeParse;
var _stripComments = require("./strip-comments.cjs");
const o = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,
u = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,
i = /^\s*["[{]|^\s*-?\d{1,16}(?:\.\d{1,17})?(?:E[+-]?\d+)?\s*$/i;
function c(t, n) {
if (t === "__proto__" || t === "constructor" && n && typeof n == "object" && "prototype" in n) {
console.warn(`Dropping "${t}" key to prevent prototype pollution.`);
return;
}
return n;
}
function parse(t, n = {}) {
if (typeof t != "string") return t;
let r = (0, _stripComments.stripComments)(t);
if (r[0] === '"' && r[r.length - 1] === '"' && !r.includes("\\")) return r.slice(1, -1);
if (r = r.trim(), r.length <= 9) switch (r.toLowerCase()) {
case "true":
return !0;
case "false":
return !1;
case "undefined":
return;
case "null":
return null;
case "nan":
return Number.NaN;
case "infinity":
return Number.POSITIVE_INFINITY;
case "-infinity":
return Number.NEGATIVE_INFINITY;
}
if (!i.test(r)) {
if (n.strict) throw new Error("Invalid JSON");
return r;
}
try {
if (o.test(r) || u.test(r)) {
if (n.strict) throw new Error("Possible prototype pollution");
return JSON.parse(r, c);
}
return JSON.parse(r);
} catch (e) {
if (n.strict) throw e;
return t;
}
}
function safeParse(t, n = {}) {
return parse(t, {
...n,
strict: !0
});
}