-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonpatch.js
501 lines (474 loc) · 15.6 KB
/
jsonpatch.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/* @preserve
* JSONPatch.js
*
* A Dharmafly project written by Thomas Parslow
* <[email protected]> and released with the kind permission of
* NetDev.
*
* Copyright 2011-2013 Thomas Parslow. All rights reserved.
* Permission is hereby granted,y free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Implements the JSON Patch IETF RFC 6902 as specified at:
*
* http://tools.ietf.org/html/rfc6902
*
* Also implements the JSON Pointer IETF RFC 6901 as specified at:
*
* http://tools.ietf.org/html/rfc6901
*
*/
/* @preserve
* KAWA modifications
*
* Modifications have been made to add non-value "exists" test operations
* in accordance to the way the game "Starbound" handles patches.
* These changes are based off of the work of Kawa:
*
* https://helmet.kafuka.org/sbmods/json/
*/
(function (root, factory) {
if (typeof exports === 'object') {
// Node
factory(module.exports);
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports'], factory);
} else {
// Browser globals (root is window)
root.jsonpatch = {};
root.returnExports = factory(root.jsonpatch);
}
}(this, function (exports) {
var apply_patch, JSONPatch, JSONPointer,_operationRequired,isArray;
// Taken from underscore.js
isArray = Array.isArray || function(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
};
/* Public: Shortcut to apply a patch the document without having to
* create a patch object first. Returns the patched document. Does
* not damage the original document, but will reuse parts of its
* structure in the new one.
*
* doc - The target document to which the patch should be applied.
* patch - A JSON Patch document specifying the changes to the
* target documentment
*
* Returns the patched document
*/
exports.apply_patch = apply_patch = function (doc, patch) {
return (new JSONPatch(patch)).apply(doc);
};
/* Public: Error thrown if the patch supplied is invalid.
*/
function InvalidPatch(message) {
Error.call(this, message); this.message = message;
}
exports.InvalidPatch = InvalidPatch;
InvalidPatch.prototype = new Error();
/* Public: Error thrown if the patch can not be apllied to the given document
*/
function PatchApplyError(message) {
Error.call(this, message); this.message = message;
}
exports.PatchApplyError = PatchApplyError;
PatchApplyError.prototype = new Error();
/* Public: A class representing a JSON Pointer. A JSON Pointer is
* used to point to a specific sub-item within a JSON document.
*
*/
exports.JSONPointer = JSONPointer = function JSONPointer (pathStr) {
var i,split,path=[];
// Split up the path
split = pathStr.split('/');
if ('' !== split[0]) {
throw new InvalidPatch('JSONPointer must start with a slash (or be an empty string)!');
}
for (i = 1; i < split.length; i++) {
path[i-1] = split[i].replace(/~1/g,'/').replace(/~0/g,'~');
}
this.path = path;
this.length = path.length;
};
/* Private: Get a segment of the pointer given a current doc
* context.
*/
JSONPointer.prototype._get_segment = function (index, node) {
var segment = this.path[index];
if(isArray(node)) {
if ('-' === segment) {
segment = node.length;
} else {
// Must be a non-negative integer in base-10 without leading zeros
if (!segment.match(/^0$|^[1-9][0-9]*$/)) {
throw new PatchApplyError('Expected a number to segment an array');
}
segment = parseInt(segment,10);
}
}
return segment;
};
// Return a shallow copy of an object
function clone(o) {
var cloned, key;
if (isArray(o)) {
return o.slice();
// typeof null is "object", but we want to copy it as null
} if (o === null) {
return o;
} else if (typeof o === "object") {
cloned = {};
for(key in o) {
if (Object.hasOwnProperty.call(o, key)) {
cloned[key] = o[key];
}
}
return cloned;
} else {
return o;
}
}
/* Private: Follow the pointer to its penultimate segment then call
* the handler with the current doc and the last key (converted to
* an int if the current doc is an array). The handler is expected to
* return a new copy of the penultimate part.
*
* doc - The document to search within
* handler - The callback function to handle the last part
*
* Returns the result of calling the handler
*/
JSONPointer.prototype._action = function (doc, handler, mutate) {
var that = this;
function follow_pointer(node, index) {
var segment, subnode;
if (!mutate) {
node = clone(node);
}
segment = that._get_segment(index, node);
// Is this the last segment?
if (index == that.path.length-1) {
node = handler(node, segment);
} else {
// Make sure we can follow the segment
if (isArray(node)) {
if (node.length <= segment) {
throw new PatchApplyError('Path not found in document');
}
} else if (typeof node === "object") {
if (!Object.hasOwnProperty.call(node, segment)) {
throw new PatchApplyError('Path not found in document');
}
} else {
throw new PatchApplyError('Path not found in document');
}
subnode = follow_pointer(node[segment], index+1);
if (!mutate) {
node[segment] = subnode;
}
}
return node;
}
return follow_pointer(doc, 0);
};
/* Public: Takes a JSON document and a value and adds the value into
* the doc at the position pointed to. If the position pointed to is
* in an array then the existing element at that position (if any)
* and all that follow it have their position incremented to make
* room. It is an error to add to a parent object that doesn't exist
* or to try to replace an existing value in an object.
*
* doc - The document to operate against. Will be mutated so should
* not be reused after the call.
* value - The value to insert at the position pointed to
*
* Returns the updated doc (the value passed in may also have been mutated)
*/
JSONPointer.prototype.add = function (doc, value, mutate) {
// Special case for a pointer to the root
if (0 === this.length) {
return value;
}
return this._action(doc, function (node, lastSegment) {
if (isArray(node)) {
if (lastSegment > node.length) {
throw new PatchApplyError('Add operation must not attempt to create a sparse array!');
}
node.splice(lastSegment, 0, value);
} else {
node[lastSegment] = value;
}
return node;
}, mutate);
};
/* Public: Takes a JSON document and removes the value pointed to.
* It is an error to attempt to remove a value that doesn't exist.
*
* doc - The document to operate against. May be mutated so should
* not be reused after the call.
*
* Returns the updated doc (the value passed in may also have been mutated)
*/
JSONPointer.prototype.remove = function (doc, mutate) {
// Special case for a pointer to the root
if (0 === this.length) {
// Removing the root makes the whole value undefined.
// NOTE: Should it be an error to remove the root if it is
// ALREADY undefined? I'm not sure...
return undefined;
}
return this._action(doc, function (node, lastSegment) {
if (!Object.hasOwnProperty.call(node,lastSegment)) {
throw new PatchApplyError('Remove operation must point to an existing value!');
}
if (isArray(node)) {
node.splice(lastSegment, 1);
} else {
delete node[lastSegment];
}
return node;
}, mutate);
};
/* Public: Semantically equivalent to a remove followed by an add
* except when the pointer points to the root element in which case
* the whole document is replaced.
*
* doc - The document to operate against. May be mutated so should
* not be reused after the call.
*
* Returns the updated doc (the value passed in may also have been mutated)
*/
JSONPointer.prototype.replace = function (doc, value, mutate) {
// Special case for a pointer to the root
if (0 === this.length) {
return value;
}
return this._action(doc, function (node, lastSegment) {
if (!Object.hasOwnProperty.call(node,lastSegment)) {
throw new PatchApplyError('Replace operation must point to an existing value!');
}
if (isArray(node)) {
node.splice(lastSegment, 1, value);
} else {
node[lastSegment] = value;
}
return node;
}, mutate);
};
/* Public: Returns the value pointed to by the pointer in the given doc.
*
* doc - The document to operate against.
*
* Returns the value
*/
JSONPointer.prototype.get = function (doc) {
var value;
if (0 === this.length) {
return doc;
}
this._action(doc, function (node, lastSegment) {
if (!Object.hasOwnProperty.call(node,lastSegment)) {
throw new PatchApplyError('Path not found in document');
}
value = node[lastSegment];
return node;
}, true);
return value;
};
/* Public: returns true if this pointer points to a child of the
* other pointer given. Returns true if both point to the same place.
*
* otherPointer - Another JSONPointer object
*
* Returns a boolean
*/
JSONPointer.prototype.subsetOf = function (otherPointer) {
if (this.length <= otherPointer.length) {
return false;
}
for (var i = 0; i < otherPointer.length; i++) {
if (otherPointer.path[i] !== this.path[i]) {
return false;
}
}
return true;
};
_operationRequired = {
add: ['value'],
replace: ['value'],
test: [],
remove: [],
move: ['from'],
copy: ['from']
};
// Check if a is deep equal to b (by the rules given in the
// JSONPatch spec)
function deepEqual(a,b) {
var key;
if (a === b) {
return true;
} else if (typeof a !== typeof b) {
return false;
} else if ('object' === typeof(a)) {
var aIsArray = isArray(a),
bIsArray = isArray(b);
if (aIsArray !== bIsArray) {
return false;
} else if (aIsArray) {
// Both are arrays
if (a.length != b.length) {
return false;
} else {
for (var i = 0; i < a.length; i++) {
if(!deepEqual(a[i], b[i])) {
return false;
}
}
}
return true;
} else {
// Check each key of the object recursively
for(key in a) {
if (Object.hasOwnProperty(a, key)) {
if (!(Object.hasOwnProperty(b,key) && deepEqual(a[key], b[key]))) {
return false;
}
}
}
for(key in b) {
if(Object.hasOwnProperty(b,key) && !Object.hasOwnProperty(a, key)) {
return false;
}
}
return true;
}
} else {
return false;
}
}
function validateOp(operation) {
var i, required;
if (!operation.op) {
throw new InvalidPatch('Operation missing!');
}
if (!_operationRequired.hasOwnProperty(operation.op)) {
throw new InvalidPatch('Invalid operation!');
}
if (!('path' in operation)) {
throw new InvalidPatch('Path missing!');
}
required = _operationRequired[operation.op];
// Check that all required keys are present
for(i = 0; i < required.length; i++) {
if(!(required[i] in operation)) {
throw new InvalidPatch(operation.op + ' must have key ' + required[i]);
}
}
}
function compileOperation(operation, mutate) {
validateOp(operation);
var op = operation.op;
var path = new JSONPointer(operation.path);
var value = operation.value;
var from = operation.from !== undefined ? new JSONPointer(operation.from) : null;
var inverse = operation.inverse;
switch (op) {
case 'add':
return function (doc) {
return path.add(doc, value, mutate);
};
case 'remove':
return function (doc) {
return path.remove(doc, mutate);
};
case 'replace':
return function (doc) {
return path.replace(doc, value, mutate);
};
case 'move':
// Check that destination isn't inside the source
if (path.subsetOf(from)) {
throw new InvalidPatch('destination must not be a child of source');
}
return function (doc) {
var value = from.get(doc);
var intermediate = from.remove(doc, mutate);
return path.add(intermediate, value, mutate);
};
case 'copy':
return function (doc) {
var value = from.get(doc);
return path.add(doc, value, mutate);
};
case 'test':
return function (doc) {
if (value == undefined) {
if (inverse && path.get(doc) != undefined)
throw new PatchApplyError("Exists operation failed. Key exists. -- path " + operation.path);
else if (!inverse && path.get(doc) == undefined)
throw new PatchApplyError("Exists operation failed. Key does not exist. -- path " + operation.path);
return doc;
}
if (!deepEqual(path.get(doc), value)) {
throw new PatchApplyError("Test operation failed. Value did not match.");
}
return doc;
};
}
}
/* Public: A class representing a patch.
*
* patch - The patch as an array or as a JSON string (containing an
* array)
* mutate - Indicates that input documents should be mutated
* (default is for the input to be unaffected.) This will
* not work correctly if the patch replaces the root of
* the document.
*/
exports.JSONPatch = JSONPatch = function JSONPatch(patch, mutate) {
this._compile(patch, mutate);
};
JSONPatch.prototype._compile = function (patch, mutate) {
var i, _this = this;
this.compiledOps = [];
if ('string' === typeof patch) {
patch = JSON.parse(patch);
}
if(!isArray(patch)) {
throw new InvalidPatch('Patch must be an array of operations');
}
for(i = 0; i < patch.length; i++) {
var compiled = compileOperation(patch[i], mutate);
_this.compiledOps.push(compiled);
}
};
/* Public: Apply the patch to a document and returns the patched
* document.
*
* doc - The document to which the patch should be applied.
*
* Returns the patched document
*/
exports.JSONPatch.prototype.apply = function (doc) {
var i;
for(i = 0; i < this.compiledOps.length; i++) {
doc = this.compiledOps[i](doc);
}
return doc;
};
}));