UNPKG

6.79 kBJavaScriptView Raw
1/*!
2Copyright (C) 2013-2017 by Andrea Giammarchi - @WebReflection
3
4Permission is hereby granted, free of charge, to any person obtaining a copy
5of this software and associated documentation files (the "Software"), to deal
6in the Software without restriction, including without limitation the rights
7to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8copies of the Software, and to permit persons to whom the Software is
9furnished to do so, subject to the following conditions:
10
11The above copyright notice and this permission notice shall be included in
12all copies or substantial portions of the Software.
13
14THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20THE SOFTWARE.
21
22*/
23var
24 // should be a not so common char
25 // possibly one JSON does not encode
26 // possibly one encodeURIComponent does not encode
27 // right now this char is '~' but this might change in the future
28 specialChar = '~',
29 safeSpecialChar = '\\x' + (
30 '0' + specialChar.charCodeAt(0).toString(16)
31 ).slice(-2),
32 escapedSafeSpecialChar = '\\' + safeSpecialChar,
33 specialCharRG = new RegExp(safeSpecialChar, 'g'),
34 safeSpecialCharRG = new RegExp(escapedSafeSpecialChar, 'g'),
35
36 safeStartWithSpecialCharRG = new RegExp('(?:^|([^\\\\]))' + escapedSafeSpecialChar),
37
38 indexOf = [].indexOf || function(v){
39 for(var i=this.length;i--&&this[i]!==v;);
40 return i;
41 },
42 $String = String // there's no way to drop warnings in JSHint
43 // about new String ... well, I need that here!
44 // faked, and happy linter!
45;
46
47function generateReplacer(value, replacer, resolve) {
48 var
49 doNotIgnore = false,
50 inspect = !!replacer,
51 path = [],
52 all = [value],
53 seen = [value],
54 mapp = [resolve ? specialChar : '[Circular]'],
55 last = value,
56 lvl = 1,
57 i, fn
58 ;
59 if (inspect) {
60 fn = typeof replacer === 'object' ?
61 function (key, value) {
62 return key !== '' && replacer.indexOf(key) < 0 ? void 0 : value;
63 } :
64 replacer;
65 }
66 return function(key, value) {
67 // the replacer has rights to decide
68 // if a new object should be returned
69 // or if there's some key to drop
70 // let's call it here rather than "too late"
71 if (inspect) value = fn.call(this, key, value);
72
73 // first pass should be ignored, since it's just the initial object
74 if (doNotIgnore) {
75 if (last !== this) {
76 i = lvl - indexOf.call(all, this) - 1;
77 lvl -= i;
78 all.splice(lvl, all.length);
79 path.splice(lvl - 1, path.length);
80 last = this;
81 }
82 // console.log(lvl, key, path);
83 if (typeof value === 'object' && value) {
84 // if object isn't referring to parent object, add to the
85 // object path stack. Otherwise it is already there.
86 if (indexOf.call(all, value) < 0) {
87 all.push(last = value);
88 }
89 lvl = all.length;
90 i = indexOf.call(seen, value);
91 if (i < 0) {
92 i = seen.push(value) - 1;
93 if (resolve) {
94 // key cannot contain specialChar but could be not a string
95 path.push(('' + key).replace(specialCharRG, safeSpecialChar));
96 mapp[i] = specialChar + path.join(specialChar);
97 } else {
98 mapp[i] = mapp[0];
99 }
100 } else {
101 value = mapp[i];
102 }
103 } else {
104 if (typeof value === 'string' && resolve) {
105 // ensure no special char involved on deserialization
106 // in this case only first char is important
107 // no need to replace all value (better performance)
108 value = value .replace(safeSpecialChar, escapedSafeSpecialChar)
109 .replace(specialChar, safeSpecialChar);
110 }
111 }
112 } else {
113 doNotIgnore = true;
114 }
115 return value;
116 };
117}
118
119function retrieveFromPath(current, keys) {
120 for(var i = 0, length = keys.length; i < length; current = current[
121 // keys should be normalized back here
122 keys[i++].replace(safeSpecialCharRG, specialChar)
123 ]);
124 return current;
125}
126
127function generateReviver(reviver) {
128 return function(key, value) {
129 var isString = typeof value === 'string';
130 if (isString && value.charAt(0) === specialChar) {
131 return new $String(value.slice(1));
132 }
133 if (key === '') value = regenerate(value, value, {});
134 // again, only one needed, do not use the RegExp for this replacement
135 // only keys need the RegExp
136 if (isString) value = value .replace(safeStartWithSpecialCharRG, '$1' + specialChar)
137 .replace(escapedSafeSpecialChar, safeSpecialChar);
138 return reviver ? reviver.call(this, key, value) : value;
139 };
140}
141
142function regenerateArray(root, current, retrieve) {
143 for (var i = 0, length = current.length; i < length; i++) {
144 current[i] = regenerate(root, current[i], retrieve);
145 }
146 return current;
147}
148
149function regenerateObject(root, current, retrieve) {
150 for (var key in current) {
151 if (current.hasOwnProperty(key)) {
152 current[key] = regenerate(root, current[key], retrieve);
153 }
154 }
155 return current;
156}
157
158function regenerate(root, current, retrieve) {
159 return current instanceof Array ?
160 // fast Array reconstruction
161 regenerateArray(root, current, retrieve) :
162 (
163 current instanceof $String ?
164 (
165 // root is an empty string
166 current.length ?
167 (
168 retrieve.hasOwnProperty(current) ?
169 retrieve[current] :
170 retrieve[current] = retrieveFromPath(
171 root, current.split(specialChar)
172 )
173 ) :
174 root
175 ) :
176 (
177 current instanceof Object ?
178 // dedicated Object parser
179 regenerateObject(root, current, retrieve) :
180 // value as it is
181 current
182 )
183 )
184 ;
185}
186
187var CircularJSON = {
188 stringify: function stringify(value, replacer, space, doNotResolve) {
189 return CircularJSON.parser.stringify(
190 value,
191 generateReplacer(value, replacer, !doNotResolve),
192 space
193 );
194 },
195 parse: function parse(text, reviver) {
196 return CircularJSON.parser.parse(
197 text,
198 generateReviver(reviver)
199 );
200 },
201 // A parser should be an API 1:1 compatible with JSON
202 // it should expose stringify and parse methods.
203 // The default parser is the native JSON.
204 parser: JSON
205};
206
207module.exports = CircularJSON;