Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

json-patch-ts

npm install @ferrow/json-patch-ts

CI

RFC 6902 JSON Patch and RFC 6901 JSON Pointer: apply, generate, and validate patches with zero dependencies.

Strict TypeScript, zero runtime dependencies, immutable operations (structural sharing — untouched branches of the document are reused, not copied), and a runnable demo covering the RFC 6902 Appendix A examples plus pointer escaping and round-trip diffing.

Install

This is a standalone repo, not (yet) published to npm. Clone it and build, or copy src/ into your project:

git clone https://github.com/FerrowAI/json-patch-ts.git
cd json-patch-ts
npm install
npm run build   # emits dist/ (CommonJS + .d.ts)
npm run demo    # runs examples/demo.js against dist/

Quickstart

import { apply, generate, validatePatch, get } from "json-patch-ts";

const doc = { name: "Ada", tags: ["math"] };

// Apply a patch (RFC 6902). Returns a NEW document; `doc` is never mutated.
const patched = apply(doc, [
  { op: "add", path: "/tags/-", value: "computing" },
  { op: "replace", path: "/name", value: "Ada Lovelace" },
]);
// patched = { name: "Ada Lovelace", tags: ["math", "computing"] }

// Generate a patch between two documents.
const patch = generate(doc, patched);
// apply(doc, patch) deep-equals patched

// Validate patch structure before applying it.
const result = validatePatch(patch);
if (!result.valid) {
  console.error(result.errors); // [{ index, reason }, ...]
}

// Read a value by JSON Pointer (RFC 6901).
get(patched, "/tags/0"); // "math"

API

JSON Pointer (RFC 6901)

  • parsePointer(pointer: string): string[] — split a pointer into unescaped reference tokens ("" -> []).
  • compilePointer(tokens: string[]): string — join raw tokens into an escaped pointer string.
  • escapeToken(token: string): string / unescapeToken(token: string): string — apply/reverse the ~0/~1 escaping rules for a single token.
  • get(doc: unknown, pointer: string): unknown — resolve a pointer; throws JsonPointerError if it doesn't resolve.
  • exists(doc: unknown, pointer: string): boolean — like get, but returns false instead of throwing.
  • set(doc: unknown, pointer: string, value: unknown, mode?: "insert" | "overwrite"): unknown — return a new document with value written at pointer, without mutating doc. mode controls array target behavior: "insert" (default) shifts elements right (JSON Patch add semantics), "overwrite" replaces the element in place (JSON Patch replace semantics). Supports the array "-" append token.
  • remove(doc: unknown, pointer: string): unknown — return a new document with the value at pointer removed (array elements are spliced out).

JSON Patch (RFC 6902)

  • apply<T>(doc: T, patch: JsonPatchOp[]): T — apply a patch, returning a new document. Throws JsonPatchError (with .index and .op) on the first failing operation; the patch is applied atomically — if any op fails (including a test mismatch), no partial result escapes and doc itself was never mutated.
  • tryApply<T>(doc: T, patch: JsonPatchOp[]): { ok: true; doc: T } | { ok: false; error: JsonPatchError } — same as apply, without throwing.
  • Supported ops: add, remove, replace, move, copy, test — full RFC 6902 semantics, including array "-" append, move-into-own-child rejection, and atomic abort on a failing test.
  • JsonPatchError{ message, index, op }.

Generate

  • generate(a: unknown, b: unknown): JsonPatchOp[] — produce a patch such that apply(a, generate(a, b)) deep-equals b. See Limits below.

Validate

  • validatePatch(patch: unknown): { valid: true; errors: [] } | { valid: false; errors: { index: number; reason: string }[] } — structural validation only (well-formed ops, required members present, valid pointers). It does not check a patch against a target document — a structurally valid patch can still fail to apply (e.g. a replace on a path that doesn't exist).

Limits

  • generate() is index-based, not a true LCS/diff, for arrays. Elements are compared position-by-position. Appending or removing from the end of an array produces minimal add/remove ops; an insertion or deletion in the middle will generally produce a replace for every shifted element instead of a single add/remove. The output is always correct (apply(a, generate(a, b)) deep-equals b) but is not guaranteed minimal. If you need a minimal middle-of-array diff, diff with an LCS algorithm yourself and hand the result to apply directly — generate()'s contract is correctness, not minimality.
  • deepEqual (used internally by generate and the test op) treats undefined object values and missing keys as different from each other, matches JSON semantics (no support for Date, Map, Set, etc. — this library operates on plain JSON-compatible values only).
  • No streaming / no support for JSON Patch's optional application/json-patch+json content-type framing — this is a pure data-structure library, not an HTTP layer.

Testing

npm run build && npm run demo

examples/demo.js is a runnable smoke test (not a test-framework suite) that asserts RFC 6902 Appendix A cases, pointer escaping, atomic-abort-on-test-failure, move-into-own-child rejection, and generate() round-trips, exiting non-zero on any assertion failure.

License

MIT


Part of the ferrow-toolkit collection · Sponsored by Ferrow

About

RFC 6902 JSON Patch and RFC 6901 JSON Pointer: apply, generate, and validate patches with zero dependencies

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages