Allow only one bookmark to be added for multiple fast starring
[chromium-blink-merge.git] / chrome / browser / resources / chromeos / chromevox / common / chromevox_json.js
blob96c78ca9f31ed05da13d6217c3e39d17f5846233
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 goog.provide('cvox.ChromeVoxJSON');
8 /**
9 * @fileoverview A simple wrapper around the JSON APIs.
10 * If it is possible to use the browser's built in native JSON, then
11 * cvox.ChromeVoxJSON is the same as JSON.
12 * If the page has its own version of JSON, cvox.ChromeVoxJSON will use its
13 * own implementation (rather than the version of JSON on the page
14 * which may be outdated/broken).
17 if (!cvox.ChromeVoxJSON) {
18 /** Placeholder object. */
19 cvox.ChromeVoxJSON = {};
22 if (window.JSON && window.JSON.toString() == '[object JSON]') {
23 cvox.ChromeVoxJSON = window.JSON;
24 } else {
26 * JSON implementation renamed to cvox.ChromeVoxJSON.
27 * This only gets called if the page has its own version of JSON.
29 * Based on:
30 * http://www.JSON.org/json2.js
31 * 2010-03-20
33 * Public Domain.
35 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
37 * See http://www.JSON.org/js.html
39 (function() {
40 function f(n) {
41 // Format integers to have at least two digits.
42 return n < 10 ? '0' + n : n;
45 if (typeof Date.prototype.toJSON !== 'function') {
47 Date.prototype.toJSON = function(key) {
49 return isFinite(this.valueOf()) ?
50 this.getUTCFullYear() + '-' +
51 f(this.getUTCMonth() + 1) + '-' +
52 f(this.getUTCDate()) + 'T' +
53 f(this.getUTCHours()) + ':' +
54 f(this.getUTCMinutes()) + ':' +
55 f(this.getUTCSeconds()) + 'Z' : 'null';
58 String.prototype.toJSON =
59 Number.prototype.toJSON =
60 Boolean.prototype.toJSON = function(key) {
61 return /** @type {string} */ (this.valueOf());
65 var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
66 escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
67 gap,
68 indent,
69 meta = { // table of character substitutions
70 '\b': '\\b',
71 '\t': '\\t',
72 '\n': '\\n',
73 '\f': '\\f',
74 '\r': '\\r',
75 '"' : '\\"',
76 '\\': '\\\\'
78 rep;
81 function quote(string) {
83 // If the string contains no control characters, no quote characters, and
84 // no backslash characters, then we can safely slap some quotes around it.
85 // Otherwise we must also replace the offending characters with safe
86 // escape sequences.
88 escapable.lastIndex = 0;
89 return escapable.test(string) ?
90 '"' + string.replace(escapable, function(a) {
91 var c = meta[a];
92 return typeof c === 'string' ? c :
93 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
94 }) + '"' :
95 '"' + string + '"';
99 function str(key, holder) {
101 // Produce a string from holder[key].
103 var i, // The loop counter.
104 k, // The member key.
105 v, // The member value.
106 length,
107 mind = gap,
108 partial,
109 value = holder[key];
111 // If the value has a toJSON method, call it to obtain a replacement
112 // value.
114 if (value && typeof value === 'object' &&
115 typeof value.toJSON === 'function') {
116 value = value.toJSON(key);
119 // If we were called with a replacer function, then call the replacer to
120 // obtain a replacement value.
122 if (typeof rep === 'function') {
123 value = rep.call(holder, key, value);
126 // What happens next depends on the value's type.
128 switch (typeof value) {
129 case 'string':
130 return quote(value);
132 case 'number':
133 // JSON numbers must be finite. Encode non-finite numbers as null.
134 return isFinite(value) ? String(value) : 'null';
136 case 'boolean':
137 case 'null':
138 // If the value is a boolean or null, convert it to a string. Note:
139 // typeof null does not produce 'null'. The case is included here in
140 // the remote chance that this gets fixed someday.
141 return String(value);
143 // If the type is 'object', we might be dealing with an object or an
144 // array or null.
146 case 'object':
148 // Due to a specification blunder in ECMAScript, typeof null is
149 // 'object', so watch out for that case.
151 if (!value) {
152 return 'null';
155 // Make an array to hold the partial results of stringifying this
156 // object value.
158 gap += indent;
159 partial = [];
161 // Is the value an array?
163 if (Object.prototype.toString.apply(value) === '[object Array]') {
165 // The value is an array. Stringify every element. Use null as a
166 // placeholder for non-JSON values.
168 length = value.length;
169 for (i = 0; i < length; i += 1) {
170 partial[i] = str(i, value) || 'null';
173 // Join all of the elements together, separated with commas, and
174 // wrap them in brackets.
176 v = partial.length === 0 ? '[]' :
177 gap ? '[\n' + gap +
178 partial.join(',\n' + gap) + '\n' +
179 mind + ']' :
180 '[' + partial.join(',') + ']';
181 gap = mind;
182 return v;
185 // If the replacer is an array, use it to select the members to be
186 // stringified.
188 if (rep && typeof rep === 'object') {
189 length = rep.length;
190 for (i = 0; i < length; i += 1) {
191 k = rep[i];
192 if (typeof k === 'string') {
193 v = str(k, value);
194 if (v) {
195 partial.push(quote(k) + (gap ? ': ' : ':') + v);
199 } else {
201 // Otherwise, iterate through all of the keys in the object.
202 for (k in value) {
203 if (Object.hasOwnProperty.call(value, k)) {
204 v = str(k, value);
205 if (v) {
206 partial.push(quote(k) + (gap ? ': ' : ':') + v);
212 // Join all of the member texts together, separated with commas,
213 // and wrap them in braces.
215 v = partial.length === 0 ? '{}' :
216 gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
217 mind + '}' : '{' + partial.join(',') + '}';
218 gap = mind;
219 return v;
223 // If the JSON object does not yet have a stringify method, give it one.
225 if (typeof cvox.ChromeVoxJSON.stringify !== 'function') {
227 * @param {*} value Input object.
228 * @param {(Array<string>|(function(string, *) : *)|null)=} replacer
229 * Replacer array or function.
230 * @param {(number|string|null)=} space Whitespace character.
231 * @return {string} json string which represents jsonObj.
233 cvox.ChromeVoxJSON.stringify = function(value, replacer, space) {
235 // The stringify method takes a value and an optional replacer, and an
236 // optional space parameter, and returns a JSON text. The replacer can
237 // be a function that can replace values, or an array of strings that
238 // will select the keys. A default replacer method can be provided. Use
239 // of the space parameter can produce text that is more easily readable.
241 var i;
242 gap = '';
243 indent = '';
245 // If the space parameter is a number, make an indent string containing
246 // that many spaces.
248 if (typeof space === 'number') {
249 for (i = 0; i < space; i += 1) {
250 indent += ' ';
253 // If the space parameter is a string, it will be used as the indent
254 // string.
256 } else if (typeof space === 'string') {
257 indent = space;
260 // If there is a replacer, it must be a function or an array.
261 // Otherwise, throw an error.
263 rep = replacer;
264 if (replacer && typeof replacer !== 'function' &&
265 (typeof replacer !== 'object' ||
266 typeof replacer.length !== 'number')) {
267 throw new Error('JSON.stringify');
270 // Make a fake root object containing our value under the key of ''.
271 // Return the result of stringifying the value.
273 return str('', {'': value});
278 // If the JSON object does not yet have a parse method, give it one.
280 if (typeof cvox.ChromeVoxJSON.parse !== 'function') {
282 * @param {string} text The string to parse.
283 * @param {(function(string, *) : *|null)=} reviver Reviver function.
284 * @return {*} The JSON object.
286 cvox.ChromeVoxJSON.parse = function(text, reviver) {
288 // The parse method takes a text and an optional reviver function, and
289 // returns a JavaScript value if the text is a valid JSON text.
291 var j;
293 function walk(holder, key) {
295 // The walk method is used to recursively walk the resulting structure
296 // so that modifications can be made.
298 var k, v, value = holder[key];
299 if (value && typeof value === 'object') {
300 for (k in value) {
301 if (Object.hasOwnProperty.call(value, k)) {
302 v = walk(value, k);
303 if (v !== undefined) {
304 value[k] = v;
305 } else {
306 delete value[k];
311 return reviver.call(holder, key, value);
315 // Parsing happens in four stages. In the first stage, we replace
316 // certain Unicode characters with escape sequences. JavaScript handles
317 // many characters incorrectly, either silently deleting them, or
318 // treating them as line endings.
320 text = String(text);
321 cx.lastIndex = 0;
322 if (cx.test(text)) {
323 text = text.replace(cx, function(a) {
324 return '\\u' +
325 ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
329 // In the second stage, we run the text against regular expressions that
330 // look for non-JSON patterns. We are especially concerned with '()' and
331 // 'new' because they can cause invocation, and '=' because it can cause
332 // mutation. But just to be safe, we want to reject all unexpected
333 // forms.
334 // We split the second stage into 4 regexp operations in order to work
335 // around crippling inefficiencies in IE's and Safari's regexp engines.
336 // First we replace the JSON backslash pairs with '@' (a non-JSON
337 // character). Second, we replace all simple value tokens with ']'
338 // characters. Third, we delete all open brackets that follow a colon or
339 // comma or that begin the text. Finally, we look to see that the
340 // remaining characters are only whitespace or ']' or ',' or ':' or '{'
341 // or '}'. If that is so, then the text is safe for eval.
343 if (/^[\],:{}\s]*$/.
344 test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
345 replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
346 replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
348 // In the third stage we use the eval function to compile the text
349 // into a JavaScript structure. The '{' operator is subject to a
350 // syntactic ambiguity in JavaScript: it can begin a block or an
351 // object literal. We wrap the text in parens to eliminate the
352 // ambiguity.
354 j = eval('(' + text + ')');
356 // In the optional fourth stage, we recursively walk the new
357 // structure, passing each name/value pair to a reviver function for
358 // possible transformation.
359 return typeof reviver === 'function' ? walk({'': j}, '') : j;
362 // If the text is not JSON parseable, then a SyntaxError is thrown.
364 throw new SyntaxError('JSON.parse');
367 }());