Skip to content

Commit

Permalink
Fix safe json stringify code
Browse files Browse the repository at this point in the history
  • Loading branch information
hansottowirtz committed Dec 31, 2022
1 parent 725761b commit 0499a2b
Showing 1 changed file with 57 additions and 21 deletions.
78 changes: 57 additions & 21 deletions src/setup-page.ts
Expand Up @@ -63,33 +63,69 @@ export const setupPage = async (page: Page) => {
const red = (message) => \`\\u001b[31m\${message}\\u001b[39m\`;
const yellow = (message) => \`\\u001b[33m\${message}\\u001b[39m\`;
// removes circular references from the object
function serializer(replacer, cycleReplacer) {
let stack = [],
keys = [];
if (cycleReplacer == null)
cycleReplacer = function (_key, value) {
if (stack[0] === value) return '[Circular]';
return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';
};
// Safe JSON.stringify, from https://github.com/debitoor/safe-json-stringify/blob/master/index.js
const hasProp = Object.prototype.hasOwnProperty;
function throwsMessage(err) {
return '[Throws: ' + (err ? err.message : '?') + ']';
}
return function (key, value) {
if (stack.length > 0) {
let thisPos = stack.indexOf(this);
~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value);
} else {
stack.push(value);
function safeGetValueFromPropertyOnObject(obj, property) {
if (hasProp.call(obj, property)) {
try {
return obj[property];
}
catch (err) {
return throwsMessage(err);
}
}
return replacer == null ? value : replacer.call(this, key, value);
return obj[property];
}
function ensureProperties(obj) {
var seen = [ ]; // store references to objects we have seen before
function visit(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (seen.indexOf(obj) !== -1) {
return '[Circular]';
}
seen.push(obj);
if (typeof obj.toJSON === 'function') {
try {
var fResult = visit(obj.toJSON());
seen.pop();
return fResult;
} catch(err) {
return throwsMessage(err);
}
}
if (Array.isArray(obj)) {
var aResult = obj.map(visit);
seen.pop();
return aResult;
}
var result = Object.keys(obj).reduce(function(result, prop) {
// prevent faulty defined getter properties
result[prop] = visit(safeGetValueFromPropertyOnObject(obj, prop));
return result;
}, {});
seen.pop();
return result;
};
return visit(obj);
}
function safeStringify(obj, replacer, spaces, cycleReplacer) {
return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces);
function safeStringify(obj, replacer, space) {
return JSON.stringify(ensureProperties(data), replacer, space);
}
function composeMessage(args) {
Expand Down

0 comments on commit 0499a2b

Please sign in to comment.