UNPKG

@nucypher/taco

Version:

### [`nucypher/taco-web`](../../README.md)

43 lines 1.64 kB
import { toHexString } from '@nucypher/shared'; const customTypeReplacer = (_key, value) => { if (value instanceof Uint8Array) { // use hex string for byte arrays return `0x${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); }; export const toJSON = (obj) => JSON.stringify(obj, sortedSerializingReplacer); export const fromJSON = (json) => JSON.parse(json, customTypeReceiver); //# sourceMappingURL=utils.js.map