write-sw-using-default-template.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 fse = require('fs-extra');
  9. const upath = require('upath');
  10. const bundle = require('./bundle');
  11. const errors = require('./errors');
  12. const populateSWTemplate = require('./populate-sw-template');
  13. module.exports = async ({
  14. babelPresetEnvTargets,
  15. cacheId,
  16. cleanupOutdatedCaches,
  17. clientsClaim,
  18. directoryIndex,
  19. disableDevLogs,
  20. ignoreURLParametersMatching,
  21. importScripts,
  22. inlineWorkboxRuntime,
  23. manifestEntries,
  24. mode,
  25. navigateFallback,
  26. navigateFallbackDenylist,
  27. navigateFallbackAllowlist,
  28. navigationPreload,
  29. offlineGoogleAnalytics,
  30. runtimeCaching,
  31. skipWaiting,
  32. sourcemap,
  33. swDest
  34. }) => {
  35. const outputDir = upath.dirname(swDest);
  36. try {
  37. await fse.mkdirp(outputDir);
  38. } catch (error) {
  39. throw new Error(`${errors['unable-to-make-sw-directory']}. ` + `'${error.message}'`);
  40. }
  41. const unbundledCode = populateSWTemplate({
  42. cacheId,
  43. cleanupOutdatedCaches,
  44. clientsClaim,
  45. directoryIndex,
  46. disableDevLogs,
  47. ignoreURLParametersMatching,
  48. importScripts,
  49. manifestEntries,
  50. navigateFallback,
  51. navigateFallbackDenylist,
  52. navigateFallbackAllowlist,
  53. navigationPreload,
  54. offlineGoogleAnalytics,
  55. runtimeCaching,
  56. skipWaiting
  57. });
  58. try {
  59. const files = await bundle({
  60. babelPresetEnvTargets,
  61. inlineWorkboxRuntime,
  62. mode,
  63. sourcemap,
  64. swDest,
  65. unbundledCode
  66. });
  67. const filePaths = [];
  68. for (const file of files) {
  69. const filePath = upath.resolve(file.name);
  70. filePaths.push(filePath);
  71. await fse.writeFile(filePath, file.contents);
  72. }
  73. return filePaths;
  74. } catch (error) {
  75. if (error.code === 'EISDIR') {
  76. // See https://github.com/GoogleChrome/workbox/issues/612
  77. throw new Error(errors['sw-write-failure-directory']);
  78. }
  79. throw new Error(`${errors['sw-write-failure']} '${error.message}'`);
  80. }
  81. };