Code Monkey home page Code Monkey logo

patch's Introduction

IMPORTANT

This package moved to a monorepo. https://github.com/sonnyp/JSON8/tree/master/packages/patch


JSON8 Patch

build status

JSON Patch RFC 6902 (and diff) implementation for JavaScript.

See jsonpatch.com for more information about JSON Patch.

JSON8 Patch passes the entire json-patch-tests suite; see Tests

Comparison

module root0 atomic1 mutates2
json8-patch
jsonpatch
jiff
json-patch
fast-json-patch ☑  

Getting started

npm install json8-patch


var ooPatch = require('json8-patch');

or

<script src="node_modules/json8-patch/JSON8Patch.js"></script>
var ooPatch = window.JSON8Patch

For performance concerns JSON8 Patch may mutate target document; if you want it to use its own copy use:

var oo = require('json8')
var myDocument = {foo: 'bar'}
var doc = oo.clone(myDocument)

See clone.

JSON8 Patch never mutates patches.

Methods

apply

demo/playground

doc = ooPatch.apply(doc, patch).doc;

ooPatch.apply (and other ooPatch methods) returns an object with a doc property because per specification a patch can replace the original root document.

The operation is atomic, if any of the patch operation fails, the document will be restored to its original state and an error will be thrown.

patch

Alias for apply method.

revert

If the patch or apply method is called with a third argument {reversible: true} it will return an additional value in the form of a revert property.

The revert object can be used to revert a patch on a document.

// apply the patch with the reversible option
var applyResult = ooPatch.apply(doc, patch, {reversible: true});
doc = applyResult.doc

// revert the patch
doc = ooPatch.revert(doc, applyResult.revert).doc;
// doc is strictly identical to the original

See also buildRevertPatch which offers more flexibility.

buildRevertPatch

demo/playground

Builds a valid JSON Patch from the result of a reversible apply operation. You can then use this patch with apply method to revert a previously applied patch.

// apply the patch
var applyResult = ooPatch.apply(doc, patch, {reversible: true});
doc = applyResult.doc

// revert the patch
var revertPatch = ooPatch.buildRevertPatch(applyResult.revert) // this is a valid JSON Patch
doc = ooPatch.apply(doc, revertPatch).doc
// doc is strictly identical to the original

Because buildRevertPatch + apply offers more flexibility over revert it is preferred.

  • use pack/unpack with the result of buildRevertPatch making it ideal for storage or transport
  • reverse a revert (and so on...) with {reversible: true}
  • diff between reverts
  • merge multiple reverts into one
  • rebase reverts

diff

demo/playground

Returns a diff in the form of a JSON Patch for 2 JSON values.

ooPatch.diff(true, false)
// [{"op": "replace", "path": "", "value": "false"}]

ooPatch.diff([], [])
// []

ooPatch.diff({}, {"foo": "bar"})
// [{"op": "add", "path": "/foo", "value": "bar"}]

valid

Returns true if the patch is valid, false otherwise.

This method only check for JSON Patch semantic. If you need to verify the patch is JSON valid, use oo.valid

