Bug 1696969 [wpt PR 27896] - Allow fuzzy matching for replaced-element-003, a=testonly
[gecko.git] / services / settings / SharedUtils.jsm
blobdb5017a742f44b60e61f61d9a59559ab7da195c5
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
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 /**
6  * Common logic shared by RemoteSettingsWorker.js (Worker) and the main thread.
7  */
9 var EXPORTED_SYMBOLS = ["SharedUtils"];
11 // Import globals that are available by default in workers but not in JSMs.
12 if (typeof crypto == "undefined") {
13   Cu.importGlobalProperties(["fetch", "crypto"]);
16 var SharedUtils = {
17   /**
18    * Check that the specified content matches the expected size and SHA-256 hash.
19    * @param {ArrayBuffer} buffer binary content
20    * @param {Number} size expected file size
21    * @param {String} size expected file SHA-256 as hex string
22    * @returns {boolean}
23    */
24   async checkContentHash(buffer, size, hash) {
25     const bytes = new Uint8Array(buffer);
26     // Has expected size? (saves computing hash)
27     if (bytes.length !== size) {
28       return false;
29     }
30     // Has expected content?
31     const hashBuffer = await crypto.subtle.digest("SHA-256", bytes);
32     const hashBytes = new Uint8Array(hashBuffer);
33     const toHex = b => b.toString(16).padStart(2, "0");
34     const hashStr = Array.from(hashBytes, toHex).join("");
35     return hashStr == hash;
36   },
38   /**
39    * Load (from disk) the JSON file distributed with the release for this collection.
40    * @param {String}  bucket
41    * @param {String}  collection
42    */
43   async loadJSONDump(bucket, collection) {
44     // When using the preview bucket, we still want to load the main dump.
45     // But we store it locally in the preview bucket.
46     const jsonBucket = bucket.replace("-preview", "");
47     const fileURI = `resource://app/defaults/settings/${jsonBucket}/${collection}.json`;
48     let response;
49     try {
50       response = await fetch(fileURI);
51     } catch (e) {
52       // Return null if file is missing.
53       return { data: null };
54     }
55     // Will throw if JSON is invalid.
56     return response.json();
57   },