-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpointer.js
More file actions
36 lines (33 loc) · 874 Bytes
/
pointer.js
File metadata and controls
36 lines (33 loc) · 874 Bytes
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
/*
* Copyright 2026 Digital Bazaar, Inc.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
// JSON pointer escape sequences
// ~0 => '~'
// ~1 => '/'
const POINTER_ESCAPE_REGEX = /~[01]/g;
export function parsePointer(pointer) {
// see RFC 6901: https://www.rfc-editor.org/rfc/rfc6901.html
const parsed = [];
const paths = pointer.split('/').slice(1);
for(const path of paths) {
if(!path.includes('~')) {
// convert any numerical path to a number as an array index
const index = parseInt(path, 10);
parsed.push(isNaN(index) ? path : index);
} else {
parsed.push(path.replace(POINTER_ESCAPE_REGEX, _unescapePointerPath));
}
}
return parsed;
}
function _unescapePointerPath(m) {
if(m === '~1') {
return '/';
}
if(m === '~0') {
return '~';
}
throw new Error(`Invalid JSON pointer escape sequence "${m}".`);
}