Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add encodeExtendedJson and decodeExtendedJson with support for BigInts, TypesArrays, and Dates #108

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/lib/format/log.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { binToHex } from './hex.js';
import { binToHex, hexToBin } from './hex.js';

const defaultStringifySpacing = 2;

Expand Down Expand Up @@ -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 = /^<Uint8Array: 0x(?<hex>[0-9a-f]*)>$/u;
const bigIntRegex = /^<bigint: (?<bigint>[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).
Expand Down