-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathlog.ts
More file actions
146 lines (139 loc) · 4.61 KB
/
log.ts
File metadata and controls
146 lines (139 loc) · 4.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import { binToHex, hexToBin } from './hex.js';
const defaultStringifySpacing = 2;
/**
* A safe method to `JSON.stringify` a value, useful for debugging and logging
* purposes.
*
* @remarks
* Without modifications, `JSON.stringify` has several shortcomings in
* debugging and logging usage:
* - throws when serializing anything containing a `bigint`
* - `Uint8Array`s are often encoded in base 10 with newlines between each
* index item
* - `functions` and `symbols` are not clearly marked
*
* This method is more helpful in these cases:
* - `bigint`: `0n` → `<bigint: 0n>`
* - `Uint8Array`: `Uint8Array.of(0,0)` → `<Uint8Array: 0x0000>`
* - `function`: `(x) => x * 2` → `<function: (x) => x * 2>`
* - `symbol`: `Symbol(A)` → `<symbol: Symbol(A)>`
*
* @param value - the data to stringify
* @param spacing - the number of spaces to use in
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const stringify = (value: any, spacing = defaultStringifySpacing) =>
JSON.stringify(
value,
// eslint-disable-next-line complexity
(_, item: unknown) => {
const type = typeof item;
const name =
typeof item === 'object' && item !== null
? item.constructor.name
: type;
switch (name) {
case 'Uint8Array':
return `<Uint8Array: 0x${binToHex(item as Uint8Array)}>`;
case 'bigint':
return `<bigint: ${(item as bigint).toString()}n>`;
case 'function':
case 'symbol':
// eslint-disable-next-line @typescript-eslint/ban-types
return `<${name}: ${(item as Function | symbol).toString()}>`;
default:
return item;
}
},
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).
*
* @param objectOrArray - the object or array in which to sort object keys
*/
export const sortObjectKeys = (
objectOrArray: unknown
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): any => {
if (Array.isArray(objectOrArray)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return objectOrArray.map(sortObjectKeys);
}
if (
typeof objectOrArray !== 'object' ||
objectOrArray === null ||
objectOrArray.constructor.name !== 'Object'
) {
return objectOrArray;
}
// eslint-disable-next-line functional/immutable-data
const keys = Object.keys(objectOrArray).sort((a, b) =>
a.localeCompare(b, 'en')
);
return keys.reduce(
(all, key) => ({
...all,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
[key]: sortObjectKeys((objectOrArray as { [key: string]: unknown })[key]),
}),
{}
);
};
const uint8ArrayRegex = /"<Uint8Array: 0x(?<hex>[0-9a-f]*)>"/gu;
const bigIntRegex = /"<bigint: (?<bigint>[0-9]*)n>"/gu;
/**
* An alternative to {@link stringify} that produces valid JavaScript for use
* as a test vector in this library. `Uint8Array`s are constructed using
* {@link hexToBin} and `bigint` values use the `BigInt` constructor. If
* `alphabetize` is `true`, all objects will be sorted in the output.
*
* Note, this assumes all strings that match the expected regular expressions
* are values of type `Uint8Array` and `bigint` respectively. String values
* that otherwise happen to match these regular expressions will be converted
* incorrectly.
*
* @param value - the value to stringify
* @param alphabetize - whether or not to alphabetize object keys, defaults
* to true
*/
export const stringifyTestVector = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any,
alphabetize = true
) => {
const stringified = alphabetize
? stringify(sortObjectKeys(value))
: stringify(value);
return stringified
.replace(uint8ArrayRegex, "hexToBin('$1')")
.replace(bigIntRegex, '$1n');
};