workbox-build
Advanced tools
Comparing version 3.0.0-alpha.1 to 3.0.0-alpha.2
@@ -5,3 +5,3 @@ { | ||
"releasesDir": "releases", | ||
"latestVersion": "3.0.0-alpha.1" | ||
"latestVersion": "3.0.0-alpha.2" | ||
} |
@@ -19,3 +19,3 @@ 'use strict'; | ||
* | ||
* @param {Object} input | ||
* @param {module:workbox-build.Configuration} config | ||
* @return {Promise<String>} A populated service worker template, based on the | ||
@@ -27,3 +27,3 @@ * other configuration options provided. | ||
var generateSWString = function () { | ||
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(input) { | ||
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(config) { | ||
var options, _ref2, manifestEntries; | ||
@@ -35,3 +35,3 @@ | ||
case 0: | ||
options = validate(input, generateSWStringSchema); | ||
options = validate(config, generateSWStringSchema); | ||
_context.next = 3; | ||
@@ -38,0 +38,0 @@ return getFileManifestEntries(options); |
@@ -25,3 +25,3 @@ 'use strict'; | ||
* | ||
* @param {Object} input | ||
* @param {module:workbox-build.Configuration} config | ||
* @return {Promise<{count: Number, size: Number}>} A promise that resolves once | ||
@@ -35,3 +35,3 @@ * the service worker file has been written to `swDest`. The `size` property | ||
var generateSW = function () { | ||
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(input) { | ||
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(config) { | ||
var options, destDirectory, cdnUrl, workboxDirectoryName, workboxSWPkg, workboxSWFilename, _ref2, count, size, manifestEntries; | ||
@@ -43,3 +43,3 @@ | ||
case 0: | ||
options = validate(input, generateSWSchema); | ||
options = validate(config, generateSWSchema); | ||
destDirectory = path.dirname(options.swDest); | ||
@@ -46,0 +46,0 @@ |
@@ -16,3 +16,3 @@ 'use strict'; | ||
* | ||
* @param {Object} input | ||
* @param {module:workbox-build.Configuration} config | ||
* @return {Promise<{manifestEntries: Array<ManifestEntry>, | ||
@@ -28,3 +28,3 @@ * count: Number, size: Number}>} A promise that resolves once the precache | ||
var getManifest = function () { | ||
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(input) { | ||
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(config) { | ||
var options, _ref2, manifestEntries, count, size; | ||
@@ -36,3 +36,3 @@ | ||
case 0: | ||
options = validate(input, getManifestSchema); | ||
options = validate(config, getManifestSchema); | ||
_context.next = 3; | ||
@@ -39,0 +39,0 @@ return getFileManifestEntries(options); |
@@ -25,3 +25,3 @@ 'use strict'; | ||
* | ||
* @param {Object} input | ||
* @param {module:workbox-build.Configuration} config | ||
* @return {Promise<{count: Number, size: Number}>} A promise that resolves once | ||
@@ -35,3 +35,3 @@ * the service worker file has been written to `swDest`. The `size` property | ||
var injectManifest = function () { | ||
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(input) { | ||
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(config) { | ||
var options, globalRegexp, _ref2, count, size, manifestEntries, swFileContents, injectionResults, entriesString; | ||
@@ -43,5 +43,5 @@ | ||
case 0: | ||
options = validate(input, injectManifestSchema); | ||
options = validate(config, injectManifestSchema); | ||
if (!(path.normalize(input.swSrc) === path.normalize(input.swDest))) { | ||
if (!(path.normalize(config.swSrc) === path.normalize(config.swDest))) { | ||
_context.next = 3; | ||
@@ -66,3 +66,3 @@ break; | ||
_context.next = 14; | ||
return fse.readFile(input.swSrc, 'utf8'); | ||
return fse.readFile(config.swSrc, 'utf8'); | ||
@@ -82,3 +82,8 @@ case 14: | ||
assert(injectionResults, errors['injection-point-not-found'] + ` ${options.injectionPointRegexp}`); | ||
assert(injectionResults, errors['injection-point-not-found'] + ( | ||
// Customize the error message when this happens: | ||
// - If the default RegExp is used, then include the expected string that | ||
// matches as a hint to the developer. | ||
// - If a custom RegExp is used, then just include the raw RegExp. | ||
options.injectionPointRegexp === defaults.injectionPointRegexp ? 'workbox.precaching.precacheAndRoute([])' : options.injectionPointRegexp)); | ||
assert(injectionResults.length === 1, errors['multiple-injection-points'] + ` ${options.injectionPointRegexp}`); | ||
@@ -105,3 +110,3 @@ | ||
_context.next = 35; | ||
return fse.writeFile(input.swDest, swFileContents); | ||
return fse.writeFile(config.swDest, swFileContents); | ||
@@ -146,2 +151,3 @@ case 35: | ||
var defaults = require('./options/defaults'); | ||
var errors = require('../lib/errors'); | ||
@@ -148,0 +154,0 @@ var getFileManifestEntries = require('../lib/get-file-manifest-entries'); |
@@ -21,9 +21,11 @@ 'use strict'; | ||
var defaults = require('./defaults'); | ||
// Define some common constrains used by all methods. | ||
module.exports = joi.object().keys({ | ||
dontCacheBustUrlsMatching: joi.object().type(RegExp), | ||
globIgnores: joi.array().items(joi.string()).default(['node_modules/**/*']), | ||
globPatterns: joi.array().items(joi.string()).default(['**/*.{js,css,html}']), | ||
globIgnores: joi.array().items(joi.string()).default(defaults.globIgnores), | ||
globPatterns: joi.array().items(joi.string()).default(defaults.globPatterns), | ||
manifestTransforms: joi.array().items(joi.func().arity(1)), | ||
maximumFileSizeToCacheInBytes: joi.number().min(1).default(2 * 1024 * 1024), | ||
maximumFileSizeToCacheInBytes: joi.number().min(1).default(defaults.maximumFileSizeToCacheInBytes), | ||
modifyUrlPrefix: joi.object(), | ||
@@ -30,0 +32,0 @@ // templatedUrls is an object where any property name is valid, and the values |
@@ -22,2 +22,3 @@ 'use strict'; | ||
var baseSchema = require('./base-schema'); | ||
var defaults = require('./defaults'); | ||
@@ -27,6 +28,6 @@ // Add some constraints that apply to both generateSW and generateSWString. | ||
cacheId: joi.string(), | ||
clientsClaim: joi.boolean().default(false), | ||
clientsClaim: joi.boolean().default(defaults.clientsClaim), | ||
directoryIndex: joi.string(), | ||
ignoreUrlParametersMatching: joi.array().items(joi.object().type(RegExp)), | ||
navigateFallback: joi.string().default(false), | ||
navigateFallback: joi.string().default(defaults.navigateFallback), | ||
navigateFallbackBlacklist: joi.array().items(joi.object().type(RegExp)), | ||
@@ -50,3 +51,3 @@ navigateFallbackWhitelist: joi.array().items(joi.object().type(RegExp)), | ||
}).requiredKeys('urlPattern', 'handler')), | ||
skipWaiting: joi.boolean().default(false) | ||
skipWaiting: joi.boolean().default(defaults.skipWaiting) | ||
}); |
@@ -22,2 +22,3 @@ 'use strict'; | ||
var commonGenerateSchema = require('./common-generate-schema'); | ||
var defaults = require('./defaults'); | ||
@@ -28,4 +29,4 @@ // Define some additional constraints. | ||
importScripts: joi.array().items(joi.string()), | ||
importWorkboxFromCDN: joi.boolean().default(true), | ||
importWorkboxFromCDN: joi.boolean().default(defaults.importWorkboxFromCDN), | ||
swDest: joi.string().required() | ||
}); |
@@ -22,2 +22,3 @@ 'use strict'; | ||
var commonGenerateSchema = require('./common-generate-schema'); | ||
var defaults = require('./defaults'); | ||
@@ -27,3 +28,4 @@ // Define some additional constraints. | ||
globDirectory: joi.string(), | ||
globPatterns: joi.array().items(joi.string()).default(defaults.generateSWStringGlobPatterns), | ||
importScripts: joi.array().items(joi.string()).required() | ||
}); |
@@ -22,8 +22,9 @@ 'use strict'; | ||
var baseSchema = require('./base-schema'); | ||
var defaults = require('./defaults'); | ||
module.exports = baseSchema.keys({ | ||
globDirectory: joi.string().required(), | ||
injectionPointRegexp: joi.object().type(RegExp).default(/(\.precacheAndRoute\()\s*\[\s*\]\s*(\))/), | ||
injectionPointRegexp: joi.object().type(RegExp).default(defaults.injectionPointRegexp), | ||
swSrc: joi.string().required(), | ||
swDest: joi.string().required() | ||
}); |
@@ -25,2 +25,5 @@ 'use strict'; | ||
var _require = require('./lib/cdn-utils'), | ||
getModuleUrl = _require.getModuleUrl; | ||
/** | ||
@@ -52,346 +55,2 @@ * This Node module can be used to generate a list of assets that should be | ||
/** | ||
* These are the full set of options that could potentially be used to configure | ||
* one of the build tools. Each of the build tools has a slightly different way | ||
* of providing this configuration: | ||
* | ||
* - When using the `workbox-build` module directly, pass the | ||
* configuration object to appropriate method. For example, | ||
* `workboxBuild.injectManifest(configuration)` or | ||
* `workboxBuild.generateSW(configuration)`. | ||
* | ||
* - When using the `workbox-cli` command line interface, use the | ||
* `--config-file` flag to point to a | ||
* [CommonJS module file](https://nodejs.org/docs/latest/api/modules.html) that | ||
* assigns the configuration object to `module.exports`. | ||
* | ||
* - When using `workbox-webpack-plugin` within a | ||
* [Webpack](https://webpack.js.org/) build, pass the configuration object to | ||
* the plugin's constructor, like | ||
* `new WorkboxBuildWebpackPlugin(configuration)`. | ||
* | ||
* Some specific options might not make sense with certain combinations of | ||
* interfaces. In those cases, the limitations are called out in the | ||
* documentation, and may lead to build-time warnings or errors. | ||
* | ||
* Each option documented here includes an example, which, for the sake of | ||
* illustration, assumes the following local filesystem setup. Please adjust | ||
* the example values to match your actual setup. | ||
* | ||
* ```sh | ||
* ./ | ||
* ├── dev/ | ||
* │ ├── app.js | ||
* │ ├── ignored.html | ||
* │ ├── image.png | ||
* │ ├── index.html | ||
* │ ├── main.css | ||
* │ ├── sw.js | ||
* │ └── templates/ | ||
* │ └── app_shell.hbs | ||
* └── dist/ | ||
* ├── app.js | ||
* ├── image.png | ||
* ├── index.html | ||
* ├── main.css | ||
* └── sw.js | ||
* ``` | ||
* | ||
* @typedef {Object} Configuration | ||
* | ||
* @property {String} swDest The path to the final service worker | ||
* file that will be created by the build process, relative to the current | ||
* working directory. | ||
* | ||
* E.g.: `'./dist/sw.js'` | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build.generateSW|generateSW()} or | ||
* {@link module:workbox-build.injectManifest|injectManifest()}. | ||
* | ||
* @property {String} swSrc The path to the source service worker | ||
* containing a `precache([])` placeholder, which will be replaced with the | ||
* precache manifest generated by the build. | ||
* | ||
* E.g.: `'./dev/sw.js'` | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build.injectManifest|injectManifest()}. | ||
* | ||
* @property {String} swTemplate A service worker template that should be | ||
* populated based on the configuration provided. The template should be in a | ||
* format that [`lodash.template`](https://lodash.com/docs/4.17.4#template) | ||
* understands. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build.generateSWNoFS|generateSWNoFS()}. | ||
* | ||
* @property {boolean} [importWorkboxFromCDN=true] If `true`, the WorkboxSW | ||
* runtime will be automatically imported into the generated service worker from | ||
* the official CDN URL. If `false`, the WorkboxSW runtime will be copied | ||
* locally into your `swDest` directory when using | ||
* {@link module:workbox-build.generateSW|generateSW()}. | ||
* If `process.env.NODE_ENV` is set to a string starting with `dev` then the | ||
* `dev` bundle of WorkboxSW, with additional assertions and debugging info, | ||
* will be used; otherwise, the `prod` bundle will be used. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build.generateSW|generateSW()} or | ||
* {@link module:workbox-build.generateSWNoFS|generateSWNoFS()}. | ||
* | ||
* @property {Array<String>} [importScripts] An optional list of JavaScript | ||
* files that should be passed to | ||
* [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts) | ||
* inside the generated service worker file. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build.generateSW|generateSW()} or | ||
* {@link module:workbox-build.generateSWNoFS|generateSWNoFS()}. | ||
* | ||
* @property {Array<String>} [globPatterns=['**\/*.{js,css,html}']] | ||
* Files matching against any of these | ||
* [glob patterns](https://github.com/isaacs/node-glob) will be included in the | ||
* precache manifest. | ||
* | ||
* E.g.: `'**\/*.{js,css,html,png}'` | ||
* | ||
* @property {String} globDirectory The base directory you wish to | ||
* match `globPatterns` against, related to the current working directory. | ||
* | ||
* E.g.: `'./dev'` | ||
* | ||
* @property {String|Array<String>} [globIgnores='node_modules'] | ||
* Files matching against any of these glob patterns will be excluded from the | ||
* file manifest, overriding any matches from `globPatterns`. | ||
* | ||
* E.g. `['**\/ignored.html']` | ||
* | ||
* @property {Object<String,Array|string>} [templatedUrls] | ||
* If a URL is rendered generated based on some server-side logic, its contents | ||
* may depend on multiple files or on some other unique string value. | ||
* | ||
* If used with an array of strings, they will be interpreted as | ||
* [glob patterns](https://github.com/isaacs/node-glob), and the contents of | ||
* any files matching the patterns will be used to uniquely version the URL. | ||
* | ||
* If used with a single string, it will be interpreted as unique versioning | ||
* information that you've generated out of band for a given URL. | ||
* | ||
* E.g. | ||
* ```js | ||
* { | ||
* '/app-shell': [ | ||
* 'dev/templates/app-shell.hbs', | ||
* 'dev/**\/*.css', | ||
* ], | ||
* '/other-page': 'my-version-info', | ||
* } | ||
* ``` | ||
* | ||
* @property {number} [maximumFileSizeToCacheInBytes=2097152] | ||
* This value can be used to determine the maximum size of files that will be | ||
* precached. This prevents you from inadvertantly precaching very large files | ||
* that might have been accidentally match your `globPatterns` values. | ||
* | ||
* @property {Array<ManifestTransform>} [manifestTransforms] An array of | ||
* manifest transformations, which will be applied sequentially against the | ||
* generated manifest. If `modifyUrlPrefix` or `dontCacheBustUrlsMatching` are | ||
* also specified, their corresponding transformations will be applied first. | ||
* | ||
* See {@link module:workbox-build.ManifestTransform|ManifestTransform}. | ||
* | ||
* @property {Object<String,String>} [modifyUrlPrefix] A mapping of | ||
* prefixes that, if present in an entry in the precache manifest, will be | ||
* replaced with the corresponding value. | ||
* | ||
* This can be used to, for example, remove or add a path prefix from a manifest | ||
* entry if your web hosting setup doesn't match your local filesystem setup. | ||
* | ||
* As an alternative with more flexibility, you can use the `manifestTransforms` | ||
* option and provide a function that modifies the entries in the manifest using | ||
* whatever logic you provide. | ||
* | ||
* E.g. | ||
* ```js | ||
* { | ||
* '/prefix-to-remove': '', | ||
* } | ||
* ``` | ||
* | ||
* @property {RegExp} [dontCacheBustUrlsMatching] Assets that match this | ||
* regex will be assumed to be uniquely versioned via their URL, an exempted | ||
* from the normal HTTP cache-busting that's done when populating the precache. | ||
* | ||
* While not required, it's recommended that if your existing build process | ||
* already inserts a `[hash]` value into each filename, you provide a RegExp | ||
* that will detect those values, as it will reduce the amount of bandwidth | ||
* consumed when precaching. | ||
* | ||
* E.g. `/\.\w{8}\./` | ||
* | ||
* @property {String} [navigateFallback] This will be used to create a | ||
* {@link workbox.routing.NavigationRoute|NavigationRoute} that will | ||
* respond to navigation requests for URLs that that aren't precached. | ||
* | ||
* This is meant to be used in a | ||
* [Single Page App](https://en.wikipedia.org/wiki/Single-page_application) | ||
* scenario, in which you want all navigations to result in common App Shell | ||
* HTML being reused. | ||
* | ||
* It's *not* intended for use as a fallback that's displayed when the browser | ||
* is offline. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly add in a call to | ||
* {@link module:workbox-sw.Router#registerNavigationRoute| | ||
* registerNavigationRoute()} | ||
* in your `swSrc` file. | ||
* | ||
* E.g. `'/app-shell'` | ||
* | ||
* @property {Array<RegExp>} [navigateFallbackWhitelist=/./] An optional | ||
* array of regular expressions that restrict which URLs the navigation route | ||
* applies to. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly add in the whitelist when calling | ||
* {@link module:workbox-sw.Router#registerNavigationRoute| | ||
* registerNavigationRoute()} | ||
* in your `swSrc` file. | ||
* | ||
* E.g. `[/pages/, /articles/]` | ||
* | ||
* @property {String} [cacheId] An optional ID to be prepended to caches | ||
* used by `workbox-sw`. This is primarily useful for local development where | ||
* multiple sites may be served from the same `http://localhost` origin. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* E.g. `'my-app-name'` | ||
* | ||
* @property {Boolean} [skipWaiting=false] Whether or not the service worker | ||
* should skip over the [waiting](https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/lifecycle#waiting) | ||
* lifecycle stage. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* @property {Boolean} [clientsClaim=false] Whether or not the service worker | ||
* should [start controlling](https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/lifecycle#clientsclaim) | ||
* any existing clients as soon as it activates. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* @property {string} [directoryIndex='index.html'] If a request for a URL | ||
* ending in '/' fails, this value will be appended to the URL and a second | ||
* request will be made. | ||
* | ||
* This should be configured to whatever your web server is using, if anything, | ||
* for its [directory index](https://httpd.apache.org/docs/2.0/mod/mod_dir.html). | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* @property {Array<Object>} [runtimeCaching] Passing in an array of objects | ||
* containing `urlPattern`s, `handler`s, and potentially `option`s that will add | ||
* the appropriate code to the generated service worker to handle runtime | ||
* caching. | ||
* | ||
* Requests for precached URLs that are picked up via `globPatterns` are handled | ||
* by default, and don't need to be accomodated in `runtimeCaching`. | ||
* | ||
* The `handler` values correspond the names of the | ||
* {@link module:workbox-sw.Strategies|strategies} supported by `workbox-sw`. | ||
* | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly add in the corresponding runtime caching behavior via | ||
* {@link module:workbox-sw.Router#registerRoute|registerRoute()} in your | ||
* `swSrc` file. | ||
* | ||
* E.g. | ||
* ```js | ||
* [{ | ||
* // You can use a RegExp as the pattern: | ||
* urlPattern: /.jpg$/, | ||
* handler: 'cacheFirst', | ||
* // Any options provided will be used when | ||
* // creating the caching strategy. | ||
* options: { | ||
* cacheName: 'image-cache', | ||
* cacheExpiration: { | ||
* maxEntries: 10, | ||
* }, | ||
* }, | ||
* }, { | ||
* // You can also use Express-style strings: | ||
* urlPattern: 'https://example.com/path/to/:file', | ||
* handler: 'staleWhileRevalidate', | ||
* options: { | ||
* cacheableResponse: { | ||
statuses: [0], | ||
* }, | ||
* }, | ||
* }] | ||
* ``` | ||
* | ||
* @property {Array<RegExp>} [ignoreUrlParametersMatching=[/^utm_/]] Any | ||
* search parameter names that match against one of the regex's in this array | ||
* will be removed before looking for a precache match. | ||
* | ||
* This is useful if your users might request URLs that contain, for example, | ||
* URL parameters used to track the source of the traffic. Those URL parameters | ||
* would normally cause the cache lookup to fail, since the URL strings used | ||
* as cache keys would not be expected to include them. | ||
* | ||
* You can use `[/./]` to ignore all URL parameters. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* E.g. `[/homescreen/]` | ||
* | ||
* @property {Boolean} [handleFetch=true] Whether or not `workbox-sw` should | ||
* create a `fetch` event handler that responds to network requests. This is | ||
* useful during development if you don't want the service worker serving stale | ||
* content. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* @memberof module:workbox-build | ||
*/ | ||
module.exports = { | ||
@@ -402,3 +61,4 @@ copyWorkboxLibraries, | ||
getManifest, | ||
getModuleUrl, | ||
injectManifest | ||
}; |
@@ -81,3 +81,3 @@ 'use strict'; | ||
'injection-point-not-found': ol`Unable to find a place to inject the manifest. | ||
Please ensure that your 'swSrc' file contains a match for the RegExp:`, | ||
Please ensure that your service worker file contains the following: `, | ||
'multiple-injection-points': ol`Please ensure that your 'swSrc' file contains | ||
@@ -107,3 +107,5 @@ only one match for the RegExp:`, | ||
the urlPattern parameter. (Express-style routes are not currently | ||
supported.)` | ||
supported.)`, | ||
'bad-runtime-caching-config': ol`An unknown configuration option was used | ||
with runtimeCaching:` | ||
}; |
@@ -54,11 +54,2 @@ 'use strict'; | ||
/** | ||
* @typedef {Object} ManifestEntry | ||
* @property {String} url The URL to the asset in the manifest. | ||
* @property {String} revision The revision details for the file. This is a | ||
* hash generated by node based on the file contents. | ||
* | ||
* @memberof module:workbox-build | ||
*/ | ||
module.exports = function () { | ||
@@ -65,0 +56,0 @@ var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(_ref) { |
'use strict'; | ||
var _keys = require('babel-runtime/core-js/object/keys'); | ||
var _keys2 = _interopRequireDefault(_keys); | ||
var _entries = require('babel-runtime/core-js/object/entries'); | ||
var _entries2 = _interopRequireDefault(_entries); | ||
var _getIterator2 = require('babel-runtime/core-js/get-iterator'); | ||
var _getIterator3 = _interopRequireDefault(_getIterator2); | ||
var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray'); | ||
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); | ||
var _stringify = require('babel-runtime/core-js/json/stringify'); | ||
@@ -7,6 +23,2 @@ | ||
var _assign = require('babel-runtime/core-js/object/assign'); | ||
var _assign2 = _interopRequireDefault(_assign); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
@@ -30,2 +42,4 @@ | ||
var ol = require('common-tags').oneLine; | ||
var errors = require('./errors'); | ||
@@ -43,27 +57,88 @@ | ||
*/ | ||
function getOptionsString(options) { | ||
var cacheOptions = options.cache || {}; | ||
// Start with a base of a few properties that need to be renamed, as well | ||
// as copying over all the other source properties as-is. | ||
var effectiveOptions = (0, _assign2.default)({ | ||
cacheName: cacheOptions.name | ||
}, options); | ||
function getOptionsString() { | ||
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
// Only create the cacheExpiration object if either maxEntries or | ||
// maxAgeSeconds is set. | ||
if (cacheOptions.maxEntries || cacheOptions.maxAgeSeconds) { | ||
effectiveOptions.cacheExpiration = (0, _assign2.default)(effectiveOptions.cacheExpiration || {}, { | ||
maxEntries: cacheOptions.maxEntries, | ||
maxAgeSeconds: cacheOptions.maxAgeSeconds | ||
var plugins = []; | ||
if (options.plugins) { | ||
plugins = options.plugins.map(function (plugin) { | ||
return (0, _stringify2.default)(plugin); | ||
}); | ||
delete options.plugins; | ||
} | ||
// Everything should be copied to the corresponding new option names at this | ||
// point, so set the old-style `cache` property to undefined so that it | ||
// doesn't show up in the JSON output. | ||
effectiveOptions.cache = undefined; | ||
var cacheName = void 0; | ||
if (options.cache && options.cache.name) { | ||
cacheName = options.cache.name; | ||
delete options.cache.name; | ||
} | ||
// JSON.stringify() will automatically omit any properties that are set to | ||
// undefined values. | ||
return (0, _stringify2.default)(effectiveOptions, null, 2); | ||
// Allow a top-level cacheName value to override the cache.name value. | ||
if (options.cacheName) { | ||
cacheName = options.cacheName; | ||
delete options.cacheName; | ||
} | ||
var networkTimeoutSeconds = void 0; | ||
if (options.networkTimeoutSeconds) { | ||
networkTimeoutSeconds = options.networkTimeoutSeconds; | ||
delete options.networkTimeoutSeconds; | ||
} | ||
var pluginsMapping = { | ||
backgroundSync: 'workbox.backgroundSync.Plugin', | ||
broadcastCacheUpdate: 'workbox.broadcastCacheUpdate.Plugin', | ||
cache: 'workbox.expiration.Plugin', | ||
cacheExpiration: 'workbox.expiration.Plugin', | ||
cacheableResponse: 'workbox.cacheableResponse.Plugin' | ||
}; | ||
var _iteratorNormalCompletion = true; | ||
var _didIteratorError = false; | ||
var _iteratorError = undefined; | ||
try { | ||
for (var _iterator = (0, _getIterator3.default)((0, _entries2.default)(options)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { | ||
var _ref = _step.value; | ||
var _ref2 = (0, _slicedToArray3.default)(_ref, 2); | ||
var pluginName = _ref2[0]; | ||
var pluginConfig = _ref2[1]; | ||
// Ensure that we have some valid configuration to pass to Plugin(). | ||
if ((0, _keys2.default)(pluginConfig).length === 0) { | ||
continue; | ||
} | ||
var pluginString = pluginsMapping[pluginName]; | ||
if (!pluginString) { | ||
throw new Error(`${errors['bad-runtime-caching-config']} ${pluginName}`); | ||
} | ||
plugins.push(`${pluginString}(${(0, _stringify2.default)(pluginConfig)})`); | ||
} | ||
} catch (err) { | ||
_didIteratorError = true; | ||
_iteratorError = err; | ||
} finally { | ||
try { | ||
if (!_iteratorNormalCompletion && _iterator.return) { | ||
_iterator.return(); | ||
} | ||
} finally { | ||
if (_didIteratorError) { | ||
throw _iteratorError; | ||
} | ||
} | ||
} | ||
if (networkTimeoutSeconds || cacheName || plugins.length > 0) { | ||
return ol`{ | ||
${networkTimeoutSeconds ? 'networkTimeoutSeconds: ' + (0, _stringify2.default)(networkTimeoutSeconds) + ',' : ''} | ||
${cacheName ? 'cacheName: ' + (0, _stringify2.default)(cacheName) + ',' : ''} | ||
plugins: [${plugins.join(', ')}] | ||
}`; | ||
} else { | ||
return ''; | ||
} | ||
} | ||
@@ -70,0 +145,0 @@ |
@@ -22,10 +22,6 @@ "use strict"; | ||
* | ||
* Here are some next steps: | ||
* You'll need to register this file in your web app and you should | ||
* disable HTTP caching for this file too. | ||
* See https://goo.gl/nhQhGp | ||
* | ||
* - Your web app needs to register this file. | ||
* See https://goo.gl/DNGzMp | ||
* | ||
* - Disable HTTP caching for this file. | ||
* See https://goo.gl/rWuKgq | ||
* | ||
* The rest of the code is auto-generated. Please don't update this file | ||
@@ -36,3 +32,3 @@ * directly; instead, make changes to your Workbox build configuration | ||
*/ | ||
<% if (importScripts) { %> | ||
@@ -52,3 +48,3 @@ importScripts(<%= importScripts.map(JSON.stringify).join(',') %>); | ||
* requests for URLs in the manifest. | ||
* See https://goo.gl/GYZoHL | ||
* See https://goo.gl/S9QRab | ||
*/ | ||
@@ -58,2 +54,3 @@ self.__precacheManifest = <%= JSON.stringify(manifestEntries, null, 2) %>.concat(self.__precacheManifest || []); | ||
if (Array.isArray(self.__precacheManifest)) { | ||
workbox.precaching.suppressWarnings(); | ||
workbox.precaching.precacheAndRoute(self.__precacheManifest, <%= precacheOptionsString %>); | ||
@@ -60,0 +57,0 @@ } |
{ | ||
"name": "workbox-build", | ||
"version": "3.0.0-alpha.1", | ||
"version": "3.0.0-alpha.2", | ||
"description": "A module that integrates into your build process, helping you generate a manifest of local files that workbox-sw should precache.", | ||
@@ -29,8 +29,12 @@ "keywords": [ | ||
"lodash.template": "^4.4.0", | ||
"workbox-cache-expiration": "^3.0.0-alpha.1", | ||
"workbox-core": "^3.0.0-alpha.1", | ||
"workbox-precaching": "^3.0.0-alpha.1", | ||
"workbox-routing": "^3.0.0-alpha.1", | ||
"workbox-strategies": "^3.0.0-alpha.1", | ||
"workbox-sw": "^3.0.0-alpha.1" | ||
"workbox-background-sync": "^3.0.0-alpha.2", | ||
"workbox-broadcast-cache-update": "^3.0.0-alpha.2", | ||
"workbox-cache-expiration": "^3.0.0-alpha.2", | ||
"workbox-cacheable-response": "^3.0.0-alpha.2", | ||
"workbox-core": "^3.0.0-alpha.2", | ||
"workbox-google-analytics": "^3.0.0-alpha.2", | ||
"workbox-precaching": "^3.0.0-alpha.2", | ||
"workbox-routing": "^3.0.0-alpha.2", | ||
"workbox-strategies": "^3.0.0-alpha.2", | ||
"workbox-sw": "^3.0.0-alpha.2" | ||
}, | ||
@@ -37,0 +41,0 @@ "main": "build/index.js", |
@@ -5,3 +5,3 @@ { | ||
"releasesDir": "releases", | ||
"latestVersion": "3.0.0-alpha.1" | ||
"latestVersion": "3.0.0-alpha.2" | ||
} |
@@ -26,3 +26,3 @@ /* | ||
* | ||
* @param {Object} input | ||
* @param {module:workbox-build.Configuration} config | ||
* @return {Promise<String>} A populated service worker template, based on the | ||
@@ -33,4 +33,4 @@ * other configuration options provided. | ||
*/ | ||
async function generateSWString(input) { | ||
const options = validate(input, generateSWStringSchema); | ||
async function generateSWString(config) { | ||
const options = validate(config, generateSWStringSchema); | ||
@@ -37,0 +37,0 @@ const {manifestEntries} = await getFileManifestEntries(options); |
@@ -37,3 +37,3 @@ /* | ||
* | ||
* @param {Object} input | ||
* @param {module:workbox-build.Configuration} config | ||
* @return {Promise<{count: Number, size: Number}>} A promise that resolves once | ||
@@ -46,4 +46,4 @@ * the service worker file has been written to `swDest`. The `size` property | ||
*/ | ||
async function generateSW(input) { | ||
const options = validate(input, generateSWSchema); | ||
async function generateSW(config) { | ||
const options = validate(config, generateSWSchema); | ||
@@ -50,0 +50,0 @@ const destDirectory = path.dirname(options.swDest); |
@@ -26,3 +26,3 @@ /* | ||
* | ||
* @param {Object} input | ||
* @param {module:workbox-build.Configuration} config | ||
* @return {Promise<{manifestEntries: Array<ManifestEntry>, | ||
@@ -37,4 +37,4 @@ * count: Number, size: Number}>} A promise that resolves once the precache | ||
*/ | ||
async function getManifest(input) { | ||
const options = validate(input, getManifestSchema); | ||
async function getManifest(config) { | ||
const options = validate(config, getManifestSchema); | ||
@@ -41,0 +41,0 @@ const {manifestEntries, count, size} = await getFileManifestEntries(options); |
@@ -21,2 +21,3 @@ /* | ||
const defaults = require('./options/defaults'); | ||
const errors = require('../lib/errors'); | ||
@@ -37,3 +38,3 @@ const getFileManifestEntries = require('../lib/get-file-manifest-entries'); | ||
* | ||
* @param {Object} input | ||
* @param {module:workbox-build.Configuration} config | ||
* @return {Promise<{count: Number, size: Number}>} A promise that resolves once | ||
@@ -46,6 +47,6 @@ * the service worker file has been written to `swDest`. The `size` property | ||
*/ | ||
async function injectManifest(input) { | ||
const options = validate(input, injectManifestSchema); | ||
async function injectManifest(config) { | ||
const options = validate(config, injectManifestSchema); | ||
if (path.normalize(input.swSrc) === path.normalize(input.swDest)) { | ||
if (path.normalize(config.swSrc) === path.normalize(config.swDest)) { | ||
throw new Error(errors['same-src-and-dest']); | ||
@@ -59,3 +60,3 @@ } | ||
try { | ||
swFileContents = await fse.readFile(input.swSrc, 'utf8'); | ||
swFileContents = await fse.readFile(config.swSrc, 'utf8'); | ||
} catch (error) { | ||
@@ -67,3 +68,9 @@ throw new Error(`${errors['invalid-sw-src']} ${error.message}`); | ||
assert(injectionResults, errors['injection-point-not-found'] + | ||
` ${options.injectionPointRegexp}`); | ||
// Customize the error message when this happens: | ||
// - If the default RegExp is used, then include the expected string that | ||
// matches as a hint to the developer. | ||
// - If a custom RegExp is used, then just include the raw RegExp. | ||
(options.injectionPointRegexp === defaults.injectionPointRegexp ? | ||
'workbox.precaching.precacheAndRoute([])' : | ||
options.injectionPointRegexp)); | ||
assert(injectionResults.length === 1, errors['multiple-injection-points'] + | ||
@@ -82,3 +89,3 @@ ` ${options.injectionPointRegexp}`); | ||
await fse.writeFile(input.swDest, swFileContents); | ||
await fse.writeFile(config.swDest, swFileContents); | ||
@@ -85,0 +92,0 @@ return {count, size}; |
@@ -19,13 +19,12 @@ /* | ||
const defaults = require('./defaults'); | ||
// Define some common constrains used by all methods. | ||
module.exports = joi.object().keys({ | ||
dontCacheBustUrlsMatching: joi.object().type(RegExp), | ||
globIgnores: joi.array().items(joi.string()).default([ | ||
'node_modules/**/*', | ||
]), | ||
globPatterns: joi.array().items(joi.string()).default([ | ||
'**/*.{js,css,html}', | ||
]), | ||
globIgnores: joi.array().items(joi.string()).default(defaults.globIgnores), | ||
globPatterns: joi.array().items(joi.string()).default(defaults.globPatterns), | ||
manifestTransforms: joi.array().items(joi.func().arity(1)), | ||
maximumFileSizeToCacheInBytes: joi.number().min(1).default(2 * 1024 * 1024), | ||
maximumFileSizeToCacheInBytes: joi.number().min(1) | ||
.default(defaults.maximumFileSizeToCacheInBytes), | ||
modifyUrlPrefix: joi.object(), | ||
@@ -32,0 +31,0 @@ // templatedUrls is an object where any property name is valid, and the values |
@@ -20,2 +20,3 @@ /* | ||
const baseSchema = require('./base-schema'); | ||
const defaults = require('./defaults'); | ||
@@ -25,6 +26,6 @@ // Add some constraints that apply to both generateSW and generateSWString. | ||
cacheId: joi.string(), | ||
clientsClaim: joi.boolean().default(false), | ||
clientsClaim: joi.boolean().default(defaults.clientsClaim), | ||
directoryIndex: joi.string(), | ||
ignoreUrlParametersMatching: joi.array().items(joi.object().type(RegExp)), | ||
navigateFallback: joi.string().default(false), | ||
navigateFallback: joi.string().default(defaults.navigateFallback), | ||
navigateFallbackBlacklist: joi.array().items(joi.object().type(RegExp)), | ||
@@ -54,3 +55,3 @@ navigateFallbackWhitelist: joi.array().items(joi.object().type(RegExp)), | ||
}).requiredKeys('urlPattern', 'handler')), | ||
skipWaiting: joi.boolean().default(false), | ||
skipWaiting: joi.boolean().default(defaults.skipWaiting), | ||
}); |
@@ -20,2 +20,3 @@ /* | ||
const commonGenerateSchema = require('./common-generate-schema'); | ||
const defaults = require('./defaults'); | ||
@@ -26,4 +27,4 @@ // Define some additional constraints. | ||
importScripts: joi.array().items(joi.string()), | ||
importWorkboxFromCDN: joi.boolean().default(true), | ||
importWorkboxFromCDN: joi.boolean().default(defaults.importWorkboxFromCDN), | ||
swDest: joi.string().required(), | ||
}); |
@@ -20,2 +20,3 @@ /* | ||
const commonGenerateSchema = require('./common-generate-schema'); | ||
const defaults = require('./defaults'); | ||
@@ -25,3 +26,5 @@ // Define some additional constraints. | ||
globDirectory: joi.string(), | ||
globPatterns: joi.array().items(joi.string()).default( | ||
defaults.generateSWStringGlobPatterns), | ||
importScripts: joi.array().items(joi.string()).required(), | ||
}); |
@@ -20,2 +20,3 @@ /* | ||
const baseSchema = require('./base-schema'); | ||
const defaults = require('./defaults'); | ||
@@ -25,5 +26,5 @@ module.exports = baseSchema.keys({ | ||
injectionPointRegexp: joi.object().type(RegExp) | ||
.default(/(\.precacheAndRoute\()\s*\[\s*\]\s*(\))/), | ||
.default(defaults.injectionPointRegexp), | ||
swSrc: joi.string().required(), | ||
swDest: joi.string().required(), | ||
}); |
346
src/index.js
@@ -22,2 +22,3 @@ /* | ||
const injectManifest = require('./entry-points/inject-manifest'); | ||
const {getModuleUrl} = require('./lib/cdn-utils'); | ||
@@ -50,346 +51,2 @@ /** | ||
/** | ||
* These are the full set of options that could potentially be used to configure | ||
* one of the build tools. Each of the build tools has a slightly different way | ||
* of providing this configuration: | ||
* | ||
* - When using the `workbox-build` module directly, pass the | ||
* configuration object to appropriate method. For example, | ||
* `workboxBuild.injectManifest(configuration)` or | ||
* `workboxBuild.generateSW(configuration)`. | ||
* | ||
* - When using the `workbox-cli` command line interface, use the | ||
* `--config-file` flag to point to a | ||
* [CommonJS module file](https://nodejs.org/docs/latest/api/modules.html) that | ||
* assigns the configuration object to `module.exports`. | ||
* | ||
* - When using `workbox-webpack-plugin` within a | ||
* [Webpack](https://webpack.js.org/) build, pass the configuration object to | ||
* the plugin's constructor, like | ||
* `new WorkboxBuildWebpackPlugin(configuration)`. | ||
* | ||
* Some specific options might not make sense with certain combinations of | ||
* interfaces. In those cases, the limitations are called out in the | ||
* documentation, and may lead to build-time warnings or errors. | ||
* | ||
* Each option documented here includes an example, which, for the sake of | ||
* illustration, assumes the following local filesystem setup. Please adjust | ||
* the example values to match your actual setup. | ||
* | ||
* ```sh | ||
* ./ | ||
* ├── dev/ | ||
* │ ├── app.js | ||
* │ ├── ignored.html | ||
* │ ├── image.png | ||
* │ ├── index.html | ||
* │ ├── main.css | ||
* │ ├── sw.js | ||
* │ └── templates/ | ||
* │ └── app_shell.hbs | ||
* └── dist/ | ||
* ├── app.js | ||
* ├── image.png | ||
* ├── index.html | ||
* ├── main.css | ||
* └── sw.js | ||
* ``` | ||
* | ||
* @typedef {Object} Configuration | ||
* | ||
* @property {String} swDest The path to the final service worker | ||
* file that will be created by the build process, relative to the current | ||
* working directory. | ||
* | ||
* E.g.: `'./dist/sw.js'` | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build.generateSW|generateSW()} or | ||
* {@link module:workbox-build.injectManifest|injectManifest()}. | ||
* | ||
* @property {String} swSrc The path to the source service worker | ||
* containing a `precache([])` placeholder, which will be replaced with the | ||
* precache manifest generated by the build. | ||
* | ||
* E.g.: `'./dev/sw.js'` | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build.injectManifest|injectManifest()}. | ||
* | ||
* @property {String} swTemplate A service worker template that should be | ||
* populated based on the configuration provided. The template should be in a | ||
* format that [`lodash.template`](https://lodash.com/docs/4.17.4#template) | ||
* understands. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build.generateSWNoFS|generateSWNoFS()}. | ||
* | ||
* @property {boolean} [importWorkboxFromCDN=true] If `true`, the WorkboxSW | ||
* runtime will be automatically imported into the generated service worker from | ||
* the official CDN URL. If `false`, the WorkboxSW runtime will be copied | ||
* locally into your `swDest` directory when using | ||
* {@link module:workbox-build.generateSW|generateSW()}. | ||
* If `process.env.NODE_ENV` is set to a string starting with `dev` then the | ||
* `dev` bundle of WorkboxSW, with additional assertions and debugging info, | ||
* will be used; otherwise, the `prod` bundle will be used. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build.generateSW|generateSW()} or | ||
* {@link module:workbox-build.generateSWNoFS|generateSWNoFS()}. | ||
* | ||
* @property {Array<String>} [importScripts] An optional list of JavaScript | ||
* files that should be passed to | ||
* [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts) | ||
* inside the generated service worker file. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build.generateSW|generateSW()} or | ||
* {@link module:workbox-build.generateSWNoFS|generateSWNoFS()}. | ||
* | ||
* @property {Array<String>} [globPatterns=['**\/*.{js,css,html}']] | ||
* Files matching against any of these | ||
* [glob patterns](https://github.com/isaacs/node-glob) will be included in the | ||
* precache manifest. | ||
* | ||
* E.g.: `'**\/*.{js,css,html,png}'` | ||
* | ||
* @property {String} globDirectory The base directory you wish to | ||
* match `globPatterns` against, related to the current working directory. | ||
* | ||
* E.g.: `'./dev'` | ||
* | ||
* @property {String|Array<String>} [globIgnores='node_modules'] | ||
* Files matching against any of these glob patterns will be excluded from the | ||
* file manifest, overriding any matches from `globPatterns`. | ||
* | ||
* E.g. `['**\/ignored.html']` | ||
* | ||
* @property {Object<String,Array|string>} [templatedUrls] | ||
* If a URL is rendered generated based on some server-side logic, its contents | ||
* may depend on multiple files or on some other unique string value. | ||
* | ||
* If used with an array of strings, they will be interpreted as | ||
* [glob patterns](https://github.com/isaacs/node-glob), and the contents of | ||
* any files matching the patterns will be used to uniquely version the URL. | ||
* | ||
* If used with a single string, it will be interpreted as unique versioning | ||
* information that you've generated out of band for a given URL. | ||
* | ||
* E.g. | ||
* ```js | ||
* { | ||
* '/app-shell': [ | ||
* 'dev/templates/app-shell.hbs', | ||
* 'dev/**\/*.css', | ||
* ], | ||
* '/other-page': 'my-version-info', | ||
* } | ||
* ``` | ||
* | ||
* @property {number} [maximumFileSizeToCacheInBytes=2097152] | ||
* This value can be used to determine the maximum size of files that will be | ||
* precached. This prevents you from inadvertantly precaching very large files | ||
* that might have been accidentally match your `globPatterns` values. | ||
* | ||
* @property {Array<ManifestTransform>} [manifestTransforms] An array of | ||
* manifest transformations, which will be applied sequentially against the | ||
* generated manifest. If `modifyUrlPrefix` or `dontCacheBustUrlsMatching` are | ||
* also specified, their corresponding transformations will be applied first. | ||
* | ||
* See {@link module:workbox-build.ManifestTransform|ManifestTransform}. | ||
* | ||
* @property {Object<String,String>} [modifyUrlPrefix] A mapping of | ||
* prefixes that, if present in an entry in the precache manifest, will be | ||
* replaced with the corresponding value. | ||
* | ||
* This can be used to, for example, remove or add a path prefix from a manifest | ||
* entry if your web hosting setup doesn't match your local filesystem setup. | ||
* | ||
* As an alternative with more flexibility, you can use the `manifestTransforms` | ||
* option and provide a function that modifies the entries in the manifest using | ||
* whatever logic you provide. | ||
* | ||
* E.g. | ||
* ```js | ||
* { | ||
* '/prefix-to-remove': '', | ||
* } | ||
* ``` | ||
* | ||
* @property {RegExp} [dontCacheBustUrlsMatching] Assets that match this | ||
* regex will be assumed to be uniquely versioned via their URL, an exempted | ||
* from the normal HTTP cache-busting that's done when populating the precache. | ||
* | ||
* While not required, it's recommended that if your existing build process | ||
* already inserts a `[hash]` value into each filename, you provide a RegExp | ||
* that will detect those values, as it will reduce the amount of bandwidth | ||
* consumed when precaching. | ||
* | ||
* E.g. `/\.\w{8}\./` | ||
* | ||
* @property {String} [navigateFallback] This will be used to create a | ||
* {@link workbox.routing.NavigationRoute|NavigationRoute} that will | ||
* respond to navigation requests for URLs that that aren't precached. | ||
* | ||
* This is meant to be used in a | ||
* [Single Page App](https://en.wikipedia.org/wiki/Single-page_application) | ||
* scenario, in which you want all navigations to result in common App Shell | ||
* HTML being reused. | ||
* | ||
* It's *not* intended for use as a fallback that's displayed when the browser | ||
* is offline. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly add in a call to | ||
* {@link module:workbox-sw.Router#registerNavigationRoute| | ||
* registerNavigationRoute()} | ||
* in your `swSrc` file. | ||
* | ||
* E.g. `'/app-shell'` | ||
* | ||
* @property {Array<RegExp>} [navigateFallbackWhitelist=/./] An optional | ||
* array of regular expressions that restrict which URLs the navigation route | ||
* applies to. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly add in the whitelist when calling | ||
* {@link module:workbox-sw.Router#registerNavigationRoute| | ||
* registerNavigationRoute()} | ||
* in your `swSrc` file. | ||
* | ||
* E.g. `[/pages/, /articles/]` | ||
* | ||
* @property {String} [cacheId] An optional ID to be prepended to caches | ||
* used by `workbox-sw`. This is primarily useful for local development where | ||
* multiple sites may be served from the same `http://localhost` origin. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* E.g. `'my-app-name'` | ||
* | ||
* @property {Boolean} [skipWaiting=false] Whether or not the service worker | ||
* should skip over the [waiting](https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/lifecycle#waiting) | ||
* lifecycle stage. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* @property {Boolean} [clientsClaim=false] Whether or not the service worker | ||
* should [start controlling](https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/lifecycle#clientsclaim) | ||
* any existing clients as soon as it activates. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* @property {string} [directoryIndex='index.html'] If a request for a URL | ||
* ending in '/' fails, this value will be appended to the URL and a second | ||
* request will be made. | ||
* | ||
* This should be configured to whatever your web server is using, if anything, | ||
* for its [directory index](https://httpd.apache.org/docs/2.0/mod/mod_dir.html). | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* @property {Array<Object>} [runtimeCaching] Passing in an array of objects | ||
* containing `urlPattern`s, `handler`s, and potentially `option`s that will add | ||
* the appropriate code to the generated service worker to handle runtime | ||
* caching. | ||
* | ||
* Requests for precached URLs that are picked up via `globPatterns` are handled | ||
* by default, and don't need to be accomodated in `runtimeCaching`. | ||
* | ||
* The `handler` values correspond the names of the | ||
* {@link module:workbox-sw.Strategies|strategies} supported by `workbox-sw`. | ||
* | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly add in the corresponding runtime caching behavior via | ||
* {@link module:workbox-sw.Router#registerRoute|registerRoute()} in your | ||
* `swSrc` file. | ||
* | ||
* E.g. | ||
* ```js | ||
* [{ | ||
* // You can use a RegExp as the pattern: | ||
* urlPattern: /.jpg$/, | ||
* handler: 'cacheFirst', | ||
* // Any options provided will be used when | ||
* // creating the caching strategy. | ||
* options: { | ||
* cacheName: 'image-cache', | ||
* cacheExpiration: { | ||
* maxEntries: 10, | ||
* }, | ||
* }, | ||
* }, { | ||
* // You can also use Express-style strings: | ||
* urlPattern: 'https://example.com/path/to/:file', | ||
* handler: 'staleWhileRevalidate', | ||
* options: { | ||
* cacheableResponse: { | ||
statuses: [0], | ||
* }, | ||
* }, | ||
* }] | ||
* ``` | ||
* | ||
* @property {Array<RegExp>} [ignoreUrlParametersMatching=[/^utm_/]] Any | ||
* search parameter names that match against one of the regex's in this array | ||
* will be removed before looking for a precache match. | ||
* | ||
* This is useful if your users might request URLs that contain, for example, | ||
* URL parameters used to track the source of the traffic. Those URL parameters | ||
* would normally cause the cache lookup to fail, since the URL strings used | ||
* as cache keys would not be expected to include them. | ||
* | ||
* You can use `[/./]` to ignore all URL parameters. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* E.g. `[/homescreen/]` | ||
* | ||
* @property {Boolean} [handleFetch=true] Whether or not `workbox-sw` should | ||
* create a `fetch` event handler that responds to network requests. This is | ||
* useful during development if you don't want the service worker serving stale | ||
* content. | ||
* | ||
* Note: This option is only valid when used with | ||
* {@link module:workbox-build#generateSW|generateSW()}. When using | ||
* {@link module:workbox-build.injectManifest|injectManifest()}, you can | ||
* explicitly pass the desired value in to the | ||
* {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc` | ||
* file. | ||
* | ||
* @memberof module:workbox-build | ||
*/ | ||
module.exports = { | ||
@@ -400,3 +57,4 @@ copyWorkboxLibraries, | ||
getManifest, | ||
getModuleUrl, | ||
injectManifest, | ||
}; |
@@ -79,3 +79,3 @@ /* | ||
'injection-point-not-found': ol`Unable to find a place to inject the manifest. | ||
Please ensure that your 'swSrc' file contains a match for the RegExp:`, | ||
Please ensure that your service worker file contains the following: `, | ||
'multiple-injection-points': ol`Please ensure that your 'swSrc' file contains | ||
@@ -107,2 +107,4 @@ only one match for the RegExp:`, | ||
supported.)`, | ||
'bad-runtime-caching-config': ol`An unknown configuration option was used | ||
with runtimeCaching:`, | ||
}; |
@@ -26,11 +26,2 @@ /* | ||
/** | ||
* @typedef {Object} ManifestEntry | ||
* @property {String} url The URL to the asset in the manifest. | ||
* @property {String} revision The revision details for the file. This is a | ||
* hash generated by node based on the file contents. | ||
* | ||
* @memberof module:workbox-build | ||
*/ | ||
module.exports = async ({ | ||
@@ -37,0 +28,0 @@ dontCacheBustUrlsMatching, |
@@ -17,2 +17,4 @@ /* | ||
const ol = require('common-tags').oneLine; | ||
const errors = require('./errors'); | ||
@@ -30,28 +32,59 @@ | ||
*/ | ||
function getOptionsString(options) { | ||
const cacheOptions = options.cache || {}; | ||
// Start with a base of a few properties that need to be renamed, as well | ||
// as copying over all the other source properties as-is. | ||
const effectiveOptions = Object.assign({ | ||
cacheName: cacheOptions.name, | ||
}, options); | ||
function getOptionsString(options = {}) { | ||
let plugins = []; | ||
if (options.plugins) { | ||
plugins = options.plugins.map((plugin) => JSON.stringify(plugin)); | ||
delete options.plugins; | ||
} | ||
// Only create the cacheExpiration object if either maxEntries or | ||
// maxAgeSeconds is set. | ||
if (cacheOptions.maxEntries || cacheOptions.maxAgeSeconds) { | ||
effectiveOptions.cacheExpiration = | ||
Object.assign(effectiveOptions.cacheExpiration || {}, { | ||
maxEntries: cacheOptions.maxEntries, | ||
maxAgeSeconds: cacheOptions.maxAgeSeconds, | ||
}); | ||
let cacheName; | ||
if (options.cache && options.cache.name) { | ||
cacheName = options.cache.name; | ||
delete options.cache.name; | ||
} | ||
// Everything should be copied to the corresponding new option names at this | ||
// point, so set the old-style `cache` property to undefined so that it | ||
// doesn't show up in the JSON output. | ||
effectiveOptions.cache = undefined; | ||
// Allow a top-level cacheName value to override the cache.name value. | ||
if (options.cacheName) { | ||
cacheName = options.cacheName; | ||
delete options.cacheName; | ||
} | ||
// JSON.stringify() will automatically omit any properties that are set to | ||
// undefined values. | ||
return JSON.stringify(effectiveOptions, null, 2); | ||
let networkTimeoutSeconds; | ||
if (options.networkTimeoutSeconds) { | ||
networkTimeoutSeconds = options.networkTimeoutSeconds; | ||
delete options.networkTimeoutSeconds; | ||
} | ||
const pluginsMapping = { | ||
backgroundSync: 'workbox.backgroundSync.Plugin', | ||
broadcastCacheUpdate: 'workbox.broadcastCacheUpdate.Plugin', | ||
cache: 'workbox.expiration.Plugin', | ||
cacheExpiration: 'workbox.expiration.Plugin', | ||
cacheableResponse: 'workbox.cacheableResponse.Plugin', | ||
}; | ||
for (const [pluginName, pluginConfig] of Object.entries(options)) { | ||
// Ensure that we have some valid configuration to pass to Plugin(). | ||
if (Object.keys(pluginConfig).length === 0) { | ||
continue; | ||
} | ||
const pluginString = pluginsMapping[pluginName]; | ||
if (!pluginString) { | ||
throw new Error(`${errors['bad-runtime-caching-config']} ${pluginName}`); | ||
} | ||
plugins.push(`${pluginString}(${JSON.stringify(pluginConfig)})`); | ||
} | ||
if (networkTimeoutSeconds || cacheName || plugins.length > 0) { | ||
return ol`{ | ||
${networkTimeoutSeconds ? ('networkTimeoutSeconds: ' + | ||
JSON.stringify(networkTimeoutSeconds)) + ',' : ''} | ||
${cacheName ? ('cacheName: ' + JSON.stringify(cacheName)) + ',' : ''} | ||
plugins: [${plugins.join(', ')}] | ||
}`; | ||
} else { | ||
return ''; | ||
} | ||
} | ||
@@ -58,0 +91,0 @@ |
@@ -20,10 +20,6 @@ /* | ||
* | ||
* Here are some next steps: | ||
* You'll need to register this file in your web app and you should | ||
* disable HTTP caching for this file too. | ||
* See https://goo.gl/nhQhGp | ||
* | ||
* - Your web app needs to register this file. | ||
* See https://goo.gl/DNGzMp | ||
* | ||
* - Disable HTTP caching for this file. | ||
* See https://goo.gl/rWuKgq | ||
* | ||
* The rest of the code is auto-generated. Please don't update this file | ||
@@ -34,3 +30,3 @@ * directly; instead, make changes to your Workbox build configuration | ||
*/ | ||
<% if (importScripts) { %> | ||
@@ -50,3 +46,3 @@ importScripts(<%= importScripts.map(JSON.stringify).join(',') %>); | ||
* requests for URLs in the manifest. | ||
* See https://goo.gl/GYZoHL | ||
* See https://goo.gl/S9QRab | ||
*/ | ||
@@ -56,2 +52,3 @@ self.__precacheManifest = <%= JSON.stringify(manifestEntries, null, 2) %>.concat(self.__precacheManifest || []); | ||
if (Array.isArray(self.__precacheManifest)) { | ||
workbox.precaching.suppressWarnings(); | ||
workbox.precaching.precacheAndRoute(self.__precacheManifest, <%= precacheOptionsString %>); | ||
@@ -58,0 +55,0 @@ } |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
69
0
158993
16
3655
+ Addedworkbox-background-sync@3.6.3(transitive)
+ Addedworkbox-broadcast-cache-update@3.6.3(transitive)
+ Addedworkbox-cacheable-response@3.6.3(transitive)
+ Addedworkbox-google-analytics@3.6.3(transitive)
Updatedworkbox-core@^3.0.0-alpha.2
Updatedworkbox-sw@^3.0.0-alpha.2