@nucypher/taco
Version:
### [`nucypher/taco-web`](../../README.md)
48 lines • 1.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromJSON = exports.toJSON = void 0;
const shared_1 = require("@nucypher/shared");
const customTypeReplacer = (_key, value) => {
if (value instanceof Uint8Array) {
// use hex string for byte arrays
return `0x${(0, shared_1.toHexString)(value)}`;
}
if (typeof value === 'bigint') {
if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER) {
// can't serialized to a safe number so use bigint string notation
return `${value}n`;
}
return Number(value);
}
return value;
};
const customTypeReceiver = (_key, value) => {
if (typeof value === 'string') {
if (/^-?\d+n$/.test(value)) {
// bigint number stored as string (`${value}n`)
return BigInt(value.slice(0, -1));
}
// NOTE: hex strings remain hex strings - could be an address (not bytes) or hex string (originally a byte array). Can't be sure which is which other than length (42) which feels flimsy
}
return value;
};
const sortedReplacer = (_key, value) => {
if (value instanceof Object && !(value instanceof Array)) {
return Object.keys(value)
.sort()
.reduce((sorted, key) => {
sorted[key] = value[key];
return sorted;
}, {});
}
return value;
};
const sortedSerializingReplacer = (_key, value) => {
const serializedValue = customTypeReplacer(_key, value);
return sortedReplacer(_key, serializedValue);
};
const toJSON = (obj) => JSON.stringify(obj, sortedSerializingReplacer);
exports.toJSON = toJSON;
const fromJSON = (json) => JSON.parse(json, customTypeReceiver);
exports.fromJSON = fromJSON;
//# sourceMappingURL=utils.js.map