modify-url-prefix-transform.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. const errors = require('./errors');
  9. const escapeRegExp = require('./escape-regexp');
  10. module.exports = modifyURLPrefix => {
  11. if (!modifyURLPrefix || typeof modifyURLPrefix !== 'object' || Array.isArray(modifyURLPrefix)) {
  12. throw new Error(errors['modify-url-prefix-bad-prefixes']);
  13. } // If there are no entries in modifyURLPrefix, just return an identity
  14. // function as a shortcut.
  15. if (Object.keys(modifyURLPrefix).length === 0) {
  16. return entry => entry;
  17. }
  18. Object.keys(modifyURLPrefix).forEach(key => {
  19. if (typeof modifyURLPrefix[key] !== 'string') {
  20. throw new Error(errors['modify-url-prefix-bad-prefixes']);
  21. }
  22. }); // Escape the user input so it's safe to use in a regex.
  23. const safeModifyURLPrefixes = Object.keys(modifyURLPrefix).map(escapeRegExp); // Join all the `modifyURLPrefix` keys so a single regex can be used.
  24. const prefixMatchesStrings = safeModifyURLPrefixes.join('|'); // Add `^` to the front the prefix matches so it only matches the start of
  25. // a string.
  26. const modifyRegex = new RegExp(`^(${prefixMatchesStrings})`);
  27. return originalManifest => {
  28. const manifest = originalManifest.map(entry => {
  29. if (typeof entry.url !== 'string') {
  30. throw new Error(errors['manifest-entry-bad-url']);
  31. }
  32. entry.url = entry.url.replace(modifyRegex, match => {
  33. return modifyURLPrefix[match];
  34. });
  35. return entry;
  36. });
  37. return {
  38. manifest
  39. };
  40. };
  41. };