1 | /*
|
2 | Copyright 2018 Google LLC
|
3 |
|
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 |
|
9 | import upath from 'upath';
|
10 |
|
11 | import {BuildResult, GetManifestOptions} from './types';
|
12 | import {getFileManifestEntries} from './lib/get-file-manifest-entries';
|
13 | import {rebasePath} from './lib/rebase-path';
|
14 | import {validateGenerateSWOptions} from './lib/validate-options';
|
15 | import {writeSWUsingDefaultTemplate} from './lib/write-sw-using-default-template';
|
16 |
|
17 | // eslint-disable-next-line jsdoc/newline-after-description
|
18 | /**
|
19 | * This method creates a list of URLs to precache, referred to as a "precache
|
20 | * manifest", based on the options you provide.
|
21 | *
|
22 | * It also takes in additional options that configures the service worker's
|
23 | * behavior, like any `runtimeCaching` rules it should use.
|
24 | *
|
25 | * Based on the precache manifest and the additional configuration, it writes
|
26 | * a ready-to-use service worker file to disk at `swDest`.
|
27 | *
|
28 | * @param {Object} config The configuration to use.
|
29 | *
|
30 | * @param {string} config.globDirectory The local directory you wish to match
|
31 | * `globPatterns` against. The path is relative to the current directory.
|
32 | *
|
33 | * @param {string} config.swDest The path and filename of the service worker file
|
34 | * that will be created by the build process, relative to the current working
|
35 | * directory. It must end in '.js'.
|
36 | *
|
37 | * @param {Array<module:workbox-build.ManifestEntry>} [config.additionalManifestEntries]
|
38 | * A list of entries to be precached, in addition to any entries that are
|
39 | * generated as part of the build configuration.
|
40 | *
|
41 | * @param {Array<string>} [config.babelPresetEnvTargets=['chrome >= 56']]
|
42 | * The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass to
|
43 | * `babel-preset-env` when transpiling the service worker bundle.
|
44 | *
|
45 | * @param {string} [config.cacheId] An optional ID to be prepended to cache
|
46 | * names. This is primarily useful for local development where multiple sites
|
47 | * may be served from the same `http://localhost:port` origin.
|
48 | *
|
49 | * @param {boolean} [config.cleanupOutdatedCaches=false] Whether or not Workbox
|
50 | * should attempt to identify and delete any precaches created by older,
|
51 | * incompatible versions.
|
52 | *
|
53 | * @param {boolean} [config.clientsClaim=false] Whether or not the service
|
54 | * worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)
|
55 | * any existing clients as soon as it activates.
|
56 | *
|
57 | * @param {string} [config.directoryIndex='index.html'] If a navigation request
|
58 | * for a URL ending in `/` fails to match a precached URL, this value will be
|
59 | * appended to the URL and that will be checked for a precache match. This
|
60 | * should be set to what your web server is using for its directory index.
|
61 | *
|
62 | * @param {RegExp} [config.dontCacheBustURLsMatching] Assets that match this will be
|
63 | * assumed to be uniquely versioned via their URL, and exempted from the normal
|
64 | * HTTP cache-busting that's done when populating the precache. While not
|
65 | * required, it's recommended that if your existing build process already
|
66 | * inserts a `[hash]` value into each filename, you provide a RegExp that will
|
67 | * detect that, as it will reduce the bandwidth consumed when precaching.
|
68 | *
|
69 | * @param {boolean} [config.globFollow=true] Determines whether or not symlinks
|
70 | * are followed when generating the precache manifest. For more information, see
|
71 | * the definition of `follow` in the `glob`
|
72 | * [documentation](https://github.com/isaacs/node-glob#options).
|
73 | *
|
74 | * @param {Array<string>} [config.globIgnores=['node_modules/**']]
|
75 | * A set of patterns matching files to always exclude when generating the
|
76 | * precache manifest. For more information, see the definition of `ignore` in the `glob`
|
77 | * [documentation](https://github.com/isaacs/node-glob#options).
|
78 | *
|
79 | * @param {Array<string>} [config.globPatterns=['**.{js,css,html}']]
|
80 | * Files matching any of these patterns will be included in the precache
|
81 | * manifest. For more information, see the
|
82 | * [`glob` primer](https://github.com/isaacs/node-glob#glob-primer).
|
83 | *
|
84 | * @param {boolean} [config.globStrict=true] If true, an error reading a directory when
|
85 | * generating a precache manifest will cause the build to fail. If false, the
|
86 | * problematic directory will be skipped. For more information, see the
|
87 | * definition of `strict` in the `glob`
|
88 | * [documentation](https://github.com/isaacs/node-glob#options).
|
89 | *
|
90 | * @param {Array<RegExp>} [config.ignoreURLParametersMatching=[/^utm_/, /^fbclid$/]]
|
91 | * Any search parameter names that match against one of the RegExp in this array
|
92 | * will be removed before looking for a precache match. This is useful if your
|
93 | * users might request URLs that contain, for example, URL parameters used to
|
94 | * track the source of the traffic.
|
95 | *
|
96 | * @param {Array<string>} [config.importScripts] A list of JavaScript files that
|
97 | * should be passed to [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)
|
98 | * inside the generated service worker file. This is useful when you want to
|
99 | * let Workbox create your top-level service worker file, but want to include
|
100 | * some additional code, such as a push event listener.
|
101 | *
|
102 | * @param {boolean} [config.inlineWorkboxRuntime=false] Whether the runtime code
|
103 | * for the Workbox library should be included in the top-level service worker,
|
104 | * or split into a separate file that needs to be deployed alongside the service
|
105 | * worker. Keeping the runtime separate means that users will not have to
|
106 | * re-download the Workbox code each time your top-level service worker changes.
|
107 | *
|
108 | * @param {Array<module:workbox-build.ManifestTransform>} [config.manifestTransforms] One or more
|
109 | * functions which will be applied sequentially against the generated manifest.
|
110 | * If `modifyURLPrefix` or `dontCacheBustURLsMatching` are also specified, their
|
111 | * corresponding transformations will be applied first.
|
112 | *
|
113 | * @param {number} [config.maximumFileSizeToCacheInBytes=2097152] This value can be
|
114 | * used to determine the maximum size of files that will be precached. This
|
115 | * prevents you from inadvertently precaching very large files that might have
|
116 | * accidentally matched one of your patterns.
|
117 | *
|
118 | * @param {string} [config.mode='production'] If set to 'production', then an
|
119 | * optimized service worker bundle that excludes debugging info will be
|
120 | * produced. If not explicitly configured here, the `process.env.NODE_ENV` value
|
121 | * will be used, and failing that, it will fall back to `'production'`.
|
122 | *
|
123 | * @param {object<string, string>} [config.modifyURLPrefix] A mapping of prefixes
|
124 | * that, if present in an entry in the precache manifest, will be replaced with
|
125 | * the corresponding value. This can be used to, for example, remove or add a
|
126 | * path prefix from a manifest entry if your web hosting setup doesn't match
|
127 | * your local filesystem setup. As an alternative with more flexibility, you can
|
128 | * use the `manifestTransforms` option and provide a function that modifies the
|
129 | * entries in the manifest using whatever logic you provide.
|
130 | *
|
131 | * @param {string} [config.navigateFallback] If specified, all
|
132 | * [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)
|
133 | * for URLs that aren't precached will be fulfilled with the HTML at the URL
|
134 | * provided. You must pass in the URL of an HTML document that is listed in your
|
135 | * precache manifest. This is meant to be used in a Single Page App scenario, in
|
136 | * which you want all navigations to use common [App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).
|
137 | *
|
138 | * @param {Array<RegExp>} [config.navigateFallbackDenylist] An optional array
|
139 | * of regular expressions that restricts which URLs the configured
|
140 | * `navigateFallback` behavior applies to. This is useful if only a subset of
|
141 | * your site's URLs should be treated as being part of a
|
142 | * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). If
|
143 | * both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are
|
144 | * configured, the denylist takes precedent.
|
145 | *
|
146 | * @param {Array<RegExp>} [config.navigateFallbackAllowlist] An optional array
|
147 | * of regular expressions that restricts which URLs the configured
|
148 | * `navigateFallback` behavior applies to. This is useful if only a subset of
|
149 | * your site's URLs should be treated as being part of a
|
150 | * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). If
|
151 | * both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are
|
152 | * configured, the denylist takes precedent.
|
153 | *
|
154 | * @param {boolean} [config.navigationPreload=false] Whether or not to enable
|
155 | * [navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)
|
156 | * in the generated service worker. When set to true, you must also use
|
157 | * `runtimeCaching` to set up an appropriate response strategy that will match
|
158 | * navigation requests, and make use of the preloaded response.
|
159 | *
|
160 | * @param {boolean|Object} [config.offlineGoogleAnalytics=false] Controls
|
161 | * whether or not to include support for
|
162 | * [offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).
|
163 | * When `true`, the call to `workbox-google-analytics`'s `initialize()` will be
|
164 | * added to your generated service worker. When set to an `Object`, that object
|
165 | * will be passed in to the `initialize()` call, allowing you to customize the
|
166 | * behavior.
|
167 | *
|
168 | * @param {Array<RuntimeCachingEntry>} [config.runtimeCaching]
|
169 | *
|
170 | * @param {boolean} [config.skipWaiting=false] Whether to add an
|
171 | * unconditional call to [`skipWaiting()`]{@link module:workbox-core.skipWaiting}
|
172 | * to the generated service worker. If `false`, then a `message` listener will
|
173 | * be added instead, allowing you to conditionally call `skipWaiting()` by posting
|
174 | * a message containing {type: 'SKIP_WAITING'}.
|
175 | *
|
176 | * @param {boolean} [config.sourcemap=true] Whether to create a sourcemap
|
177 | * for the generated service worker files.
|
178 | *
|
179 | * @param {Object} [config.templatedURLs] If a URL is rendered based on some
|
180 | * server-side logic, its contents may depend on multiple files or on some other
|
181 | * unique string value. The keys in this object are server-rendered URLs. If the
|
182 | * values are an array of strings, they will be interpreted as `glob` patterns,
|
183 | * and the contents of any files matching the patterns will be used to uniquely
|
184 | * version the URL. If used with a single string, it will be interpreted as
|
185 | * unique versioning information that you've generated for a given URL.
|
186 | *
|
187 | * @return {Promise<{count: number, filePaths: Array<string>, size: number, warnings: Array<string>}>}
|
188 | * A promise that resolves once the service worker and related files
|
189 | * (indicated by `filePaths`) has been written to `swDest`. The `size` property
|
190 | * contains the aggregate size of all the precached entries, in bytes, and the
|
191 | * `count` property contains the total number of precached entries. Any
|
192 | * non-fatal warning messages will be returned via `warnings`.
|
193 | *
|
194 | * @memberof module:workbox-build
|
195 | */
|
196 | export async function generateSW(config: unknown): Promise<BuildResult> {
|
197 | const options = validateGenerateSWOptions(config);
|
198 | let entriesResult;
|
199 |
|
200 | if (options.globDirectory) {
|
201 | // Make sure we leave swDest out of the precache manifest.
|
202 | options.globIgnores!.push(rebasePath({
|
203 | baseDirectory: options.globDirectory,
|
204 | file: options.swDest,
|
205 | }));
|
206 |
|
207 | // If we create an extra external runtime file, ignore that, too.
|
208 | // See https://rollupjs.org/guide/en/#outputchunkfilenames for naming.
|
209 | if (!options.inlineWorkboxRuntime) {
|
210 | const swDestDir = upath.dirname(options.swDest);
|
211 | const workboxRuntimeFile = upath.join(swDestDir, 'workbox-*.js');
|
212 | options.globIgnores!.push(rebasePath({
|
213 | baseDirectory: options.globDirectory,
|
214 | file: workboxRuntimeFile,
|
215 | }));
|
216 | }
|
217 |
|
218 | // We've previously asserted that options.globDirectory is set, so this
|
219 | // should be a safe cast.
|
220 | entriesResult = await getFileManifestEntries(options as GetManifestOptions);
|
221 | } else {
|
222 | entriesResult = {
|
223 | count: 0,
|
224 | manifestEntries: [],
|
225 | size: 0,
|
226 | warnings: [],
|
227 | };
|
228 | }
|
229 |
|
230 | const filePaths = await writeSWUsingDefaultTemplate(Object.assign({
|
231 | manifestEntries: entriesResult.manifestEntries,
|
232 | }, options));
|
233 |
|
234 | return {
|
235 | filePaths,
|
236 | count: entriesResult.count,
|
237 | size: entriesResult.size,
|
238 | warnings: entriesResult.warnings,
|
239 | };
|
240 | }
|