json-diff-ts 1.0.12 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,10 @@
1
1
  # json-diff-ts
2
2
 
3
- ![Master CI/Publish](https://github.com/ltwlf/json-diff-ts/workflows/Master%20CI/Publish/badge.svg)
3
+ ![Master CI/Publish](https://github.com/ltwlf/json-diff-ts/workflows/Master%20CI/Publish/badge.svg)
4
4
  [![Known Vulnerabilities](https://snyk.io/test/github/ltwlf/json-diff-ts/badge.svg?targetFile=package.json)](https://snyk.io/test/github/ltwlf/json-diff-ts?targetFile=package.json)
5
5
  [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=ltwlf_json-diff-ts&metric=alert_status)](https://sonarcloud.io/dashboard?id=ltwlf_json-diff-ts)
6
6
 
7
- A diff tool for JavaScript based on https://www.npmjs.com/package/diff-json (viruschidai@gmail.com) rewritten in TypeScript.
8
-
9
- The most compelling feature of this diff library is the support for array keys instead of just indexes and is compatible with JSONPath.
7
+ TypeScript diff tool with support for array keys instead of just indexes and compatible with JSONPath.
10
8
 
11
9
  ## Features
12
10
 
@@ -17,60 +15,70 @@ If a key is specified for an embedded array, the diff will be generated based on
17
15
  #### Examples:
18
16
 
19
17
  ```javascript
18
+ var changesets = require('json-diff-ts');
19
+ var newObj, oldObj;
20
+
21
+ oldObj = {
22
+ name: 'joe',
23
+ age: 55,
24
+ coins: [2, 5],
25
+ children: [
26
+ { name: 'kid1', age: 1 },
27
+ { name: 'kid2', age: 2 }
28
+ ]
29
+ };
30
+
31
+ newObj = {
32
+ name: 'smith',
33
+ coins: [2, 5, 1],
34
+ children: [
35
+ { name: 'kid3', age: 3 },
36
+ { name: 'kid1', age: 0 },
37
+ { name: 'kid2', age: 2 }
38
+ ]
39
+ };
20
40
 
21
- var changesets = require('diff-json-ts');
22
- var newObj, oldObj;
23
-
24
- oldObj = {
25
- name: 'joe',
26
- age: 55,
27
- coins: [2, 5],
28
- children: [
29
- {name: 'kid1', age: 1},
30
- {name: 'kid2', age: 2}
31
- ]};
32
-
33
- newObj = {
34
- name: 'smith',
35
- coins: [2, 5, 1],
36
- children: [
37
- {name: 'kid3', age: 3},
38
- {name: 'kid1', age: 0},
39
- {name: 'kid2', age: 2}
40
- ]};
41
-
42
-
43
- # Assume children is an array of child object and the child object has 'name' as its primary key
44
- diffs = changesets.diff(oldObj, newObj, {children: 'name'}); // keys can also be hierarchical e.g. {children: 'name', 'children.grandChildren', 'age'}
41
+ // Assume children is an array of child object and the child object has 'name' as its primary key
42
+ // keys can also be hierarchical e.g. {children: 'name', 'children.grandChildren', 'age'}
43
+ // or use functions that return the key of an object e.g. {children: function(obj) { return obj.key; }}
44
+ diffs = changesets.diff(oldObj, newObj, { children: 'name' });
45
45
 
46
- expect(diffs).to.eql([
47
- {
48
- type: 'update', key: 'name', value: 'smith', oldValue: 'joe'
49
- },
50
- {
51
- type: 'update', key: 'coins', embededKey: '$index', changes: [
52
- {type: 'add', key: '2', value: 1 }
53
- ]
54
- },
55
- {
56
- type: 'update',
57
- key: 'children',
58
- embededKey: 'name',
59
- changes: [
60
- {
61
- type: 'update', key: 'kid1', changes: [
62
- {type: 'update', key: 'age', value: 0, oldValue: 1 }
63
- ]
64
- },
65
- {
66
- type: 'add', key: 'kid3', value: {name: 'kid3', age: 3 }
67
- }
68
- ]
69
- },
70
- {
71
- type: 'remove', key: 'age', value: 55
72
- }
73
- ]);
46
+ expect(diffs).to.eql([
47
+ {
48
+ type: 'update',
49
+ key: 'name',
50
+ value: 'smith',
51
+ oldValue: 'joe'
52
+ },
53
+ {
54
+ type: 'update',
55
+ key: 'coins',
56
+ embededKey: '$index',
57
+ changes: [{ type: 'add', key: '2', value: 1 }]
58
+ },
59
+ {
60
+ type: 'update',
61
+ key: 'children',
62
+ embededKey: 'name',
63
+ changes: [
64
+ {
65
+ type: 'update',
66
+ key: 'kid1',
67
+ changes: [{ type: 'update', key: 'age', value: 0, oldValue: 1 }]
68
+ },
69
+ {
70
+ type: 'add',
71
+ key: 'kid3',
72
+ value: { name: 'kid3', age: 3 }
73
+ }
74
+ ]
75
+ },
76
+ {
77
+ type: 'remove',
78
+ key: 'age',
79
+ value: 55
80
+ }
81
+ ]);
74
82
  ```
75
83
 
76
84
  ### flattenChangeset
@@ -87,7 +95,7 @@ const changeset = unflattenChanges(flatChanges.slice(1, 5));
87
95
  // ...
88
96
  ```
89
97
 
90
- The **flatChange** formant will look like this:
98
+ The **flatChange** format will look like this:
91
99
 
92
100
  ```javascript
93
101
  [
@@ -132,58 +140,65 @@ The **flatChange** formant will look like this:
132
140
  #### Examples:
133
141
 
134
142
  ```javascript
135
-
136
- var changesets = require('diff-json-ts');
137
- var oldObj = {
138
- name: 'joe',
139
- age: 55,
140
- coins: [2, 5],
141
- children: [
142
- {name: 'kid1', age: 1},
143
- {name: 'kid2', age: 2}
144
- ]};
145
-
146
-
147
- # Assume children is an array of child object and the child object has 'name' as its primary key
148
- diffs = [
149
- {
150
- type: 'update', key: 'name', value: 'smith', oldValue: 'joe'
151
- },
152
- {
153
- type: 'update', key: 'coins', embededKey: '$index', changes: [
154
- {type: 'add', key: '2', value: 1 }
155
- ]
156
- },
157
- {
158
- type: 'update',
159
- key: 'children',
160
- embededKey: 'name', // The key property name of the elements in an array
161
- changes: [
162
- {
163
- type: 'update', key: 'kid1', changes: [
164
- {type: 'update', key: 'age', value: 0, oldValue: 1 }
165
- ]
166
- },
167
- {
168
- type: 'add', key: 'kid3', value: {name: 'kid3', age: 3 }
169
- }
170
- ]
171
- },
172
- {
173
- type: 'remove', key: 'age', value: 55
174
- }
143
+ var changesets = require('json-diff-ts');
144
+ var oldObj = {
145
+ name: 'joe',
146
+ age: 55,
147
+ coins: [2, 5],
148
+ children: [
149
+ { name: 'kid1', age: 1 },
150
+ { name: 'kid2', age: 2 }
175
151
  ]
152
+ };
176
153
 
177
- changesets.applyChanges(oldObj, diffs)
178
- expect(oldObj).to.eql({
179
- name: 'smith',
180
- coins: [2, 5, 1],
181
- children: [
182
- {name: 'kid3', age: 3},
183
- {name: 'kid1', age: 0},
184
- {name: 'kid2', age: 2}
185
- ]});
154
+ // Assume children is an array of child object and the child object has 'name' as its primary key
155
+ diffs = [
156
+ {
157
+ type: 'update',
158
+ key: 'name',
159
+ value: 'smith',
160
+ oldValue: 'joe'
161
+ },
162
+ {
163
+ type: 'update',
164
+ key: 'coins',
165
+ embededKey: '$index',
166
+ changes: [{ type: 'add', key: '2', value: 1 }]
167
+ },
168
+ {
169
+ type: 'update',
170
+ key: 'children',
171
+ embededKey: 'name', // The key property name of the elements in an array
172
+ changes: [
173
+ {
174
+ type: 'update',
175
+ key: 'kid1',
176
+ changes: [{ type: 'update', key: 'age', value: 0, oldValue: 1 }]
177
+ },
178
+ {
179
+ type: 'add',
180
+ key: 'kid3',
181
+ value: { name: 'kid3', age: 3 }
182
+ }
183
+ ]
184
+ },
185
+ {
186
+ type: 'remove',
187
+ key: 'age',
188
+ value: 55
189
+ }
190
+ ];
186
191
 
192
+ changesets.applyChanges(oldObj, diffs);
193
+ expect(oldObj).to.eql({
194
+ name: 'smith',
195
+ coins: [2, 5, 1],
196
+ children: [
197
+ { name: 'kid3', age: 3 },
198
+ { name: 'kid1', age: 0 },
199
+ { name: 'kid2', age: 2 }
200
+ ]
201
+ });
187
202
  ```
188
203
 
189
204
  ### revertChange
@@ -192,7 +207,7 @@ The **flatChange** formant will look like this:
192
207
 
193
208
  ```javascript
194
209
 
195
- var changesets = require('diff-json-ts');
210
+ var changesets = require('json-diff-ts');
196
211
 
197
212
  var newObj = {
198
213
  name: 'smith',
@@ -203,7 +218,7 @@ The **flatChange** formant will look like this:
203
218
  {name: 'kid2', age: 2}
204
219
  ]};
205
220
 
206
- # Assume children is an array of child object and the child object has 'name' as its primary key
221
+ // Assume children is an array of child object and the child object has 'name' as its primary key
207
222
  diffs = [
208
223
  {
209
224
  type: 'update', key: 'name', value: 'smith', oldValue: 'joe'
@@ -258,10 +273,18 @@ npm run test
258
273
  ```
259
274
 
260
275
  ## Contact
276
+
261
277
  Blog: https://blog.leitwolf.io
262
278
 
263
279
  Twitter: [@cglessner](https://twitter.com/cglessner)
264
280
 
281
+ ## Changelog
282
+
283
+ - v1.2.2 Add support for functions to resove object keys (PR by [Abraxxa](https://github.com/abraxxa))
284
+
285
+ ## Credits
286
+
287
+ This project was based on https://www.npmjs.com/package/diff-json (viruschidai@gmail.com)
265
288
 
266
289
  ## Licence
267
290
 
@@ -275,7 +298,7 @@ The above copyright notice and this permission notice shall be included in all c
275
298
 
276
299
  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.
277
300
 
278
- The project is based on diff-json (https://www.npmjs.com/package/diff-json). Copyright 2013 viruschidai@gmail.com. for additional details.
301
+ The project is based on diff-json (https://www.npmjs.com/package/diff-json). Copyright 2013 viruschidai@gmail.com. for additional details.
279
302
 
280
303
  **Original License**
281
304
 
package/lib/index.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from './jsonDiff';
2
+ export * from './jsonCompare';
package/lib/index.js CHANGED
@@ -4,3 +4,4 @@ function __export(m) {
4
4
  }
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  __export(require("./jsonDiff"));
7
+ __export(require("./jsonCompare"));
@@ -0,0 +1,15 @@
1
+ import { IFlatChange, Operation } from './jsonDiff';
2
+ export declare enum CompareOperation {
3
+ CONTAINER = "CONTAINER",
4
+ UNCHANGED = "UNCHANGED"
5
+ }
6
+ export interface IComparisonEnrichedNode {
7
+ type: Operation | CompareOperation;
8
+ value: IComparisonEnrichedNode | IComparisonEnrichedNode[] | any | any[];
9
+ oldValue?: any;
10
+ }
11
+ export declare const createValue: (value: any) => IComparisonEnrichedNode;
12
+ export declare const createContainer: (value: object | []) => IComparisonEnrichedNode;
13
+ export declare const enrich: (object: any) => IComparisonEnrichedNode;
14
+ export declare const applyChangelist: (object: IComparisonEnrichedNode, changelist: IFlatChange[]) => IComparisonEnrichedNode;
15
+ export declare const compare: (oldObject: any, newObject: any) => IComparisonEnrichedNode;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const lodash_1 = require("lodash");
4
+ const jsonDiff_1 = require("./jsonDiff");
5
+ var CompareOperation;
6
+ (function (CompareOperation) {
7
+ CompareOperation["CONTAINER"] = "CONTAINER";
8
+ CompareOperation["UNCHANGED"] = "UNCHANGED";
9
+ })(CompareOperation = exports.CompareOperation || (exports.CompareOperation = {}));
10
+ exports.createValue = (value) => ({ type: CompareOperation.UNCHANGED, value });
11
+ exports.createContainer = (value) => ({
12
+ type: CompareOperation.CONTAINER,
13
+ value
14
+ });
15
+ exports.enrich = (object) => {
16
+ const objectType = jsonDiff_1.getTypeOfObj(object);
17
+ switch (objectType) {
18
+ case 'Object':
19
+ return lodash_1.keys(object)
20
+ .map((key) => ({ key, value: exports.enrich(object[key]) }))
21
+ .reduce((accumulator, entry) => {
22
+ accumulator.value[entry.key] = entry.value;
23
+ return accumulator;
24
+ }, exports.createContainer({}));
25
+ case 'Array':
26
+ return lodash_1.chain(object)
27
+ .map(value => exports.enrich(value))
28
+ .reduce((accumulator, value) => {
29
+ accumulator.value.push(value);
30
+ return accumulator;
31
+ }, exports.createContainer([]))
32
+ .value();
33
+ case 'Function':
34
+ return undefined;
35
+ case 'Date':
36
+ default:
37
+ // Primitive value
38
+ return exports.createValue(object);
39
+ }
40
+ };
41
+ exports.applyChangelist = (object, changelist) => {
42
+ lodash_1.chain(changelist)
43
+ .map(entry => (Object.assign(Object.assign({}, entry), { path: lodash_1.replace(entry.path, '$.', '.') })))
44
+ .map(entry => (Object.assign(Object.assign({}, entry), { path: lodash_1.replace(entry.path, /(\[(?<array>\d)\]\.)/g, 'ARRVAL_START$<array>ARRVAL_END') })))
45
+ .map(entry => (Object.assign(Object.assign({}, entry), { path: lodash_1.replace(entry.path, /(?<dot>\.)/g, '.value$<dot>') })))
46
+ .map(entry => (Object.assign(Object.assign({}, entry), { path: lodash_1.replace(entry.path, /\./, '') })))
47
+ .map(entry => (Object.assign(Object.assign({}, entry), { path: lodash_1.replace(entry.path, /ARRVAL_START/g, '.value[') })))
48
+ .map(entry => (Object.assign(Object.assign({}, entry), { path: lodash_1.replace(entry.path, /ARRVAL_END/g, '].value.') })))
49
+ .value()
50
+ .forEach(entry => {
51
+ switch (entry.type) {
52
+ case jsonDiff_1.Operation.ADD:
53
+ case jsonDiff_1.Operation.UPDATE:
54
+ lodash_1.set(object, entry.path, { type: entry.type, value: entry.value, oldValue: entry.oldValue });
55
+ break;
56
+ case jsonDiff_1.Operation.REMOVE:
57
+ lodash_1.set(object, entry.path, { type: entry.type, value: undefined, oldValue: entry.value });
58
+ break;
59
+ default:
60
+ throw new Error();
61
+ }
62
+ });
63
+ return object;
64
+ };
65
+ exports.compare = (oldObject, newObject) => {
66
+ return exports.applyChangelist(exports.enrich(oldObject), jsonDiff_1.flattenChangeset(jsonDiff_1.diff(oldObject, newObject)));
67
+ };
package/lib/jsonDiff.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Dictionary } from 'lodash';
2
+ declare type FunctionKey = (obj: any) => any;
2
3
  export declare const getTypeOfObj: (obj: any) => string;
3
- export declare const diff: (oldObj: any, newObj: any, embeddedObjKeys?: Dictionary<string>) => IChange[];
4
+ export declare const diff: (oldObj: any, newObj: any, embeddedObjKeys?: Dictionary<string | FunctionKey>) => IChange[];
4
5
  export declare const applyChangeset: (obj: any, changeset: Changeset) => any;
5
6
  export declare const revertChangeset: (obj: any, changeset: Changeset) => any;
6
7
  export declare enum Operation {
@@ -11,7 +12,7 @@ export declare enum Operation {
11
12
  export interface IChange {
12
13
  type: Operation;
13
14
  key: string;
14
- embeddedKey?: string;
15
+ embeddedKey?: string | FunctionKey;
15
16
  value?: any | any[];
16
17
  oldValue?: any;
17
18
  changes?: IChange[];
@@ -25,5 +26,6 @@ export interface IFlatChange {
25
26
  value?: any;
26
27
  oldValue?: any;
27
28
  }
28
- export declare const flattenChangeset: (obj: IChange | Changeset, path?: string, embeddedKey?: string) => IFlatChange[];
29
+ export declare const flattenChangeset: (obj: IChange | Changeset, path?: string, embeddedKey?: string | FunctionKey) => IFlatChange[];
29
30
  export declare const unflattenChanges: (changes: IFlatChange | IFlatChange[]) => IChange[];
31
+ export {};
package/lib/jsonDiff.js CHANGED
@@ -96,7 +96,7 @@ const compareObject = (oldObj, newObj, path, embeddedObjKeys, keyPath, skipPath
96
96
  return changes;
97
97
  };
98
98
  const compareArray = (oldObj, newObj, path, embeddedObjKeys, keyPath) => {
99
- const left = embeddedObjKeys != null ? embeddedObjKeys[keyPath.join('.')] : undefined;
99
+ const left = getObjectKey(embeddedObjKeys, keyPath);
100
100
  const uniqKey = left != null ? left : '$index';
101
101
  const indexedOldObj = convertArrayToObj(oldObj, uniqKey);
102
102
  const indexedNewObj = convertArrayToObj(newObj, uniqKey);
@@ -115,6 +115,21 @@ const compareArray = (oldObj, newObj, path, embeddedObjKeys, keyPath) => {
115
115
  return [];
116
116
  }
117
117
  };
118
+ const getObjectKey = (embeddedObjKeys, keyPath) => {
119
+ if (embeddedObjKeys != null) {
120
+ const path = keyPath.join('.');
121
+ const key = embeddedObjKeys[path];
122
+ if (key != null) {
123
+ return key;
124
+ }
125
+ for (const regex in embeddedObjKeys) {
126
+ if (path.match(new RegExp(regex))) {
127
+ return embeddedObjKeys[regex];
128
+ }
129
+ }
130
+ }
131
+ return undefined;
132
+ };
118
133
  const convertArrayToObj = (arr, uniqKey) => {
119
134
  let obj = {};
120
135
  if (uniqKey !== '$index') {
@@ -309,7 +324,14 @@ exports.unflattenChanges = (changes) => {
309
324
  changes.forEach(change => {
310
325
  const obj = {};
311
326
  let ptr = obj;
312
- const segments = change.path.split(/((?<!@)\.)/).filter(x => x !== '.');
327
+ const segments = change.path.split(/([^@])\./).reduce((acc, curr, i) => {
328
+ const x = Math.floor(i / 2);
329
+ if (!acc[x]) {
330
+ acc[x] = '';
331
+ }
332
+ acc[x] += curr;
333
+ return acc;
334
+ }, []);
313
335
  // $.childern[@.name='chris'].age
314
336
  // =>
315
337
  // $
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-diff-ts",
3
- "version": "1.0.12",
3
+ "version": "1.2.2",
4
4
  "description": "A diff tool for JavaScript based on https://www.npmjs.com/package/diff-json written in TypeScript.",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",