ooPatch.valid({})  // false
ooPatch.valid([{}] // false
ooPatch.valid([{op: "foo", path: null, value: undefined}]) // false
ooPatch.valid([{op: "add", path: "/foo"}]) // false

ooPatch.valid([]) // true
ooPatch.valid([{op: "add", path: "/foo", value: "bar"}]) // true

concat

Concats multiple patches into one.

var patch1 = [{op: "add", value: "bar", path: "/foo"}]
var patch2 = [{op: "remove", path: "/foo"}]
var patch = ooPatch.concat(patch1, patch2)

// patch is
[
  {op: "add", value: "bar", path: "/foo"},
  {op: "remove", path: "/foo"}
]

Operations

add, copy, replace, move, remove, test operations return an object of the form {doc: document, previous: value}

  • doc is the patched document
  • previous is the previous/replaced value

add

doc = ooPatch.add(doc, '/foo', 'foo').doc;

remove

doc = ooPatch.remove(doc, '/foo').doc;

replace

doc = ooPatch.replace(doc, '/foo', 'foo').doc;

move

doc = ooPatch.move(doc, '/foo', '/bar').doc;

copy

doc = ooPatch.copy(doc, '/foo', '/bar').doc;

test

doc = ooPatch.test(doc, '/foo', 'bar').doc;

Extra operations

Those are not part of the standard and are only provided for convenience.

get

ooPatch.get(doc, '/foo');
// returns value at /foo

has

ooPatch.has(doc, '/foo');
// returns true if there is a value at /foo

Patch size

Per specification patches are pretty verbose. JSON8 provides pack and unpack methods to reduce the size of patches and save memory/space/bandwidth.

Size (in bytes) comparaison for the following patch file

[
  {"op": "add", "path": "/a/b/c", "value": ["foo", "bar"]},
  {"op": "remove", "path": "/a/b/c"},
  {"op": "replace", "path": "/a/b/c", "value": 42},
  {"op": "move", "from": "/a/b/c", "path": "/a/b/d"},
  {"op": "copy", "from": "/a/b/c", "path": "/a/b/e"},
  {"op": "test", "path": "/a/b/c", "value": "foo"}
]
format size (in bytes)
unpacked 313
unpacked gzip 148
packed 151
packed gzip 99

In pratice I'd recommand to use pack/unpack if

  • data compression cannot be used on the transport of the patch
  • keeping a large amount of patches in memory/on disk

pack

demo/playground

var patch = [
  {"op": "add", "path": "/a/b/c", "value": ["foo", "bar"]},
  {"op": "remove", "path": "/a/b/c"},
  {"op": "replace", "path": "/a/b/c", "value": 42},
  {"op": "move", "from": "/a/b/c", "path": "/a/b/d"},
  {"op": "copy", "from": "/a/b/c", "path": "/a/b/e"},
  {"op": "test", "path": "/a/b/c", "value": "foo"}
];

var packed = ooPatch.pack(patch);

Here is what packed looks like

[
  [0, "/a/b/c", ["foo", "bar"]],
  [1, "/a/b/c"],
  [2, "/a/b/c", 42],
  [3, "/a/b/d", "/a/b/c"],
  [4, "/a/b/e", "/a/b/c"],
  [5, "/a/b/c", "foo"],
]

unpack

demo/playground

var patch = ooPatch.unpack(packed);
// [{...}, {...}, ...]

Tests

npm install mocha browserify
npm test

Contributing

See CONTRIBUTING.md

Footnotes
root

Refers to the library ability to replace/remove root (/) on your target.

Lack of this ability makes the library unable to comply with the specification and will result in unknown/inconsistent states for your target documents.

[
  {"op": "replace", "path": "/", "value": "{}"},
  {"op": "remove", "path": "/"}
]
atomic

Refers to the library ability to revert successful patch operations after a failure on the mutated target.

Lack of this ability makes the library unable to comply with the specification and will result in unknown/inconsistent states for your target documents.

https://tools.ietf.org/html/rfc6902#section-5

mutates

Refers to the ability of the library to mutates the target document.

It is best to choose a library which mutate the target document because it leaves you with the choice of creating a shallow copy first.

patch's People

Contributors

sonnyp avatar rosshadden avatar

Stargazers

 avatar momo avatar  avatar Vedanta-krit das (Alex Vedmedenko) avatar Fazil Uruniyengal avatar Andrii Davydov avatar Rajab Natshah avatar crapthings avatar Ryota Arai avatar Félix Girault avatar Solzimer avatar Johan Forsberg avatar Pascal Tbf avatar Nick avatar  avatar Jussi Holm avatar Sibelius Seraphini avatar Sunny Hirai avatar Michael Ball avatar Bastian Kistner avatar

Watchers

 avatar Sunny Hirai avatar James Cloos avatar Rajab Natshah avatar

patch's Issues

Stops working when latest versions of json8-patch and json8-pointer are both installed

I don't know if this has happened to anybody else, but on my Angular 5 project, I ran npm install in a new clone of my project, and it installed [email protected] and [email protected], json8-patch stopped working, at least for .add() and .apply() operations.

At first it gave walk is not a function errors in add.js, because walk(), which is imported from json8-pointer, was not exported in the [email protected] index.js file. After I fixed that, however, it still didn't work, because apparently the walk function has been changed to use the import @fuba/walk in [email protected], and that walk function works differently than the built-in walk function that existed in [email protected]. And apparently if you have both json8-patch and json8-pointer installed in your project, json8-patch will use the already-installed json8-pointer instead of its own "json8-pointer": "^0.5.0" dependency.

Support packing/unpacking during diff/apply

This library is probably one of the only json patch implementations that has a serializer that can pack/unpack operations to reduce the size/verbosity of the implementation. My recommendation is to allow a user to do that at the same time, so there is no performance penalty during the initial diff or apply.

patch.diff(obj1, obj2, true) for packing while diffing.

Can't a {reversible: true} revert just be a patch?

When you call apply with {reversible: true} it returns an object that is different than a patch.

var patchResult = ooPatch.apply(doc, patch, {reversible: true};
patchResult.revert // this does not return a patch object but a custom revert object

I'm worried about the semantics of the patchResult being something other than a patch. Couldn't this just be a normal patch?

I was working on something similar and I was returning patches for reversibles. Is there any reason why patchResult.revert doesn't just return a patch? Is this a design decision?

Revertible Patches

Overview

Create a Revertible Patch Format.

Create a non-standard revertible patch format that you can extract standard forward and revert patches from.

Details

One of the things I really like about JSON8 is its support for compression that expands to the standard patch format. The encoding could even be used with other JSON patch libraries.

The addition of the revert as standard diff (from sonnyp assuming its accepted) also follows the format of sticking to the standard and building on it rather than doing an augmented version of the standard.

Other diff libraries are also having issues with revert because it goes off of the standard in some ways (e.g. a diff by itself doesn't have enough information to generate a revert) so some are contemplating going off standard or asking for the standard to be changed.

My suggestion is to basically create a "JSON patch with revert format".

The alternative (which is my current plan) is that I create a PatchSet that includes both the forward diff and the revert diff in it. Of course, it is much larger than it needs to be since there is redundant information but it does solve the problem.

With the "JSON patch with revert format", a delete operation would result in a data structure that includes enough information to do the revert add operation.

We would call a method on this RevertiblePatch object to get back either a forward diff or a revert diff.

var forwardPatch = ooPatch.getPatch(revertiblePatch);
var revertPatch = ooPatch.getRevert(revertiblePatch);

I believe this is a good format because you ultimately end up with JSON objects that comply with the standard.

Browser support

Does this solution work in the browser? I don't see a bower package for it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.