From 4e00ffa7c781bb14b0de82356bb777e7030c408e Mon Sep 17 00:00:00 2001 From: mainnet-pat Date: Thu, 4 May 2023 20:02:34 +0000 Subject: [PATCH] Add extended parse function, compatible with Uint8Array and BigInt --- src/lib/format/log.ts | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/lib/format/log.ts b/src/lib/format/log.ts index 4a92ec56..01973075 100644 --- a/src/lib/format/log.ts +++ b/src/lib/format/log.ts @@ -1,4 +1,4 @@ -import { binToHex } from './hex.js'; +import { binToHex, hexToBin } from './hex.js'; const defaultStringifySpacing = 2; @@ -50,6 +50,35 @@ export const stringify = (value: any, spacing = defaultStringifySpacing) => spacing ); +/** + * An extended json parser compatible with `stringify` from libauth + * + * @remarks + * Currently supported extended types are Uint8Array and bigint + * + * @param json - json string to parse + * + * @returns {any} reconstructed entity serialized with `stringify` + */ +export const parse = (json: string): any => { + const uint8ArrayRegex = /^[0-9a-f]*)>$/u; + const bigIntRegex = /^[0-9]*)n>$/; + + return JSON.parse(json, (_key, value) => { + if (typeof value === "string") { + const bigintMatch = value.match(bigIntRegex); + if (bigintMatch) { + return BigInt(bigintMatch[1]!); + } + const uint8ArrayMatch = value.match(uint8ArrayRegex); + if (uint8ArrayMatch) { + return hexToBin(uint8ArrayMatch[1]!); + } + } + return value; + }); +} + /** * Given a value, recursively sort the keys of all objects it references * (without sorting arrays).