inject-manifest.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. 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.InjectManifest = void 0;
  13. const escape_regexp_1 = require("workbox-build/build/lib/escape-regexp");
  14. const replace_and_update_source_map_1 = require("workbox-build/build/lib/replace-and-update-source-map");
  15. const validate_options_1 = require("workbox-build/build/lib/validate-options");
  16. const pretty_bytes_1 = __importDefault(require("pretty-bytes"));
  17. const fast_json_stable_stringify_1 = __importDefault(require("fast-json-stable-stringify"));
  18. const upath_1 = __importDefault(require("upath"));
  19. const webpack_1 = __importDefault(require("webpack"));
  20. const get_manifest_entries_from_compilation_1 = require("./lib/get-manifest-entries-from-compilation");
  21. const get_sourcemap_asset_name_1 = require("./lib/get-sourcemap-asset-name");
  22. const relative_to_output_path_1 = require("./lib/relative-to-output-path");
  23. // Used to keep track of swDest files written by *any* instance of this plugin.
  24. // See https://github.com/GoogleChrome/workbox/issues/2181
  25. const _generatedAssetNames = new Set();
  26. // SingleEntryPlugin in v4 was renamed to EntryPlugin in v5.
  27. const SingleEntryPlugin = webpack_1.default.EntryPlugin || webpack_1.default.SingleEntryPlugin;
  28. // webpack v4/v5 compatibility:
  29. // https://github.com/webpack/webpack/issues/11425#issuecomment-686607633
  30. const { RawSource } = webpack_1.default.sources || require('webpack-sources');
  31. /**
  32. * This class supports compiling a service worker file provided via `swSrc`,
  33. * and injecting into that service worker a list of URLs and revision
  34. * information for precaching based on the webpack asset pipeline.
  35. *
  36. * Use an instance of `InjectManifest` in the
  37. * [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
  38. * webpack config.
  39. *
  40. * In addition to injecting the manifest, this plugin will perform a compilation
  41. * of the `swSrc` file, using the options from the main webpack configuration.
  42. *
  43. * ```
  44. * // The following lists some common options; see the rest of the documentation
  45. * // for the full set of options and defaults.
  46. * new InjectManifest({
  47. * exclude: [/.../, '...'],
  48. * maximumFileSizeToCacheInBytes: ...,
  49. * swSrc: '...',
  50. * });
  51. * ```
  52. *
  53. * @memberof module:workbox-webpack-plugin
  54. */
  55. class InjectManifest {
  56. /**
  57. * Creates an instance of InjectManifest.
  58. */
  59. constructor(config) {
  60. this.config = config;
  61. this.alreadyCalled = false;
  62. }
  63. /**
  64. * @param {Object} [compiler] default compiler object passed from webpack
  65. *
  66. * @private
  67. */
  68. propagateWebpackConfig(compiler) {
  69. // Because this.config is listed last, properties that are already set
  70. // there take precedence over derived properties from the compiler.
  71. this.config = Object.assign({
  72. mode: compiler.options.mode,
  73. // Use swSrc with a hardcoded .js extension, in case swSrc is a .ts file.
  74. swDest: upath_1.default.parse(this.config.swSrc).name + '.js',
  75. }, this.config);
  76. }
  77. /**
  78. * @param {Object} [compiler] default compiler object passed from webpack
  79. *
  80. * @private
  81. */
  82. apply(compiler) {
  83. var _a;
  84. this.propagateWebpackConfig(compiler);
  85. compiler.hooks.make.tapPromise(this.constructor.name, (compilation) => this.handleMake(compilation, compiler).catch((error) => {
  86. compilation.errors.push(error);
  87. }));
  88. // webpack v4/v5 compatibility:
  89. // https://github.com/webpack/webpack/issues/11425#issuecomment-690387207
  90. if ((_a = webpack_1.default.version) === null || _a === void 0 ? void 0 : _a.startsWith('4.')) {
  91. compiler.hooks.emit.tapPromise(this.constructor.name, (compilation) => this.addAssets(compilation).catch((error) => {
  92. compilation.errors.push(error);
  93. }));
  94. }
  95. else {
  96. const { PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER } = webpack_1.default.Compilation;
  97. // Specifically hook into thisCompilation, as per
  98. // https://github.com/webpack/webpack/issues/11425#issuecomment-690547848
  99. compiler.hooks.thisCompilation.tap(this.constructor.name, (compilation) => {
  100. compilation.hooks.processAssets.tapPromise({
  101. name: this.constructor.name,
  102. // TODO(jeffposnick): This may need to change eventually.
  103. // See https://github.com/webpack/webpack/issues/11822#issuecomment-726184972
  104. stage: PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - 10,
  105. }, () => this.addAssets(compilation).catch((error) => {
  106. compilation.errors.push(error);
  107. }));
  108. });
  109. }
  110. }
  111. /**
  112. * @param {Object} compilation The webpack compilation.
  113. * @param {Object} parentCompiler The webpack parent compiler.
  114. *
  115. * @private
  116. */
  117. async performChildCompilation(compilation, parentCompiler) {
  118. const outputOptions = {
  119. path: parentCompiler.options.output.path,
  120. filename: this.config.swDest,
  121. };
  122. const childCompiler = compilation.createChildCompiler(this.constructor.name, outputOptions, []);
  123. childCompiler.context = parentCompiler.context;
  124. childCompiler.inputFileSystem = parentCompiler.inputFileSystem;
  125. childCompiler.outputFileSystem = parentCompiler.outputFileSystem;
  126. if (Array.isArray(this.config.webpackCompilationPlugins)) {
  127. for (const plugin of this.config.webpackCompilationPlugins) {
  128. // plugin has a generic type, eslint complains for an unsafe
  129. // assign and unsafe use
  130. // eslint-disable-next-line
  131. plugin.apply(childCompiler);
  132. }
  133. }
  134. new SingleEntryPlugin(parentCompiler.context, this.config.swSrc, this.constructor.name).apply(childCompiler);
  135. await new Promise((resolve, reject) => {
  136. childCompiler.runAsChild((error, _entries, childCompilation) => {
  137. var _a, _b;
  138. if (error) {
  139. reject(error);
  140. }
  141. else {
  142. compilation.warnings = compilation.warnings.concat((_a = childCompilation === null || childCompilation === void 0 ? void 0 : childCompilation.warnings) !== null && _a !== void 0 ? _a : []);
  143. compilation.errors = compilation.errors.concat((_b = childCompilation === null || childCompilation === void 0 ? void 0 : childCompilation.errors) !== null && _b !== void 0 ? _b : []);
  144. resolve();
  145. }
  146. });
  147. });
  148. }
  149. /**
  150. * @param {Object} compilation The webpack compilation.
  151. * @param {Object} parentCompiler The webpack parent compiler.
  152. *
  153. * @private
  154. */
  155. addSrcToAssets(compilation, parentCompiler) {
  156. // eslint-disable-next-line
  157. const source = parentCompiler.inputFileSystem.readFileSync(this.config.swSrc);
  158. compilation.emitAsset(this.config.swDest, new RawSource(source));
  159. }
  160. /**
  161. * @param {Object} compilation The webpack compilation.
  162. * @param {Object} parentCompiler The webpack parent compiler.
  163. *
  164. * @private
  165. */
  166. async handleMake(compilation, parentCompiler) {
  167. try {
  168. this.config = (0, validate_options_1.validateWebpackInjectManifestOptions)(this.config);
  169. }
  170. catch (error) {
  171. if (error instanceof Error) {
  172. throw new Error(`Please check your ${this.constructor.name} plugin ` +
  173. `configuration:\n${error.message}`);
  174. }
  175. }
  176. this.config.swDest = (0, relative_to_output_path_1.relativeToOutputPath)(compilation, this.config.swDest);
  177. _generatedAssetNames.add(this.config.swDest);
  178. if (this.config.compileSrc) {
  179. await this.performChildCompilation(compilation, parentCompiler);
  180. }
  181. else {
  182. this.addSrcToAssets(compilation, parentCompiler);
  183. // This used to be a fatal error, but just warn at runtime because we
  184. // can't validate it easily.
  185. if (Array.isArray(this.config.webpackCompilationPlugins) &&
  186. this.config.webpackCompilationPlugins.length > 0) {
  187. compilation.warnings.push(new Error('compileSrc is false, so the ' +
  188. 'webpackCompilationPlugins option will be ignored.'));
  189. }
  190. }
  191. }
  192. /**
  193. * @param {Object} compilation The webpack compilation.
  194. *
  195. * @private
  196. */
  197. async addAssets(compilation) {
  198. var _a, _b, _c, _d, _e;
  199. // See https://github.com/GoogleChrome/workbox/issues/1790
  200. if (this.alreadyCalled) {
  201. const warningMessage = `${this.constructor.name} has been called ` +
  202. `multiple times, perhaps due to running webpack in --watch mode. The ` +
  203. `precache manifest generated after the first call may be inaccurate! ` +
  204. `Please see https://github.com/GoogleChrome/workbox/issues/1790 for ` +
  205. `more information.`;
  206. if (!compilation.warnings.some((warning) => warning instanceof Error && warning.message === warningMessage)) {
  207. compilation.warnings.push(new Error(warningMessage));
  208. }
  209. }
  210. else {
  211. this.alreadyCalled = true;
  212. }
  213. const config = Object.assign({}, this.config);
  214. // Ensure that we don't precache any of the assets generated by *any*
  215. // instance of this plugin.
  216. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  217. config.exclude.push(({ asset }) => _generatedAssetNames.has(asset.name));
  218. // See https://webpack.js.org/contribute/plugin-patterns/#monitoring-the-watch-graph
  219. const absoluteSwSrc = upath_1.default.resolve(this.config.swSrc);
  220. compilation.fileDependencies.add(absoluteSwSrc);
  221. const swAsset = compilation.getAsset(config.swDest);
  222. const swAssetString = swAsset.source.source().toString();
  223. const globalRegexp = new RegExp((0, escape_regexp_1.escapeRegExp)(config.injectionPoint), 'g');
  224. const injectionResults = swAssetString.match(globalRegexp);
  225. if (!injectionResults) {
  226. throw new Error(`Can't find ${(_a = config.injectionPoint) !== null && _a !== void 0 ? _a : ''} in your SW source.`);
  227. }
  228. if (injectionResults.length !== 1) {
  229. throw new Error(`Multiple instances of ${(_b = config.injectionPoint) !== null && _b !== void 0 ? _b : ''} were ` +
  230. `found in your SW source. Include it only once. For more info, see ` +
  231. `https://github.com/GoogleChrome/workbox/issues/2681`);
  232. }
  233. const { size, sortedEntries } = await (0, get_manifest_entries_from_compilation_1.getManifestEntriesFromCompilation)(compilation, config);
  234. let manifestString = (0, fast_json_stable_stringify_1.default)(sortedEntries);
  235. if (this.config.compileSrc &&
  236. // See https://github.com/GoogleChrome/workbox/issues/2729
  237. !(((_c = compilation.options) === null || _c === void 0 ? void 0 : _c.devtool) === 'eval-cheap-source-map' &&
  238. ((_d = compilation.options.optimization) === null || _d === void 0 ? void 0 : _d.minimize))) {
  239. // See https://github.com/GoogleChrome/workbox/issues/2263
  240. manifestString = manifestString.replace(/"/g, `'`);
  241. }
  242. const sourcemapAssetName = (0, get_sourcemap_asset_name_1.getSourcemapAssetName)(compilation, swAssetString, config.swDest);
  243. if (sourcemapAssetName) {
  244. _generatedAssetNames.add(sourcemapAssetName);
  245. const sourcemapAsset = compilation.getAsset(sourcemapAssetName);
  246. const { source, map } = await (0, replace_and_update_source_map_1.replaceAndUpdateSourceMap)({
  247. jsFilename: config.swDest,
  248. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  249. originalMap: JSON.parse(sourcemapAsset.source.source().toString()),
  250. originalSource: swAssetString,
  251. replaceString: manifestString,
  252. searchString: config.injectionPoint,
  253. });
  254. compilation.updateAsset(sourcemapAssetName, new RawSource(map));
  255. compilation.updateAsset(config.swDest, new RawSource(source));
  256. }
  257. else {
  258. // If there's no sourcemap associated with swDest, a simple string
  259. // replacement will suffice.
  260. compilation.updateAsset(config.swDest, new RawSource(swAssetString.replace(config.injectionPoint, manifestString)));
  261. }
  262. if (compilation.getLogger) {
  263. const logger = compilation.getLogger(this.constructor.name);
  264. logger.info(`The service worker at ${(_e = config.swDest) !== null && _e !== void 0 ? _e : ''} will precache
  265. ${sortedEntries.length} URLs, totaling ${(0, pretty_bytes_1.default)(size)}.`);
  266. }
  267. }
  268. }
  269. exports.InjectManifest = InjectManifest;