/
util.ts
377 lines (358 loc) · 10.1 KB
/
util.ts
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
import {
JsonStringPointer,
UriFragmentIdentifierPointer,
Pointer,
RelativeJsonPointer,
PathSegment,
PathSegments,
Decoder,
} from './types';
export function replace(source: string, find: string, repl: string): string {
let res = '';
let rem = source;
let beg = 0;
let end = -1;
while ((end = rem.indexOf(find)) > -1) {
res += source.substring(beg, beg + end) + repl;
rem = rem.substring(end + find.length, rem.length);
beg += end + find.length;
}
if (rem.length > 0) {
res += source.substring(source.length - rem.length, source.length);
}
return res;
}
export function decodeFragmentSegments(segments: PathSegments): PathSegments {
let i = -1;
const len = segments.length;
const res = new Array(len);
while (++i < len) {
if (typeof segments[i] === 'string') {
res[i] = replace(
replace(decodeURIComponent(segments[i] as string), '~1', '/'),
'~0',
'~',
);
} else {
res[i] = segments[i];
}
}
return res;
}
export function encodeFragmentSegments(segments: PathSegments): PathSegments {
let i = -1;
const len = segments.length;
const res = new Array(len);
while (++i < len) {
if (typeof segments[i] === 'string') {
res[i] = encodeURIComponent(
replace(replace(segments[i] as string, '~', '~0'), '/', '~1'),
);
} else {
res[i] = segments[i];
}
}
return res;
}
export function decodePointerSegments(segments: PathSegments): PathSegments {
let i = -1;
const len = segments.length;
const res = new Array(len);
while (++i < len) {
if (typeof segments[i] === 'string') {
res[i] = replace(replace(segments[i] as string, '~1', '/'), '~0', '~');
} else {
res[i] = segments[i];
}
}
return res;
}
export function encodePointerSegments(segments: PathSegments): PathSegments {
let i = -1;
const len = segments.length;
const res = new Array(len);
while (++i < len) {
if (typeof segments[i] === 'string') {
res[i] = replace(replace(segments[i] as string, '~', '~0'), '/', '~1');
} else {
res[i] = segments[i];
}
}
return res;
}
export function decodePointer(ptr: Pointer): PathSegments {
if (typeof ptr !== 'string') {
throw new TypeError(
'Invalid type: JSON Pointers are represented as strings.',
);
}
if (ptr.length === 0) {
return [];
}
if (ptr[0] !== '/') {
throw new ReferenceError(
'Invalid JSON Pointer syntax. Non-empty pointer must begin with a solidus `/`.',
);
}
return decodePointerSegments(ptr.substring(1).split('/'));
}
export function encodePointer(path: PathSegments): JsonStringPointer {
if (!path || (path && !Array.isArray(path))) {
throw new TypeError('Invalid type: path must be an array of segments.');
}
if (path.length === 0) {
return '';
}
return '/'.concat(encodePointerSegments(path).join('/'));
}
export function decodeUriFragmentIdentifier(
ptr: UriFragmentIdentifierPointer,
): PathSegments {
if (typeof ptr !== 'string') {
throw new TypeError(
'Invalid type: JSON Pointers are represented as strings.',
);
}
if (ptr.length === 0 || ptr[0] !== '#') {
throw new ReferenceError(
'Invalid JSON Pointer syntax; URI fragment identifiers must begin with a hash.',
);
}
if (ptr.length === 1) {
return [];
}
if (ptr[1] !== '/') {
throw new ReferenceError('Invalid JSON Pointer syntax.');
}
return decodeFragmentSegments(ptr.substring(2).split('/'));
}
export function encodeUriFragmentIdentifier(
path: PathSegments,
): UriFragmentIdentifierPointer {
if (!path || (path && !Array.isArray(path))) {
throw new TypeError('Invalid type: path must be an array of segments.');
}
if (path.length === 0) {
return '#';
}
return '#/'.concat(encodeFragmentSegments(path).join('/'));
}
const InvalidRelativePointerError =
'Invalid Relative JSON Pointer syntax. Relative pointer must begin with a non-negative integer, followed by either the number sign (#), or a JSON Pointer.';
export function decodeRelativePointer(ptr: RelativeJsonPointer): PathSegments {
if (typeof ptr !== 'string') {
throw new TypeError(
'Invalid type: Relative JSON Pointers are represented as strings.',
);
}
if (ptr.length === 0) {
// https://tools.ietf.org/id/draft-handrews-relative-json-pointer-00.html#rfc.section.3
throw new ReferenceError(InvalidRelativePointerError);
}
const segments = ptr.split('/');
let first = segments[0];
// It is a name reference; strip the hash.
if (first[first.length - 1] == '#') {
if (segments.length > 1) {
throw new ReferenceError(InvalidRelativePointerError);
}
first = first.substr(0, first.length - 1);
}
let i = -1;
const len = first.length;
while (++i < len) {
if (first[i] < '0' || first[i] > '9') {
throw new ReferenceError(InvalidRelativePointerError);
}
}
const path: unknown[] = decodePointerSegments(segments.slice(1));
path.unshift(segments[0]);
return path as PathSegments;
}
export function toArrayIndexReference(
arr: readonly unknown[],
idx: PathSegment,
): number {
if (typeof idx === 'number') return idx;
const len = idx.length;
if (!len) return -1;
let cursor = 0;
if (len === 1 && idx[0] === '-') {
if (!Array.isArray(arr)) {
return 0;
}
return arr.length;
}
while (++cursor < len) {
if (idx[cursor] < '0' || idx[cursor] > '9') {
return -1;
}
}
return parseInt(idx, 10);
}
export type Dereference = (it: unknown) => unknown;
export function compilePointerDereference(path: PathSegments): Dereference {
let body = "if (typeof(it) !== 'undefined'";
if (path.length === 0) {
return (it): unknown => it;
}
body = path.reduce((body, _, i) => {
return (
body +
"\n\t&& it !== null && typeof((it = it['" +
replace(replace(path[i] + '', '\\', '\\\\'), "'", "\\'") +
"'])) !== 'undefined'"
);
}, "if (typeof(it) !== 'undefined'") as string;
body = body + ') {\n\treturn it;\n }';
// eslint-disable-next-line no-new-func
return new Function('it', body) as Dereference;
}
export function setValueAtPath(
target: unknown,
val: unknown,
path: PathSegments,
force = false,
): unknown {
if (path.length === 0) {
throw new Error('Cannot set the root object; assign it directly.');
}
if (typeof target === 'undefined') {
throw new TypeError('Cannot set values on undefined');
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let it: any = target;
const len = path.length;
const end = path.length - 1;
let step: PathSegment;
let cursor = -1;
let rem: unknown;
let p: number;
while (++cursor < len) {
step = path[cursor];
if (typeof step !== 'string' && typeof step !== 'number') {
throw new TypeError('PathSegments must be a string or a number.');
}
if (
// Reconsider this strategy. It disallows legitimate structures on
// non - objects, or more precisely, on objects not derived from a class
// or constructor function.
step === '__proto__' ||
step === 'constructor' ||
step === 'prototype'
) {
throw new Error('Attempted prototype pollution disallowed.');
}
if (Array.isArray(it)) {
if (step === '-' && cursor === end) {
it.push(val);
return undefined;
}
p = toArrayIndexReference(it, step);
if (it.length > p) {
if (cursor === end) {
rem = it[p];
it[p] = val;
break;
}
it = it[p];
} else if (cursor === end && p === it.length) {
if (force) {
it.push(val);
return undefined;
}
} else if (force) {
it = it[p] = cursor === end ? val : {};
}
} else {
if (typeof it[step] === 'undefined') {
if (force) {
if (cursor === end) {
it[step] = val;
return undefined;
}
// if the next step is an array index, this step should be an array.
const n = Number(path[cursor + 1]);
if (
Number.isInteger(n) &&
toArrayIndexReference(it[step], n) !== -1
) {
it = it[step] = [];
continue;
}
it = it[step] = {};
continue;
}
return undefined;
}
if (cursor === end) {
rem = it[step];
it[step] = val;
break;
}
it = it[step];
}
}
return rem;
}
export function unsetValueAtPath(target: unknown, path: PathSegments): unknown {
if (path.length === 0) {
throw new Error('Cannot unset the root object; assign it directly.');
}
if (typeof target === 'undefined') {
throw new TypeError('Cannot unset values on undefined');
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let it: any = target;
const len = path.length;
const end = path.length - 1;
let step: PathSegment;
let cursor = -1;
let rem: unknown;
let p: number;
while (++cursor < len) {
step = path[cursor];
if (typeof step !== 'string' && typeof step !== 'number') {
throw new TypeError('PathSegments must be a string or a number.');
}
if (
step === '__proto__' ||
step === 'constructor' ||
step === 'prototype'
) {
throw new Error('Attempted prototype pollution disallowed.');
}
if (Array.isArray(it)) {
p = toArrayIndexReference(it, step);
if (p >= it.length) return undefined;
if (cursor === end) {
rem = it[p];
delete it[p];
break;
}
it = it[p];
} else {
if (typeof it[step] === 'undefined') {
return undefined;
}
if (cursor === end) {
rem = it[step];
delete it[step];
break;
}
it = it[step];
}
}
return rem;
}
export function looksLikeFragment(ptr: Pointer): boolean {
return typeof ptr === 'string' && ptr.length > 0 && ptr[0] === '#';
}
export function pickDecoder(ptr: Pointer): Decoder {
return looksLikeFragment(ptr) ? decodeUriFragmentIdentifier : decodePointer;
}
export function decodePtrInit(ptr: Pointer | PathSegments): PathSegments {
return Array.isArray(ptr)
? ptr.slice(0)
: pickDecoder(ptr as Pointer)(ptr as Pointer);
}