modify-url-prefix-transform.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. /*
  3. Copyright 2018 Google LLC
  4. Use of this source code is governed by an MIT-style
  5. license that can be found in the LICENSE file or at
  6. https://opensource.org/licenses/MIT.
  7. */
  8. Object.defineProperty(exports, "__esModule", { value: true });
  9. exports.modifyURLPrefixTransform = void 0;
  10. const errors_1 = require("./errors");
  11. const escape_regexp_1 = require("./escape-regexp");
  12. function modifyURLPrefixTransform(modifyURLPrefix) {
  13. if (!modifyURLPrefix ||
  14. typeof modifyURLPrefix !== 'object' ||
  15. Array.isArray(modifyURLPrefix)) {
  16. throw new Error(errors_1.errors['modify-url-prefix-bad-prefixes']);
  17. }
  18. // If there are no entries in modifyURLPrefix, just return an identity
  19. // function as a shortcut.
  20. if (Object.keys(modifyURLPrefix).length === 0) {
  21. return (manifest) => {
  22. return { manifest };
  23. };
  24. }
  25. for (const key of Object.keys(modifyURLPrefix)) {
  26. if (typeof modifyURLPrefix[key] !== 'string') {
  27. throw new Error(errors_1.errors['modify-url-prefix-bad-prefixes']);
  28. }
  29. }
  30. // Escape the user input so it's safe to use in a regex.
  31. const safeModifyURLPrefixes = Object.keys(modifyURLPrefix).map(escape_regexp_1.escapeRegExp);
  32. // Join all the `modifyURLPrefix` keys so a single regex can be used.
  33. const prefixMatchesStrings = safeModifyURLPrefixes.join('|');
  34. // Add `^` to the front the prefix matches so it only matches the start of
  35. // a string.
  36. const modifyRegex = new RegExp(`^(${prefixMatchesStrings})`);
  37. return (originalManifest) => {
  38. const manifest = originalManifest.map((entry) => {
  39. if (typeof entry.url !== 'string') {
  40. throw new Error(errors_1.errors['manifest-entry-bad-url']);
  41. }
  42. entry.url = entry.url.replace(modifyRegex, (match) => {
  43. return modifyURLPrefix[match];
  44. });
  45. return entry;
  46. });
  47. return { manifest };
  48. };
  49. }
  50. exports.modifyURLPrefixTransform = modifyURLPrefixTransform;