@m6d/cortex-cli 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,6 +21,50 @@ export function escapePointerToken(token: string) {
21
21
  return token.replaceAll("~", "~0").replaceAll("/", "~1");
22
22
  }
23
23
 
24
- export function unescapePointerToken(token: string) {
24
+ function unescapePointerToken(token: string) {
25
25
  return token.replaceAll("~1", "/").replaceAll("~0", "~");
26
26
  }
27
+
28
+ /**
29
+ * The reference tokens of a JSON Pointer, bare (`/a/b`) or as a URI fragment (`#/a/b`, which
30
+ * is percent-decoded before it splits, as RFC 6901 section 6 has it); `[]` names the whole
31
+ * document. Undefined for text that is neither, or a fragment whose percent-encoding is
32
+ * malformed.
33
+ */
34
+ export function pointerTokens(pointer: string) {
35
+ let path = pointer;
36
+ if (pointer.startsWith("#")) {
37
+ try {
38
+ path = decodeURIComponent(pointer.slice(1));
39
+ } catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ if (path === "") return [];
44
+ if (!path.startsWith("/")) return undefined;
45
+ return path.slice(1).split("/").map(unescapePointerToken);
46
+ }
47
+
48
+ /** A JSON Pointer token that names an array index: digits with no leading zero. */
49
+ export const ARRAY_INDEX = /^(?:0|[1-9]\d*)$/;
50
+
51
+ /** A number spelled as JSON writes one: decimal, in ASCII digits so every regex engine reads the pattern alike. */
52
+ export const JSON_NUMBER_PATTERN = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$/;
53
+
54
+ /**
55
+ * The value one reference token names under `container`: an own key of an object, or an
56
+ * `ARRAY_INDEX` of an array; undefined when there is none, so an inherited key such as
57
+ * `constructor` never resolves.
58
+ */
59
+ export function pointerChild(container: unknown, token: string) {
60
+ if (Array.isArray(container)) {
61
+ const items: unknown[] = container;
62
+ return ARRAY_INDEX.test(token) ? items[Number(token)] : undefined;
63
+ }
64
+ return isRecord(container) && Object.hasOwn(container, token) ? container[token] : undefined;
65
+ }
66
+
67
+ /** The value a JSON Pointer names in `document`, one `pointerChild` per token; undefined when it names nothing. */
68
+ export function readJsonPointer(document: unknown, pointer: string) {
69
+ return pointerTokens(pointer)?.reduce<unknown>(pointerChild, document);
70
+ }