UNPKG

9.86 kBJavaScriptView Raw
1'use strict';
2
3var consola = require('consola');
4var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
5var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
6var reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
7var escaped = {
8 '<': '\\u003C',
9 '>': '\\u003E',
10 '/': '\\u002F',
11 '\\': '\\\\',
12 '\b': '\\b',
13 '\f': '\\f',
14 '\n': '\\n',
15 '\r': '\\r',
16 '\t': '\\t',
17 '\0': '\\0',
18 '\u2028': '\\u2028',
19 '\u2029': '\\u2029'
20};
21var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
22// workaround to disable warnings, see https://github.com/nuxt/nuxt.js/issues/4026 for details
23var defaultLogLevel = process.env.NUXT_ENV_DEVALUE_LOG_LEVEL || 'warn';
24var logLimit = parseInt(process.env.NUXT_ENV_DEVALUE_LOG_LIMIT) || 99;
25function devalue(value, level) {
26 if (level === void 0) { level = defaultLogLevel; }
27 var counts = new Map();
28 var logNum = 0;
29 function log(message) {
30 if (logNum < logLimit) {
31 consola[level](message);
32 logNum += 1;
33 }
34 }
35 function walk(thing) {
36 if (typeof thing === 'function') {
37 consola[level]("Cannot stringify a function " + thing.name);
38 return;
39 }
40 if (counts.has(thing)) {
41 counts.set(thing, counts.get(thing) + 1);
42 return;
43 }
44 counts.set(thing, 1);
45 if (!isPrimitive(thing)) {
46 var type = getType(thing);
47 switch (type) {
48 case 'Number':
49 case 'String':
50 case 'Boolean':
51 case 'Date':
52 case 'RegExp':
53 return;
54 case 'Array':
55 thing.forEach(walk);
56 break;
57 case 'Set':
58 case 'Map':
59 Array.from(thing).forEach(walk);
60 break;
61 default:
62 var proto = Object.getPrototypeOf(thing);
63 if (proto !== Object.prototype &&
64 proto !== null &&
65 Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
66 if (typeof thing.toJSON !== "function") {
67 log("Cannot stringify arbitrary non-POJOs " + thing.constructor.name);
68 }
69 }
70 else if (Object.getOwnPropertySymbols(thing).length > 0) {
71 log("Cannot stringify POJOs with symbolic keys " + Object.getOwnPropertySymbols(thing).map(function (symbol) { return symbol.toString(); }));
72 }
73 else {
74 Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
75 }
76 }
77 }
78 }
79 walk(value);
80 var names = new Map();
81 Array.from(counts)
82 .filter(function (entry) { return entry[1] > 1; })
83 .sort(function (a, b) { return b[1] - a[1]; })
84 .forEach(function (entry, i) {
85 names.set(entry[0], getName(i));
86 });
87 function stringify(thing) {
88 if (names.has(thing)) {
89 return names.get(thing);
90 }
91 if (isPrimitive(thing)) {
92 return stringifyPrimitive(thing);
93 }
94 var type = getType(thing);
95 switch (type) {
96 case 'Number':
97 case 'String':
98 case 'Boolean':
99 return "Object(" + stringify(thing.valueOf()) + ")";
100 case 'RegExp':
101 return thing.toString();
102 case 'Date':
103 return "new Date(" + thing.getTime() + ")";
104 case 'Array':
105 var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
106 var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
107 return "[" + members.join(',') + tail + "]";
108 case 'Set':
109 case 'Map':
110 return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
111 default:
112 if (thing.toJSON) {
113 var json = thing.toJSON();
114 if (getType(json) === 'String') {
115 // Try to parse the returned data
116 try {
117 json = JSON.parse(json);
118 }
119 catch (e) { }
120 }
121 return stringify(json);
122 }
123 if (Object.getPrototypeOf(thing) === null) {
124 if (Object.keys(thing).length === 0) {
125 return 'Object.create(null)';
126 }
127 return "Object.create(null,{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":{writable:true,enumerable:true,value:" + stringify(thing[key]) + "}"; }).join(',') + "})";
128 }
129 return "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
130 }
131 }
132 var str = stringify(value);
133 if (names.size) {
134 var params_1 = [];
135 var statements_1 = [];
136 var values_1 = [];
137 names.forEach(function (name, thing) {
138 params_1.push(name);
139 if (isPrimitive(thing)) {
140 values_1.push(stringifyPrimitive(thing));
141 return;
142 }
143 var type = getType(thing);
144 switch (type) {
145 case 'Number':
146 case 'String':
147 case 'Boolean':
148 values_1.push("Object(" + stringify(thing.valueOf()) + ")");
149 break;
150 case 'RegExp':
151 values_1.push(thing.toString());
152 break;
153 case 'Date':
154 values_1.push("new Date(" + thing.getTime() + ")");
155 break;
156 case 'Array':
157 values_1.push("Array(" + thing.length + ")");
158 thing.forEach(function (v, i) {
159 statements_1.push(name + "[" + i + "]=" + stringify(v));
160 });
161 break;
162 case 'Set':
163 values_1.push("new Set");
164 statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
165 break;
166 case 'Map':
167 values_1.push("new Map");
168 statements_1.push(name + "." + Array.from(thing).map(function (_a) {
169 var k = _a[0], v = _a[1];
170 return "set(" + stringify(k) + ", " + stringify(v) + ")";
171 }).join('.'));
172 break;
173 default:
174 values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
175 Object.keys(thing).forEach(function (key) {
176 statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
177 });
178 }
179 });
180 statements_1.push("return " + str);
181 return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
182 }
183 else {
184 return str;
185 }
186}
187function getName(num) {
188 var name = '';
189 do {
190 name = chars[num % chars.length] + name;
191 num = ~~(num / chars.length) - 1;
192 } while (num >= 0);
193 return reserved.test(name) ? name + "_" : name;
194}
195function isPrimitive(thing) {
196 return Object(thing) !== thing;
197}
198function stringifyPrimitive(thing) {
199 if (typeof thing === 'string')
200 return stringifyString(thing);
201 if (thing === void 0)
202 return 'void 0';
203 if (thing === 0 && 1 / thing < 0)
204 return '-0';
205 var str = String(thing);
206 if (typeof thing === 'number')
207 return str.replace(/^(-)?0\./, '$1.');
208 return str;
209}
210function getType(thing) {
211 return Object.prototype.toString.call(thing).slice(8, -1);
212}
213function escapeUnsafeChar(c) {
214 return escaped[c] || c;
215}
216function escapeUnsafeChars(str) {
217 return str.replace(unsafeChars, escapeUnsafeChar);
218}
219function safeKey(key) {
220 return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify((key)));
221}
222function safeProp(key) {
223 return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
224}
225function stringifyString(str) {
226 var result = '"';
227 for (var i = 0; i < str.length; i += 1) {
228 var char = str.charAt(i);
229 var code = char.charCodeAt(0);
230 if (char === '"') {
231 result += '\\"';
232 }
233 else if (char in escaped) {
234 result += escaped[char];
235 }
236 else if (code >= 0xd800 && code <= 0xdfff) {
237 var next = str.charCodeAt(i + 1);
238 // If this is the beginning of a [high, low] surrogate pair,
239 // add the next two characters, otherwise escape
240 if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
241 result += char + str[++i];
242 }
243 else {
244 result += "\\u" + code.toString(16).toUpperCase();
245 }
246 }
247 else {
248 result += char;
249 }
250 }
251 result += '"';
252 return result;
253}
254
255module.exports = devalue;