WorkboxSW.mjs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /*
  2. Copyright 2018 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import '../_version.mjs';
  8. const CDN_PATH = `WORKBOX_CDN_ROOT_URL`;
  9. const MODULE_KEY_TO_NAME_MAPPING = {
  10. /**
  11. * @name backgroundSync
  12. * @memberof workbox
  13. * @see module:workbox-background-sync
  14. */
  15. backgroundSync: 'background-sync',
  16. /**
  17. * @name broadcastUpdate
  18. * @memberof workbox
  19. * @see module:workbox-broadcast-update
  20. */
  21. broadcastUpdate: 'broadcast-update',
  22. /**
  23. * @name cacheableResponse
  24. * @memberof workbox
  25. * @see module:workbox-cacheable-response
  26. */
  27. cacheableResponse: 'cacheable-response',
  28. /**
  29. * @name core
  30. * @memberof workbox
  31. * @see module:workbox-core
  32. */
  33. core: 'core',
  34. /**
  35. * @name expiration
  36. * @memberof workbox
  37. * @see module:workbox-expiration
  38. */
  39. expiration: 'expiration',
  40. /**
  41. * @name googleAnalytics
  42. * @memberof workbox
  43. * @see module:workbox-google-analytics
  44. */
  45. googleAnalytics: 'offline-ga',
  46. /**
  47. * @name navigationPreload
  48. * @memberof workbox
  49. * @see module:workbox-navigation-preload
  50. */
  51. navigationPreload: 'navigation-preload',
  52. /**
  53. * @name precaching
  54. * @memberof workbox
  55. * @see module:workbox-precaching
  56. */
  57. precaching: 'precaching',
  58. /**
  59. * @name rangeRequests
  60. * @memberof workbox
  61. * @see module:workbox-range-requests
  62. */
  63. rangeRequests: 'range-requests',
  64. /**
  65. * @name routing
  66. * @memberof workbox
  67. * @see module:workbox-routing
  68. */
  69. routing: 'routing',
  70. /**
  71. * @name strategies
  72. * @memberof workbox
  73. * @see module:workbox-strategies
  74. */
  75. strategies: 'strategies',
  76. /**
  77. * @name streams
  78. * @memberof workbox
  79. * @see module:workbox-streams
  80. */
  81. streams: 'streams',
  82. };
  83. /**
  84. * This class can be used to make it easy to use the various parts of
  85. * Workbox.
  86. *
  87. * @private
  88. */
  89. export class WorkboxSW {
  90. /**
  91. * Creates a proxy that automatically loads workbox namespaces on demand.
  92. *
  93. * @private
  94. */
  95. constructor() {
  96. this.v = {};
  97. this._options = {
  98. debug: self.location.hostname === 'localhost',
  99. modulePathPrefix: null,
  100. modulePathCb: null,
  101. };
  102. this._env = this._options.debug ? 'dev' : 'prod';
  103. this._modulesLoaded = false;
  104. return new Proxy(this, {
  105. get(target, key) {
  106. if (target[key]) {
  107. return target[key];
  108. }
  109. const moduleName = MODULE_KEY_TO_NAME_MAPPING[key];
  110. if (moduleName) {
  111. target.loadModule(`workbox-${moduleName}`);
  112. }
  113. return target[key];
  114. },
  115. });
  116. }
  117. /**
  118. * Updates the configuration options. You can specify whether to treat as a
  119. * debug build and whether to use a CDN or a specific path when importing
  120. * other workbox-modules
  121. *
  122. * @param {Object} [options]
  123. * @param {boolean} [options.debug] If true, `dev` builds are using, otherwise
  124. * `prod` builds are used. By default, `prod` is used unless on localhost.
  125. * @param {Function} [options.modulePathPrefix] To avoid using the CDN with
  126. * `workbox-sw` set the path prefix of where modules should be loaded from.
  127. * For example `modulePathPrefix: '/third_party/workbox/v3.0.0/'`.
  128. * @param {workbox~ModulePathCallback} [options.modulePathCb] If defined,
  129. * this callback will be responsible for determining the path of each
  130. * workbox module.
  131. *
  132. * @alias workbox.setConfig
  133. */
  134. setConfig(options = {}) {
  135. if (!this._modulesLoaded) {
  136. Object.assign(this._options, options);
  137. this._env = this._options.debug ? 'dev' : 'prod';
  138. } else {
  139. throw new Error('Config must be set before accessing workbox.* modules');
  140. }
  141. }
  142. /**
  143. * Load a Workbox module by passing in the appropriate module name.
  144. *
  145. * This is not generally needed unless you know there are modules that are
  146. * dynamically used and you want to safe guard use of the module while the
  147. * user may be offline.
  148. *
  149. * @param {string} moduleName
  150. *
  151. * @alias workbox.loadModule
  152. */
  153. loadModule(moduleName) {
  154. const modulePath = this._getImportPath(moduleName);
  155. try {
  156. importScripts(modulePath);
  157. this._modulesLoaded = true;
  158. } catch (err) {
  159. // TODO Add context of this error if using the CDN vs the local file.
  160. // We can't rely on workbox-core being loaded so using console
  161. // eslint-disable-next-line
  162. console.error(
  163. `Unable to import module '${moduleName}' from '${modulePath}'.`);
  164. throw err;
  165. }
  166. }
  167. /**
  168. * This method will get the path / CDN URL to be used for importScript calls.
  169. *
  170. * @param {string} moduleName
  171. * @return {string} URL to the desired module.
  172. *
  173. * @private
  174. */
  175. _getImportPath(moduleName) {
  176. if (this._options.modulePathCb) {
  177. return this._options.modulePathCb(moduleName, this._options.debug);
  178. }
  179. // TODO: This needs to be dynamic some how.
  180. let pathParts = [CDN_PATH];
  181. const fileName = `${moduleName}.${this._env}.js`;
  182. const pathPrefix = this._options.modulePathPrefix;
  183. if (pathPrefix) {
  184. // Split to avoid issues with developers ending / not ending with slash
  185. pathParts = pathPrefix.split('/');
  186. // We don't need a slash at the end as we will be adding
  187. // a filename regardless
  188. if (pathParts[pathParts.length - 1] === '') {
  189. pathParts.splice(pathParts.length - 1, 1);
  190. }
  191. }
  192. pathParts.push(fileName);
  193. return pathParts.join('/');
  194. }
  195. }