source: node_modules/fast-json-patch/dist/fast-json-patch.js

main
Last change on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 36.7 KB
Line 
1/*! fast-json-patch, version: 3.1.1 */
2var jsonpatch =
3/******/ (function(modules) { // webpackBootstrap
4/******/ // The module cache
5/******/ var installedModules = {};
6/******/
7/******/ // The require function
8/******/ function __webpack_require__(moduleId) {
9/******/
10/******/ // Check if module is in cache
11/******/ if(installedModules[moduleId]) {
12/******/ return installedModules[moduleId].exports;
13/******/ }
14/******/ // Create a new module (and put it into the cache)
15/******/ var module = installedModules[moduleId] = {
16/******/ i: moduleId,
17/******/ l: false,
18/******/ exports: {}
19/******/ };
20/******/
21/******/ // Execute the module function
22/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
23/******/
24/******/ // Flag the module as loaded
25/******/ module.l = true;
26/******/
27/******/ // Return the exports of the module
28/******/ return module.exports;
29/******/ }
30/******/
31/******/
32/******/ // expose the modules object (__webpack_modules__)
33/******/ __webpack_require__.m = modules;
34/******/
35/******/ // expose the module cache
36/******/ __webpack_require__.c = installedModules;
37/******/
38/******/ // define getter function for harmony exports
39/******/ __webpack_require__.d = function(exports, name, getter) {
40/******/ if(!__webpack_require__.o(exports, name)) {
41/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
42/******/ }
43/******/ };
44/******/
45/******/ // define __esModule on exports
46/******/ __webpack_require__.r = function(exports) {
47/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
48/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
49/******/ }
50/******/ Object.defineProperty(exports, '__esModule', { value: true });
51/******/ };
52/******/
53/******/ // create a fake namespace object
54/******/ // mode & 1: value is a module id, require it
55/******/ // mode & 2: merge all properties of value into the ns
56/******/ // mode & 4: return value when already ns object
57/******/ // mode & 8|1: behave like require
58/******/ __webpack_require__.t = function(value, mode) {
59/******/ if(mode & 1) value = __webpack_require__(value);
60/******/ if(mode & 8) return value;
61/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
62/******/ var ns = Object.create(null);
63/******/ __webpack_require__.r(ns);
64/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
65/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
66/******/ return ns;
67/******/ };
68/******/
69/******/ // getDefaultExport function for compatibility with non-harmony modules
70/******/ __webpack_require__.n = function(module) {
71/******/ var getter = module && module.__esModule ?
72/******/ function getDefault() { return module['default']; } :
73/******/ function getModuleExports() { return module; };
74/******/ __webpack_require__.d(getter, 'a', getter);
75/******/ return getter;
76/******/ };
77/******/
78/******/ // Object.prototype.hasOwnProperty.call
79/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
80/******/
81/******/ // __webpack_public_path__
82/******/ __webpack_require__.p = "";
83/******/
84/******/
85/******/ // Load entry module and return exports
86/******/ return __webpack_require__(__webpack_require__.s = 2);
87/******/ })
88/************************************************************************/
89/******/ ([
90/* 0 */
91/***/ (function(module, exports) {
92
93/*!
94 * https://github.com/Starcounter-Jack/JSON-Patch
95 * (c) 2017-2022 Joachim Wester
96 * MIT licensed
97 */
98var __extends = (this && this.__extends) || (function () {
99 var extendStatics = function (d, b) {
100 extendStatics = Object.setPrototypeOf ||
101 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
102 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
103 return extendStatics(d, b);
104 };
105 return function (d, b) {
106 extendStatics(d, b);
107 function __() { this.constructor = d; }
108 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
109 };
110})();
111Object.defineProperty(exports, "__esModule", { value: true });
112var _hasOwnProperty = Object.prototype.hasOwnProperty;
113function hasOwnProperty(obj, key) {
114 return _hasOwnProperty.call(obj, key);
115}
116exports.hasOwnProperty = hasOwnProperty;
117function _objectKeys(obj) {
118 if (Array.isArray(obj)) {
119 var keys_1 = new Array(obj.length);
120 for (var k = 0; k < keys_1.length; k++) {
121 keys_1[k] = "" + k;
122 }
123 return keys_1;
124 }
125 if (Object.keys) {
126 return Object.keys(obj);
127 }
128 var keys = [];
129 for (var i in obj) {
130 if (hasOwnProperty(obj, i)) {
131 keys.push(i);
132 }
133 }
134 return keys;
135}
136exports._objectKeys = _objectKeys;
137;
138/**
139* Deeply clone the object.
140* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy)
141* @param {any} obj value to clone
142* @return {any} cloned obj
143*/
144function _deepClone(obj) {
145 switch (typeof obj) {
146 case "object":
147 return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5
148 case "undefined":
149 return null; //this is how JSON.stringify behaves for array items
150 default:
151 return obj; //no need to clone primitives
152 }
153}
154exports._deepClone = _deepClone;
155//3x faster than cached /^\d+$/.test(str)
156function isInteger(str) {
157 var i = 0;
158 var len = str.length;
159 var charCode;
160 while (i < len) {
161 charCode = str.charCodeAt(i);
162 if (charCode >= 48 && charCode <= 57) {
163 i++;
164 continue;
165 }
166 return false;
167 }
168 return true;
169}
170exports.isInteger = isInteger;
171/**
172* Escapes a json pointer path
173* @param path The raw pointer
174* @return the Escaped path
175*/
176function escapePathComponent(path) {
177 if (path.indexOf('/') === -1 && path.indexOf('~') === -1)
178 return path;
179 return path.replace(/~/g, '~0').replace(/\//g, '~1');
180}
181exports.escapePathComponent = escapePathComponent;
182/**
183 * Unescapes a json pointer path
184 * @param path The escaped pointer
185 * @return The unescaped path
186 */
187function unescapePathComponent(path) {
188 return path.replace(/~1/g, '/').replace(/~0/g, '~');
189}
190exports.unescapePathComponent = unescapePathComponent;
191function _getPathRecursive(root, obj) {
192 var found;
193 for (var key in root) {
194 if (hasOwnProperty(root, key)) {
195 if (root[key] === obj) {
196 return escapePathComponent(key) + '/';
197 }
198 else if (typeof root[key] === 'object') {
199 found = _getPathRecursive(root[key], obj);
200 if (found != '') {
201 return escapePathComponent(key) + '/' + found;
202 }
203 }
204 }
205 }
206 return '';
207}
208exports._getPathRecursive = _getPathRecursive;
209function getPath(root, obj) {
210 if (root === obj) {
211 return '/';
212 }
213 var path = _getPathRecursive(root, obj);
214 if (path === '') {
215 throw new Error("Object not found in root");
216 }
217 return "/" + path;
218}
219exports.getPath = getPath;
220/**
221* Recursively checks whether an object has any undefined values inside.
222*/
223function hasUndefined(obj) {
224 if (obj === undefined) {
225 return true;
226 }
227 if (obj) {
228 if (Array.isArray(obj)) {
229 for (var i_1 = 0, len = obj.length; i_1 < len; i_1++) {
230 if (hasUndefined(obj[i_1])) {
231 return true;
232 }
233 }
234 }
235 else if (typeof obj === "object") {
236 var objKeys = _objectKeys(obj);
237 var objKeysLength = objKeys.length;
238 for (var i = 0; i < objKeysLength; i++) {
239 if (hasUndefined(obj[objKeys[i]])) {
240 return true;
241 }
242 }
243 }
244 }
245 return false;
246}
247exports.hasUndefined = hasUndefined;
248function patchErrorMessageFormatter(message, args) {
249 var messageParts = [message];
250 for (var key in args) {
251 var value = typeof args[key] === 'object' ? JSON.stringify(args[key], null, 2) : args[key]; // pretty print
252 if (typeof value !== 'undefined') {
253 messageParts.push(key + ": " + value);
254 }
255 }
256 return messageParts.join('\n');
257}
258var PatchError = /** @class */ (function (_super) {
259 __extends(PatchError, _super);
260 function PatchError(message, name, index, operation, tree) {
261 var _newTarget = this.constructor;
262 var _this = _super.call(this, patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree })) || this;
263 _this.name = name;
264 _this.index = index;
265 _this.operation = operation;
266 _this.tree = tree;
267 Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359
268 _this.message = patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree });
269 return _this;
270 }
271 return PatchError;
272}(Error));
273exports.PatchError = PatchError;
274
275
276/***/ }),
277/* 1 */
278/***/ (function(module, exports, __webpack_require__) {
279
280Object.defineProperty(exports, "__esModule", { value: true });
281var helpers_js_1 = __webpack_require__(0);
282exports.JsonPatchError = helpers_js_1.PatchError;
283exports.deepClone = helpers_js_1._deepClone;
284/* We use a Javascript hash to store each
285 function. Each hash entry (property) uses
286 the operation identifiers specified in rfc6902.
287 In this way, we can map each patch operation
288 to its dedicated function in efficient way.
289 */
290/* The operations applicable to an object */
291var objOps = {
292 add: function (obj, key, document) {
293 obj[key] = this.value;
294 return { newDocument: document };
295 },
296 remove: function (obj, key, document) {
297 var removed = obj[key];
298 delete obj[key];
299 return { newDocument: document, removed: removed };
300 },
301 replace: function (obj, key, document) {
302 var removed = obj[key];
303 obj[key] = this.value;
304 return { newDocument: document, removed: removed };
305 },
306 move: function (obj, key, document) {
307 /* in case move target overwrites an existing value,
308 return the removed value, this can be taxing performance-wise,
309 and is potentially unneeded */
310 var removed = getValueByPointer(document, this.path);
311 if (removed) {
312 removed = helpers_js_1._deepClone(removed);
313 }
314 var originalValue = applyOperation(document, { op: "remove", path: this.from }).removed;
315 applyOperation(document, { op: "add", path: this.path, value: originalValue });
316 return { newDocument: document, removed: removed };
317 },
318 copy: function (obj, key, document) {
319 var valueToCopy = getValueByPointer(document, this.from);
320 // enforce copy by value so further operations don't affect source (see issue #177)
321 applyOperation(document, { op: "add", path: this.path, value: helpers_js_1._deepClone(valueToCopy) });
322 return { newDocument: document };
323 },
324 test: function (obj, key, document) {
325 return { newDocument: document, test: _areEquals(obj[key], this.value) };
326 },
327 _get: function (obj, key, document) {
328 this.value = obj[key];
329 return { newDocument: document };
330 }
331};
332/* The operations applicable to an array. Many are the same as for the object */
333var arrOps = {
334 add: function (arr, i, document) {
335 if (helpers_js_1.isInteger(i)) {
336 arr.splice(i, 0, this.value);
337 }
338 else { // array props
339 arr[i] = this.value;
340 }
341 // this may be needed when using '-' in an array
342 return { newDocument: document, index: i };
343 },
344 remove: function (arr, i, document) {
345 var removedList = arr.splice(i, 1);
346 return { newDocument: document, removed: removedList[0] };
347 },
348 replace: function (arr, i, document) {
349 var removed = arr[i];
350 arr[i] = this.value;
351 return { newDocument: document, removed: removed };
352 },
353 move: objOps.move,
354 copy: objOps.copy,
355 test: objOps.test,
356 _get: objOps._get
357};
358/**
359 * Retrieves a value from a JSON document by a JSON pointer.
360 * Returns the value.
361 *
362 * @param document The document to get the value from
363 * @param pointer an escaped JSON pointer
364 * @return The retrieved value
365 */
366function getValueByPointer(document, pointer) {
367 if (pointer == '') {
368 return document;
369 }
370 var getOriginalDestination = { op: "_get", path: pointer };
371 applyOperation(document, getOriginalDestination);
372 return getOriginalDestination.value;
373}
374exports.getValueByPointer = getValueByPointer;
375/**
376 * Apply a single JSON Patch Operation on a JSON document.
377 * Returns the {newDocument, result} of the operation.
378 * It modifies the `document` and `operation` objects - it gets the values by reference.
379 * If you would like to avoid touching your values, clone them:
380 * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.
381 *
382 * @param document The document to patch
383 * @param operation The operation to apply
384 * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.
385 * @param mutateDocument Whether to mutate the original document or clone it before applying
386 * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.
387 * @return `{newDocument, result}` after the operation
388 */
389function applyOperation(document, operation, validateOperation, mutateDocument, banPrototypeModifications, index) {
390 if (validateOperation === void 0) { validateOperation = false; }
391 if (mutateDocument === void 0) { mutateDocument = true; }
392 if (banPrototypeModifications === void 0) { banPrototypeModifications = true; }
393 if (index === void 0) { index = 0; }
394 if (validateOperation) {
395 if (typeof validateOperation == 'function') {
396 validateOperation(operation, 0, document, operation.path);
397 }
398 else {
399 validator(operation, 0);
400 }
401 }
402 /* ROOT OPERATIONS */
403 if (operation.path === "") {
404 var returnValue = { newDocument: document };
405 if (operation.op === 'add') {
406 returnValue.newDocument = operation.value;
407 return returnValue;
408 }
409 else if (operation.op === 'replace') {
410 returnValue.newDocument = operation.value;
411 returnValue.removed = document; //document we removed
412 return returnValue;
413 }
414 else if (operation.op === 'move' || operation.op === 'copy') { // it's a move or copy to root
415 returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field
416 if (operation.op === 'move') { // report removed item
417 returnValue.removed = document;
418 }
419 return returnValue;
420 }
421 else if (operation.op === 'test') {
422 returnValue.test = _areEquals(document, operation.value);
423 if (returnValue.test === false) {
424 throw new exports.JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
425 }
426 returnValue.newDocument = document;
427 return returnValue;
428 }
429 else if (operation.op === 'remove') { // a remove on root
430 returnValue.removed = document;
431 returnValue.newDocument = null;
432 return returnValue;
433 }
434 else if (operation.op === '_get') {
435 operation.value = document;
436 return returnValue;
437 }
438 else { /* bad operation */
439 if (validateOperation) {
440 throw new exports.JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);
441 }
442 else {
443 return returnValue;
444 }
445 }
446 } /* END ROOT OPERATIONS */
447 else {
448 if (!mutateDocument) {
449 document = helpers_js_1._deepClone(document);
450 }
451 var path = operation.path || "";
452 var keys = path.split('/');
453 var obj = document;
454 var t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift
455 var len = keys.length;
456 var existingPathFragment = undefined;
457 var key = void 0;
458 var validateFunction = void 0;
459 if (typeof validateOperation == 'function') {
460 validateFunction = validateOperation;
461 }
462 else {
463 validateFunction = validator;
464 }
465 while (true) {
466 key = keys[t];
467 if (key && key.indexOf('~') != -1) {
468 key = helpers_js_1.unescapePathComponent(key);
469 }
470 if (banPrototypeModifications &&
471 (key == '__proto__' ||
472 (key == 'prototype' && t > 0 && keys[t - 1] == 'constructor'))) {
473 throw new TypeError('JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README');
474 }
475 if (validateOperation) {
476 if (existingPathFragment === undefined) {
477 if (obj[key] === undefined) {
478 existingPathFragment = keys.slice(0, t).join('/');
479 }
480 else if (t == len - 1) {
481 existingPathFragment = operation.path;
482 }
483 if (existingPathFragment !== undefined) {
484 validateFunction(operation, 0, document, existingPathFragment);
485 }
486 }
487 }
488 t++;
489 if (Array.isArray(obj)) {
490 if (key === '-') {
491 key = obj.length;
492 }
493 else {
494 if (validateOperation && !helpers_js_1.isInteger(key)) {
495 throw new exports.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document);
496 } // only parse key when it's an integer for `arr.prop` to work
497 else if (helpers_js_1.isInteger(key)) {
498 key = ~~key;
499 }
500 }
501 if (t >= len) {
502 if (validateOperation && operation.op === "add" && key > obj.length) {
503 throw new exports.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document);
504 }
505 var returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch
506 if (returnValue.test === false) {
507 throw new exports.JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
508 }
509 return returnValue;
510 }
511 }
512 else {
513 if (t >= len) {
514 var returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch
515 if (returnValue.test === false) {
516 throw new exports.JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
517 }
518 return returnValue;
519 }
520 }
521 obj = obj[key];
522 // If we have more keys in the path, but the next value isn't a non-null object,
523 // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.
524 if (validateOperation && t < len && (!obj || typeof obj !== "object")) {
525 throw new exports.JsonPatchError('Cannot perform operation at the desired path', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);
526 }
527 }
528 }
529}
530exports.applyOperation = applyOperation;
531/**
532 * Apply a full JSON Patch array on a JSON document.
533 * Returns the {newDocument, result} of the patch.
534 * It modifies the `document` object and `patch` - it gets the values by reference.
535 * If you would like to avoid touching your values, clone them:
536 * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.
537 *
538 * @param document The document to patch
539 * @param patch The patch to apply
540 * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.
541 * @param mutateDocument Whether to mutate the original document or clone it before applying
542 * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.
543 * @return An array of `{newDocument, result}` after the patch
544 */
545function applyPatch(document, patch, validateOperation, mutateDocument, banPrototypeModifications) {
546 if (mutateDocument === void 0) { mutateDocument = true; }
547 if (banPrototypeModifications === void 0) { banPrototypeModifications = true; }
548 if (validateOperation) {
549 if (!Array.isArray(patch)) {
550 throw new exports.JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');
551 }
552 }
553 if (!mutateDocument) {
554 document = helpers_js_1._deepClone(document);
555 }
556 var results = new Array(patch.length);
557 for (var i = 0, length_1 = patch.length; i < length_1; i++) {
558 // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`
559 results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i);
560 document = results[i].newDocument; // in case root was replaced
561 }
562 results.newDocument = document;
563 return results;
564}
565exports.applyPatch = applyPatch;
566/**
567 * Apply a single JSON Patch Operation on a JSON document.
568 * Returns the updated document.
569 * Suitable as a reducer.
570 *
571 * @param document The document to patch
572 * @param operation The operation to apply
573 * @return The updated document
574 */
575function applyReducer(document, operation, index) {
576 var operationResult = applyOperation(document, operation);
577 if (operationResult.test === false) { // failed test
578 throw new exports.JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
579 }
580 return operationResult.newDocument;
581}
582exports.applyReducer = applyReducer;
583/**
584 * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.
585 * @param {object} operation - operation object (patch)
586 * @param {number} index - index of operation in the sequence
587 * @param {object} [document] - object where the operation is supposed to be applied
588 * @param {string} [existingPathFragment] - comes along with `document`
589 */
590function validator(operation, index, document, existingPathFragment) {
591 if (typeof operation !== 'object' || operation === null || Array.isArray(operation)) {
592 throw new exports.JsonPatchError('Operation is not an object', 'OPERATION_NOT_AN_OBJECT', index, operation, document);
593 }
594 else if (!objOps[operation.op]) {
595 throw new exports.JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);
596 }
597 else if (typeof operation.path !== 'string') {
598 throw new exports.JsonPatchError('Operation `path` property is not a string', 'OPERATION_PATH_INVALID', index, operation, document);
599 }
600 else if (operation.path.indexOf('/') !== 0 && operation.path.length > 0) {
601 // paths that aren't empty string should start with "/"
602 throw new exports.JsonPatchError('Operation `path` property must start with "/"', 'OPERATION_PATH_INVALID', index, operation, document);
603 }
604 else if ((operation.op === 'move' || operation.op === 'copy') && typeof operation.from !== 'string') {
605 throw new exports.JsonPatchError('Operation `from` property is not present (applicable in `move` and `copy` operations)', 'OPERATION_FROM_REQUIRED', index, operation, document);
606 }
607 else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && operation.value === undefined) {
608 throw new exports.JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_REQUIRED', index, operation, document);
609 }
610 else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && helpers_js_1.hasUndefined(operation.value)) {
611 throw new exports.JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED', index, operation, document);
612 }
613 else if (document) {
614 if (operation.op == "add") {
615 var pathLen = operation.path.split("/").length;
616 var existingPathLen = existingPathFragment.split("/").length;
617 if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {
618 throw new exports.JsonPatchError('Cannot perform an `add` operation at the desired path', 'OPERATION_PATH_CANNOT_ADD', index, operation, document);
619 }
620 }
621 else if (operation.op === 'replace' || operation.op === 'remove' || operation.op === '_get') {
622 if (operation.path !== existingPathFragment) {
623 throw new exports.JsonPatchError('Cannot perform the operation at a path that does not exist', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);
624 }
625 }
626 else if (operation.op === 'move' || operation.op === 'copy') {
627 var existingValue = { op: "_get", path: operation.from, value: undefined };
628 var error = validate([existingValue], document);
629 if (error && error.name === 'OPERATION_PATH_UNRESOLVABLE') {
630 throw new exports.JsonPatchError('Cannot perform the operation from a path that does not exist', 'OPERATION_FROM_UNRESOLVABLE', index, operation, document);
631 }
632 }
633 }
634}
635exports.validator = validator;
636/**
637 * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.
638 * If error is encountered, returns a JsonPatchError object
639 * @param sequence
640 * @param document
641 * @returns {JsonPatchError|undefined}
642 */
643function validate(sequence, document, externalValidator) {
644 try {
645 if (!Array.isArray(sequence)) {
646 throw new exports.JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');
647 }
648 if (document) {
649 //clone document and sequence so that we can safely try applying operations
650 applyPatch(helpers_js_1._deepClone(document), helpers_js_1._deepClone(sequence), externalValidator || true);
651 }
652 else {
653 externalValidator = externalValidator || validator;
654 for (var i = 0; i < sequence.length; i++) {
655 externalValidator(sequence[i], i, document, undefined);
656 }
657 }
658 }
659 catch (e) {
660 if (e instanceof exports.JsonPatchError) {
661 return e;
662 }
663 else {
664 throw e;
665 }
666 }
667}
668exports.validate = validate;
669// based on https://github.com/epoberezkin/fast-deep-equal
670// MIT License
671// Copyright (c) 2017 Evgeny Poberezkin
672// Permission is hereby granted, free of charge, to any person obtaining a copy
673// of this software and associated documentation files (the "Software"), to deal
674// in the Software without restriction, including without limitation the rights
675// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
676// copies of the Software, and to permit persons to whom the Software is
677// furnished to do so, subject to the following conditions:
678// The above copyright notice and this permission notice shall be included in all
679// copies or substantial portions of the Software.
680// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
681// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
682// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
683// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
684// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
685// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
686// SOFTWARE.
687function _areEquals(a, b) {
688 if (a === b)
689 return true;
690 if (a && b && typeof a == 'object' && typeof b == 'object') {
691 var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key;
692 if (arrA && arrB) {
693 length = a.length;
694 if (length != b.length)
695 return false;
696 for (i = length; i-- !== 0;)
697 if (!_areEquals(a[i], b[i]))
698 return false;
699 return true;
700 }
701 if (arrA != arrB)
702 return false;
703 var keys = Object.keys(a);
704 length = keys.length;
705 if (length !== Object.keys(b).length)
706 return false;
707 for (i = length; i-- !== 0;)
708 if (!b.hasOwnProperty(keys[i]))
709 return false;
710 for (i = length; i-- !== 0;) {
711 key = keys[i];
712 if (!_areEquals(a[key], b[key]))
713 return false;
714 }
715 return true;
716 }
717 return a !== a && b !== b;
718}
719exports._areEquals = _areEquals;
720;
721
722
723/***/ }),
724/* 2 */
725/***/ (function(module, exports, __webpack_require__) {
726
727var core = __webpack_require__(1);
728Object.assign(exports, core);
729
730var duplex = __webpack_require__(3);
731Object.assign(exports, duplex);
732
733var helpers = __webpack_require__(0);
734exports.JsonPatchError = helpers.PatchError;
735exports.deepClone = helpers._deepClone;
736exports.escapePathComponent = helpers.escapePathComponent;
737exports.unescapePathComponent = helpers.unescapePathComponent;
738
739
740/***/ }),
741/* 3 */
742/***/ (function(module, exports, __webpack_require__) {
743
744Object.defineProperty(exports, "__esModule", { value: true });
745/*!
746 * https://github.com/Starcounter-Jack/JSON-Patch
747 * (c) 2017-2021 Joachim Wester
748 * MIT license
749 */
750var helpers_js_1 = __webpack_require__(0);
751var core_js_1 = __webpack_require__(1);
752var beforeDict = new WeakMap();
753var Mirror = /** @class */ (function () {
754 function Mirror(obj) {
755 this.observers = new Map();
756 this.obj = obj;
757 }
758 return Mirror;
759}());
760var ObserverInfo = /** @class */ (function () {
761 function ObserverInfo(callback, observer) {
762 this.callback = callback;
763 this.observer = observer;
764 }
765 return ObserverInfo;
766}());
767function getMirror(obj) {
768 return beforeDict.get(obj);
769}
770function getObserverFromMirror(mirror, callback) {
771 return mirror.observers.get(callback);
772}
773function removeObserverFromMirror(mirror, observer) {
774 mirror.observers.delete(observer.callback);
775}
776/**
777 * Detach an observer from an object
778 */
779function unobserve(root, observer) {
780 observer.unobserve();
781}
782exports.unobserve = unobserve;
783/**
784 * Observes changes made to an object, which can then be retrieved using generate
785 */
786function observe(obj, callback) {
787 var patches = [];
788 var observer;
789 var mirror = getMirror(obj);
790 if (!mirror) {
791 mirror = new Mirror(obj);
792 beforeDict.set(obj, mirror);
793 }
794 else {
795 var observerInfo = getObserverFromMirror(mirror, callback);
796 observer = observerInfo && observerInfo.observer;
797 }
798 if (observer) {
799 return observer;
800 }
801 observer = {};
802 mirror.value = helpers_js_1._deepClone(obj);
803 if (callback) {
804 observer.callback = callback;
805 observer.next = null;
806 var dirtyCheck = function () {
807 generate(observer);
808 };
809 var fastCheck = function () {
810 clearTimeout(observer.next);
811 observer.next = setTimeout(dirtyCheck);
812 };
813 if (typeof window !== 'undefined') { //not Node
814 window.addEventListener('mouseup', fastCheck);
815 window.addEventListener('keyup', fastCheck);
816 window.addEventListener('mousedown', fastCheck);
817 window.addEventListener('keydown', fastCheck);
818 window.addEventListener('change', fastCheck);
819 }
820 }
821 observer.patches = patches;
822 observer.object = obj;
823 observer.unobserve = function () {
824 generate(observer);
825 clearTimeout(observer.next);
826 removeObserverFromMirror(mirror, observer);
827 if (typeof window !== 'undefined') {
828 window.removeEventListener('mouseup', fastCheck);
829 window.removeEventListener('keyup', fastCheck);
830 window.removeEventListener('mousedown', fastCheck);
831 window.removeEventListener('keydown', fastCheck);
832 window.removeEventListener('change', fastCheck);
833 }
834 };
835 mirror.observers.set(callback, new ObserverInfo(callback, observer));
836 return observer;
837}
838exports.observe = observe;
839/**
840 * Generate an array of patches from an observer
841 */
842function generate(observer, invertible) {
843 if (invertible === void 0) { invertible = false; }
844 var mirror = beforeDict.get(observer.object);
845 _generate(mirror.value, observer.object, observer.patches, "", invertible);
846 if (observer.patches.length) {
847 core_js_1.applyPatch(mirror.value, observer.patches);
848 }
849 var temp = observer.patches;
850 if (temp.length > 0) {
851 observer.patches = [];
852 if (observer.callback) {
853 observer.callback(temp);
854 }
855 }
856 return temp;
857}
858exports.generate = generate;
859// Dirty check if obj is different from mirror, generate patches and update mirror
860function _generate(mirror, obj, patches, path, invertible) {
861 if (obj === mirror) {
862 return;
863 }
864 if (typeof obj.toJSON === "function") {
865 obj = obj.toJSON();
866 }
867 var newKeys = helpers_js_1._objectKeys(obj);
868 var oldKeys = helpers_js_1._objectKeys(mirror);
869 var changed = false;
870 var deleted = false;
871 //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)"
872 for (var t = oldKeys.length - 1; t >= 0; t--) {
873 var key = oldKeys[t];
874 var oldVal = mirror[key];
875 if (helpers_js_1.hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) {
876 var newVal = obj[key];
877 if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) {
878 _generate(oldVal, newVal, patches, path + "/" + helpers_js_1.escapePathComponent(key), invertible);
879 }
880 else {
881 if (oldVal !== newVal) {
882 changed = true;
883 if (invertible) {
884 patches.push({ op: "test", path: path + "/" + helpers_js_1.escapePathComponent(key), value: helpers_js_1._deepClone(oldVal) });
885 }
886 patches.push({ op: "replace", path: path + "/" + helpers_js_1.escapePathComponent(key), value: helpers_js_1._deepClone(newVal) });
887 }
888 }
889 }
890 else if (Array.isArray(mirror) === Array.isArray(obj)) {
891 if (invertible) {
892 patches.push({ op: "test", path: path + "/" + helpers_js_1.escapePathComponent(key), value: helpers_js_1._deepClone(oldVal) });
893 }
894 patches.push({ op: "remove", path: path + "/" + helpers_js_1.escapePathComponent(key) });
895 deleted = true; // property has been deleted
896 }
897 else {
898 if (invertible) {
899 patches.push({ op: "test", path: path, value: mirror });
900 }
901 patches.push({ op: "replace", path: path, value: obj });
902 changed = true;
903 }
904 }
905 if (!deleted && newKeys.length == oldKeys.length) {
906 return;
907 }
908 for (var t = 0; t < newKeys.length; t++) {
909 var key = newKeys[t];
910 if (!helpers_js_1.hasOwnProperty(mirror, key) && obj[key] !== undefined) {
911 patches.push({ op: "add", path: path + "/" + helpers_js_1.escapePathComponent(key), value: helpers_js_1._deepClone(obj[key]) });
912 }
913 }
914}
915/**
916 * Create an array of patches from the differences in two objects
917 */
918function compare(tree1, tree2, invertible) {
919 if (invertible === void 0) { invertible = false; }
920 var patches = [];
921 _generate(tree1, tree2, patches, '', invertible);
922 return patches;
923}
924exports.compare = compare;
925
926
927/***/ })
928/******/ ]);
Note: See TracBrowser for help on using the repository browser.