(*--------------------------------------------------------------------------- Copyright (c) 2025 Anil Madhavapeddy . All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (** RFC 6901 JSON Pointer implementation for jsont. This module provides {{:https://www.rfc-editor.org/rfc/rfc6901}RFC 6901} JSON Pointer parsing, serialization, and evaluation compatible with {!Jsont} codecs. A JSON Pointer is a string syntax for identifying a specific value within a JSON document. For example, given the JSON document: {v { "foo": ["bar", "baz"], "": 0, "a/b": 1, "m~n": 2 } v} The following JSON Pointers evaluate to: {ul {- [""] - the whole document} {- ["/foo"] - the array [\["bar", "baz"\]]} {- ["/foo/0"] - the string ["bar"]} {- ["/"] - the integer [0] (empty string key)} {- ["/a~1b"] - the integer [1] ([~1] escapes [/])} {- ["/m~0n"] - the integer [2] ([~0] escapes [~])}} {1:tokens Reference Tokens} JSON Pointer uses escape sequences for special characters in reference tokens. The character [~] must be encoded as [~0] and [/] as [~1]. When unescaping, [~1] is processed before [~0] to correctly handle sequences like [~01] which should become [~1], not [/]. *) (** {1 Reference tokens} Reference tokens are the individual segments between [/] characters in a JSON Pointer string. They require escaping of [~] and [/]. *) module Token : sig type t = string (** The type for unescaped reference tokens. These are plain strings representing object member names or array index strings. *) val escape : t -> string (** [escape s] escapes special characters in [s] for use in a JSON Pointer. Specifically, [~] becomes [~0] and [/] becomes [~1]. *) val unescape : string -> t (** [unescape s] unescapes a JSON Pointer reference token. Specifically, [~1] becomes [/] and [~0] becomes [~]. @raise Jsont.Error if [s] contains invalid escape sequences (a [~] not followed by [0] or [1]). *) end (** {1 Indices} Indices represent individual navigation steps in a JSON Pointer. For objects, this is a member name. For arrays, this is either a numeric index or the special end-of-array marker [-]. *) module Index : sig type t = | Mem of string (** [Mem name] indexes into an object member with the given [name]. The name is unescaped (i.e., [/] and [~] appear literally). *) | Nth of int (** [Nth n] indexes into an array at position [n] (zero-based). Must be non-negative and without leading zeros in string form (except for [0] itself). *) | End (** [End] represents the [-] token, indicating the position after the last element of an array. This is used for append operations in {!Jsont_pointer.add} and similar mutation functions. Evaluating a pointer containing [End] with {!Jsont_pointer.get} will raise an error since it refers to a nonexistent element. *) val pp : Format.formatter -> t -> unit (** [pp] formats an index in JSON Pointer string notation. *) val equal : t -> t -> bool (** [equal i1 i2] is [true] iff [i1] and [i2] are the same index. *) val compare : t -> t -> int (** [compare i1 i2] is a total order on indices. *) (** {2:jsont_conv Conversion with Jsont.Path} *) val of_path_index : Jsont.Path.index -> t (** [of_path_index idx] converts a {!Jsont.Path.index} to an index. *) val to_path_index : t -> Jsont.Path.index option (** [to_path_index idx] converts to a {!Jsont.Path.index}. Returns [None] for {!End} since it has no equivalent in {!Jsont.Path}. *) end (** {1 Pointers} *) type t (** The type for JSON Pointers. A pointer is a sequence of {!Index.t} values representing a path from the root of a JSON document to a specific value. *) val root : t (** [root] is the empty pointer that references the whole document. In string form this is [""]. *) val is_root : t -> bool (** [is_root p] is [true] iff [p] is the {!root} pointer. *) val make : Index.t list -> t (** [make indices] creates a pointer from a list of indices. The list is ordered from root to target (i.e., the first element is the first step from the root). *) val indices : t -> Index.t list (** [indices p] returns the indices of [p] from root to target. *) val append : t -> Index.t -> t (** [append p idx] appends [idx] to the end of pointer [p]. *) val concat : t -> t -> t (** [concat p1 p2] appends all indices of [p2] to [p1]. *) val parent : t -> t option (** [parent p] returns the parent pointer of [p], or [None] if [p] is the {!root}. *) val last : t -> Index.t option (** [last p] returns the last index of [p], or [None] if [p] is the {!root}. *) (** {2:parsing Parsing} *) val of_string : string -> t (** [of_string s] parses a JSON Pointer from its string representation. The string must be either empty (representing the root) or start with [/]. Each segment between [/] characters is unescaped as a reference token. Segments that are valid non-negative integers without leading zeros become {!Index.Nth} indices; the string [-] becomes {!Index.End}; all others become {!Index.Mem}. @raise Jsont.Error if [s] has invalid syntax: - Non-empty string not starting with [/] - Invalid escape sequence ([~] not followed by [0] or [1]) - Array index with leading zeros - Array index that overflows [int] *) val of_string_result : string -> (t, string) result (** [of_string_result s] is like {!of_string} but returns a result instead of raising. *) val of_uri_fragment : string -> t (** [of_uri_fragment s] parses a JSON Pointer from URI fragment form. This is like {!of_string} but first percent-decodes the string according to {{:https://www.rfc-editor.org/rfc/rfc3986}RFC 3986}. The leading [#] should {b not} be included in [s]. @raise Jsont.Error on invalid syntax or invalid percent-encoding. *) val of_uri_fragment_result : string -> (t, string) result (** [of_uri_fragment_result s] is like {!of_uri_fragment} but returns a result instead of raising. *) (** {2:serializing Serializing} *) val to_string : t -> string (** [to_string p] serializes [p] to its JSON Pointer string representation. Returns [""] for the root pointer, otherwise [/] followed by escaped reference tokens joined by [/]. *) val to_uri_fragment : t -> string (** [to_uri_fragment p] serializes [p] to URI fragment form. This is like {!to_string} but additionally percent-encodes characters that are not allowed in URI fragments per RFC 3986. The leading [#] is {b not} included in the result. *) val pp : Format.formatter -> t -> unit (** [pp] formats a pointer using {!to_string}. *) (** {2:comparison Comparison} *) val equal : t -> t -> bool (** [equal p1 p2] is [true] iff [p1] and [p2] have the same indices. *) val compare : t -> t -> int (** [compare p1 p2] is a total order on pointers, comparing indices lexicographically. *) (** {2:jsont_path Conversion with Jsont.Path} *) val of_path : Jsont.Path.t -> t (** [of_path p] converts a {!Jsont.Path.t} to a JSON Pointer. *) val to_path : t -> Jsont.Path.t option (** [to_path p] converts to a {!Jsont.Path.t}. Returns [None] if [p] contains an {!Index.End} index. *) val to_path_exn : t -> Jsont.Path.t (** [to_path_exn p] is like {!to_path} but raises {!Jsont.Error} if conversion fails. *) (** {1 Evaluation} These functions evaluate a JSON Pointer against a {!Jsont.json} value to retrieve the referenced value. *) val get : t -> Jsont.json -> Jsont.json (** [get p json] retrieves the value at pointer [p] in [json]. @raise Jsont.Error if: - The pointer references a nonexistent object member - The pointer references an out-of-bounds array index - The pointer contains {!Index.End} (since [-] always refers to a nonexistent element) - An index type doesn't match the JSON value (e.g., {!Index.Nth} on an object) *) val get_result : t -> Jsont.json -> (Jsont.json, Jsont.Error.t) result (** [get_result p json] is like {!get} but returns a result. *) val find : t -> Jsont.json -> Jsont.json option (** [find p json] is like {!get} but returns [None] instead of raising when the pointer doesn't resolve to a value. *) (** {1 Mutation} These functions modify a {!Jsont.json} value at a location specified by a JSON Pointer. They are designed to support {{:https://www.rfc-editor.org/rfc/rfc6902}RFC 6902 JSON Patch} operations. All mutation functions return a new JSON value with the modification applied; they do not mutate the input. *) val set : t -> Jsont.json -> value:Jsont.json -> Jsont.json (** [set p json ~value] replaces the value at pointer [p] with [value]. For {!Index.End} on arrays, appends [value] to the end of the array. @raise Jsont.Error if the pointer doesn't resolve to an existing location (except for {!Index.End} on arrays). *) val add : t -> Jsont.json -> value:Jsont.json -> Jsont.json (** [add p json ~value] adds [value] at the location specified by [p]. The behavior depends on the target: {ul {- For objects: If the member exists, it is replaced. If it doesn't exist, a new member is added.} {- For arrays with {!Index.Nth}: Inserts [value] {e before} the specified index, shifting subsequent elements. The index must be valid (0 to length inclusive).} {- For arrays with {!Index.End}: Appends [value] to the array.}} @raise Jsont.Error if: - The parent of the target location doesn't exist - An array index is out of bounds (except for {!Index.End}) - The parent is not an object or array *) val remove : t -> Jsont.json -> Jsont.json (** [remove p json] removes the value at pointer [p]. For objects, removes the member. For arrays, removes the element and shifts subsequent elements. @raise Jsont.Error if: - [p] is the root (cannot remove the root) - The pointer doesn't resolve to an existing value - The pointer contains {!Index.End} *) val replace : t -> Jsont.json -> value:Jsont.json -> Jsont.json (** [replace p json ~value] replaces the value at pointer [p] with [value]. Unlike {!add}, this requires the target to exist. @raise Jsont.Error if: - The pointer doesn't resolve to an existing value - The pointer contains {!Index.End} *) val move : from:t -> path:t -> Jsont.json -> Jsont.json (** [move ~from ~path json] moves the value from [from] to [path]. This is equivalent to {!remove} at [from] followed by {!add} at [path] with the removed value. @raise Jsont.Error if: - [from] doesn't resolve to a value - [path] is a proper prefix of [from] (would create a cycle) - Either pointer contains {!Index.End} *) val copy : from:t -> path:t -> Jsont.json -> Jsont.json (** [copy ~from ~path json] copies the value from [from] to [path]. This is equivalent to {!get} at [from] followed by {!add} at [path] with the retrieved value. @raise Jsont.Error if: - [from] doesn't resolve to a value - Either pointer contains {!Index.End} *) val test : t -> Jsont.json -> expected:Jsont.json -> bool (** [test p json ~expected] tests if the value at [p] equals [expected]. Returns [true] if the values are equal according to {!Jsont.Json.equal}, [false] otherwise. Also returns [false] (rather than raising) if the pointer doesn't resolve. Note: This implements the semantics of the JSON Patch "test" operation. *) (** {1 Jsont Integration} These types and functions integrate JSON Pointers with the {!Jsont} codec system. *) val jsont : t Jsont.t (** [jsont] is a {!Jsont.t} codec for JSON Pointers. On decode, parses a JSON string as a JSON Pointer using {!of_string}. On encode, serializes a pointer to a JSON string using {!to_string}. *) val jsont_uri_fragment : t Jsont.t (** [jsont_uri_fragment] is like {!jsont} but uses URI fragment encoding. On decode, parses using {!of_uri_fragment}. On encode, serializes using {!to_uri_fragment}. *) (** {2:query Query combinators} These combinators integrate with jsont's query system, allowing JSON Pointers to be used with jsont codecs for typed access. *) val path : ?absent:'a -> t -> 'a Jsont.t -> 'a Jsont.t (** [path p t] decodes the value at pointer [p] using codec [t]. If [absent] is provided and the pointer doesn't resolve, returns [absent] instead of raising. This is similar to {!Jsont.path} but uses JSON Pointer syntax. *) val set_path : ?allow_absent:bool -> 'a Jsont.t -> t -> 'a -> Jsont.json Jsont.t (** [set_path t p v] sets the value at pointer [p] to [v] encoded with [t]. If [allow_absent] is [true] (default [false]), creates missing intermediate structure as needed. This is similar to {!Jsont.set_path} but uses JSON Pointer syntax. *) val update_path : ?absent:'a -> t -> 'a Jsont.t -> Jsont.json Jsont.t (** [update_path p t] recodes the value at pointer [p] with codec [t]. This is similar to {!Jsont.update_path} but uses JSON Pointer syntax. *) val delete_path : ?allow_absent:bool -> t -> Jsont.json Jsont.t (** [delete_path p] removes the value at pointer [p]. If [allow_absent] is [true] (default [false]), does nothing if the pointer doesn't resolve instead of raising. *)