summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab/tools/resourceUriPlugin.js
blob: 938822f410f785a19f3397853801cb31eec38f3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

// This plugin supports finding files with particular resource:// URIs
// and translating the uri into a relative filesytem path where the file may be
// found when running within the Karma / Mocha test framework.

module.exports = {
  ResourceUriPlugin: class ResourceUriPlugin {
    /**
     * @typedef {RegEx} ResourceReplacement0
     *   A regular expression matching a resource:// URI substring to be
     *   replaced.
     * @typedef {string} ResourceReplacement1
     *   A string to replace the matched substring with.
     * @typedef {[ResourceReplacement0, ResourceReplacement1]} ResourceReplacement
     */

    /**
     * Maps regular expressions representing resource URIs to strings that
     * should replace matches for those regular expressions.
     *
     * @type {ResourceReplacement[]}
     */
    #resourcePathRegExes;

    /**
     * @param {object} options
     * @param {ResourceReplacement[]} options.resourcePathRegExes
     *   An array of regex/string tuples to perform replacements on for
     *   imports involving resource:// URIs.
     */
    constructor({ resourcePathRegExes }) {
      this.#resourcePathRegExes = resourcePathRegExes;
    }

    apply(compiler) {
      compiler.hooks.compilation.tap(
        "ResourceUriPlugin",
        (compilation, { normalModuleFactory }) => {
          normalModuleFactory.hooks.resolveForScheme
            .for("resource")
            .tap("ResourceUriPlugin", resourceData => {
              const url = new URL(resourceData.resource);

              for (let [regex, replacement] of this.#resourcePathRegExes) {
                if (!url.href.match(regex)) {
                  continue;
                }
                const pathname = url.href.replace(regex, replacement);
                resourceData.path = pathname;
                resourceData.query = url.search;
                resourceData.fragment = url.hash;
                resourceData.resource = pathname + url.search + url.hash;
                return true;
              }

              return true;
            });
        }
      );
    }
  },
};