module-registry.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. "use strict";
  2. /*
  3. Copyright 2019 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. var __importDefault = (this && this.__importDefault) || function (mod) {
  9. return (mod && mod.__esModule) ? mod : { "default": mod };
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.ModuleRegistry = void 0;
  13. const common_tags_1 = require("common-tags");
  14. const upath_1 = __importDefault(require("upath"));
  15. /**
  16. * Class for keeping track of which Workbox modules are used by the generated
  17. * service worker script.
  18. *
  19. * @private
  20. */
  21. class ModuleRegistry {
  22. /**
  23. * @private
  24. */
  25. constructor() {
  26. this._modulesUsed = new Map();
  27. }
  28. /**
  29. * @return {Array<string>} A list of all of the import statements that are
  30. * needed for the modules being used.
  31. * @private
  32. */
  33. getImportStatements() {
  34. const workboxModuleImports = [];
  35. for (const [localName, { moduleName, pkg }] of this._modulesUsed) {
  36. // By default require.resolve returns the resolved path of the 'main'
  37. // field, which might be deeper than the package root. To work around
  38. // this, we can find the package's root by resolving its package.json and
  39. // strip the '/package.json' from the resolved path.
  40. const pkgJsonPath = require.resolve(`${pkg}/package.json`);
  41. const pkgRoot = upath_1.default.dirname(pkgJsonPath);
  42. const importStatement = (0, common_tags_1.oneLine) `import {${moduleName} as ${localName}} from
  43. '${pkgRoot}/${moduleName}.mjs';`;
  44. workboxModuleImports.push(importStatement);
  45. }
  46. return workboxModuleImports;
  47. }
  48. /**
  49. * @param {string} pkg The workbox package that the module belongs to.
  50. * @param {string} moduleName The name of the module to import.
  51. * @return {string} The local variable name that corresponds to that module.
  52. * @private
  53. */
  54. getLocalName(pkg, moduleName) {
  55. return `${pkg.replace(/-/g, '_')}_${moduleName}`;
  56. }
  57. /**
  58. * @param {string} pkg The workbox package that the module belongs to.
  59. * @param {string} moduleName The name of the module to import.
  60. * @return {string} The local variable name that corresponds to that module.
  61. * @private
  62. */
  63. use(pkg, moduleName) {
  64. const localName = this.getLocalName(pkg, moduleName);
  65. this._modulesUsed.set(localName, { moduleName, pkg });
  66. return localName;
  67. }
  68. }
  69. exports.ModuleRegistry = ModuleRegistry;