Bug 1838365 add some DecodedStream finished logging r=pehrsons,media-playback-reviewe...
[gecko.git] / toolkit / modules / CanonicalJSON.sys.mjs
blob07ee318895173041ed4195f2a1aaaf6f792693e7
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3  * You can obtain one at http://mozilla.org/MPL/2.0/. */
5 export var CanonicalJSON = {
6   /**
7    * Return the canonical JSON form of the passed source, sorting all the object
8    * keys recursively. Note that this method will cause an infinite loop if
9    * cycles exist in the source (bug 1265357).
10    *
11    * @param source
12    *        The elements to be serialized.
13    *
14    * The output will have all unicode chars escaped with the unicode codepoint
15    * as lowercase hexadecimal.
16    *
17    * @usage
18    *        CanonicalJSON.stringify(listOfRecords);
19    **/
20   stringify: function stringify(source, jsescFn) {
21     if (typeof jsescFn != "function") {
22       const { jsesc } = ChromeUtils.importESModule(
23         "resource://gre/modules/third_party/jsesc/jsesc.mjs"
24       );
25       jsescFn = jsesc;
26     }
27     if (Array.isArray(source)) {
28       const jsonArray = source.map(x => (typeof x === "undefined" ? null : x));
29       return (
30         "[" + jsonArray.map(item => stringify(item, jsescFn)).join(",") + "]"
31       );
32     }
34     if (typeof source === "number") {
35       if (source === 0) {
36         return Object.is(source, -0) ? "-0" : "0";
37       }
38     }
40     // Leverage jsesc library, mainly for unicode escaping.
41     const toJSON = input => jsescFn(input, { lowercaseHex: true, json: true });
43     if (typeof source !== "object" || source === null) {
44       return toJSON(source);
45     }
47     // Dealing with objects, ordering keys.
48     const sortedKeys = Object.keys(source).sort();
49     const lastIndex = sortedKeys.length - 1;
50     return (
51       sortedKeys.reduce((serial, key, index) => {
52         const value = source[key];
53         // JSON.stringify drops keys with an undefined value.
54         if (typeof value === "undefined") {
55           return serial;
56         }
57         const jsonValue = value && value.toJSON ? value.toJSON() : value;
58         const suffix = index !== lastIndex ? "," : "";
59         const escapedKey = toJSON(key);
60         return (
61           serial + escapedKey + ":" + stringify(jsonValue, jsescFn) + suffix
62         );
63       }, "{") + "}"
64     );
65   },