-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
278 lines (244 loc) · 6.91 KB
/
index.js
File metadata and controls
278 lines (244 loc) · 6.91 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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
const delimiter = "\uFFFD" // eslint complains about the file appearing to be binary if the character is pasted in
const forbiddenRecordKeys = ["__proto__", "prototype"]
const unescapedColonRegex = /(?<!\\):/g
const unescapedDelimiterRegex = new RegExp(`(?<!\\\\)${delimiter}`, "g")
const escapedColonRegex = /\\:/g
const escapedDelimiterRegex = new RegExp(`\\\\${delimiter}`, "g")
const escapedForwardSlashAtEndRegex = /\\$/
/**
* If what's supplied is a Record and not null or an Array
* @template T
* @param {T} item
* @returns {T extends Record<any, any> ? true : false}
*/
function isObject(item) {
// @ts-expect-error true or false is a boolean
return (typeof item === "object" && !Array.isArray(item) && item !== null)
}
// encode
/**
* Transforms supported non Record and Array data types to a string to be appended to the encoding result
* @param {any} item
* @returns {string}
*/
function encodePrimitive(item) {
if (item === null) return "n" // nil
const t = typeof item
switch (t) {
case "bigint":
return `b${item}` // bigint
case "undefined":
return "v" // void
case "string":
return `"${item.replace(unescapedDelimiterRegex, `\\${delimiter}`).replace(escapedForwardSlashAtEndRegex, "")}` // strings
case "boolean":
return item ? "t" : "f" // booleans
case "number":
return String(item)
default:
throw new Error(`Don't know how to encode ${t}: ${require("util").inspect(item)}`)
}
}
/**
* Actually encodes items to their string formats
* @param {any} item
* @returns {string}
*/
function encodePush(item) {
let rt = ""
if (isObject(item)) rt += `{${encodeStep(item)}}` // obj
else if (Array.isArray(item)) {
// array
const mapped = item.map((i, ind, arr) => {
return isObject(i)
? `{${encodeStep(i)}}`
// [...null, 1000] => [...n�1000] Appends delimiter if isn't last element
: `${encodeStep(i)}${ind !== arr.length - 1 ? delimiter : ""}`
}).join("")
rt += `[${mapped}]`
} else rt += encodePrimitive(item)
return rt
}
/**
* @param {Record<string, any> | Array<any>} info
* @returns {string}
*/
function encodeStep(info) {
let rt = ""
if (!isObject(info)) rt += encodePush(info)
else {
const keys = Object.keys(info)
for (let index = 0; index < keys.length; index++) {
const key = keys[index]
if (forbiddenRecordKeys.includes(key)) continue
rt += `${key.replace(unescapedColonRegex, "\\:")}:`
// @ts-expect-error It will be an Object here
rt += encodePush(info[key])
// They have their own endings, so space can be saved
// @ts-expect-error It will be an Object here
if ((index !== keys.length - 1) && !isObject(info[key]) && !Array.isArray(info[key])) rt += delimiter
}
}
return rt
}
/**
* A method to encode custom data in a space efficient and supportive format similar to JSON-ish.
* Keys cannot be "\_\_proto\_\_" or "prototype"
* @param {Record<string, any> | Array<any>} info
* @returns {string}
*/
function encode(info) {
if (!info) return ""
if (!isObject(info) && !Array.isArray(info)) throw new Error("Cannot encode non Records or Arrays by themselves")
return encodeStep(info)
}
// decode
/**
* @param {string} text
* @param {number} openPos
* @param {"]" | "}"} expecting
* @returns {number}
*/
function findClosing(text, openPos, expecting) {
let closePos = openPos
let counter = 1
const opener = expecting === "]" ? "[" : "{"
while (counter > 0) {
if (text.length === closePos) throw new Error(`Unbalanced ${expecting}`)
const c = text[++closePos]
if (c === opener) counter++
else if (c === expecting) counter--
}
return closePos
}
/**
* @param {string} str
* @param {string} item
* @returns {number}
*/
function indexOfNextUnescapedItem(str, item) {
const index = str.indexOf(item)
if (index === -1) return -1
if (index === 0) return 1 + indexOfNextUnescapedItem(str.slice(1), item)
if (str[index - 1] === "\\") return index + indexOfNextUnescapedItem(str.slice(index + 1), item)
return index
}
/**
* Transforms supported encoded non Record and Array data types to their decoded types
* @param {string} val
* @returns {any}
*/
function decodePrimitive(val) {
let actualValue
switch (val[0]) {
case "t":
actualValue = true
break
case "f":
actualValue = false
break
case "v":
actualValue = void 0
break
case "n":
actualValue = null
break
case "b":
actualValue = BigInt(val.slice(1))
break
case "\"":
actualValue = val.slice(1).replace(escapedDelimiterRegex, delimiter)
break
default:
actualValue = Number(val)
break
}
return actualValue
}
/**
* @param {string} str
* @returns {any}
*/
function decodeStep(str) {
let rt = str.startsWith("[") ? [] : {}
let text = str
while (text.length) {
let key = ""
let ignore = false
if (isObject(rt)) {
const firstColon = indexOfNextUnescapedItem(text, ":")
key = text.slice(0, firstColon)
if (forbiddenRecordKeys.includes(key)) ignore = true
text = text.slice(firstColon + 1)
}
const nextDelimiter = indexOfNextUnescapedItem(text, delimiter)
const endToUse = nextDelimiter === -1 ? text.length : nextDelimiter
let actualValue
switch (text[0]) {
case "{": {
const closingIndex = findClosing(text, 0, "}")
if (!ignore) actualValue = decodeStep(text.slice(1, closingIndex))
text = text.slice(closingIndex + 1)
break
}
case "[": {
const closingIndex = findClosing(text, 0, "]")
let text2 = text.slice(1, closingIndex)
const holder = []
if (!ignore) {
while (text2.length) {
switch (text2[0]) {
case "{": {
const closingIndex2 = findClosing(text2, 0, "}")
const toPush = decodeStep(text2.slice(1, closingIndex2))
holder.push(toPush)
text2 = text2.slice(closingIndex2 + 1)
break
}
case "[": {
const closingIndex2 = findClosing(text2, 0, "]")
const toPush = decodeStep(text2.slice(0, closingIndex2 + 1))
holder.push(toPush)
text2 = text2.slice(closingIndex2 + 2) // will always be a delimiter after otherwise if end of string, will clamp to end
break
}
default: {
const nextDelimiter2 = indexOfNextUnescapedItem(text2, delimiter)
const endToUse2 = nextDelimiter2 === -1 ? text2.length : nextDelimiter2
const sliced = text2.slice(0, endToUse2)
const toPush = decodePrimitive(sliced)
holder.push(toPush)
text2 = text2.slice(endToUse2 + 1)
break
}
}
}
}
text = text.slice(closingIndex + 1)
if (Array.isArray(rt)) {
rt = holder
ignore = true
} else actualValue = holder
break
}
default:
actualValue = decodePrimitive(text.slice(0, endToUse))
text = text.slice(endToUse + 1)
break
}
if (ignore) continue
// @ts-expect-error It will be an Object here
if (isObject(rt)) rt[key.replace(escapedColonRegex, ":")] = actualValue
// @ts-expect-error It will be an Array here
else rt.push(actualValue)
}
return rt
}
/**
* @param {string} str
* @returns {any}
*/
function decode(str) {
return decodeStep(str)
}
module.exports = { encode, decode }