workbox-routing
Advanced tools
Comparing version 3.6.2 to 4.0.0-alpha.0
@@ -6,20 +6,12 @@ this.workbox = this.workbox || {}; | ||
try { | ||
self.workbox.v['workbox:routing:3.6.2'] = 1; | ||
self.workbox.v['workbox:routing:4.0.0-alpha.0'] = 1; | ||
} catch (e) {} // eslint-disable-line | ||
/* | ||
Copyright 2017 Google Inc. All Rights Reserved. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
Copyright 2018 Google LLC | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
Use of this source code is governed by an MIT-style | ||
license that can be found in the LICENSE file or at | ||
https://opensource.org/licenses/MIT. | ||
*/ | ||
/** | ||
@@ -33,4 +25,4 @@ * The default HTTP method, 'GET', used when there's no specific method | ||
*/ | ||
const defaultMethod = 'GET'; | ||
/** | ||
@@ -43,19 +35,12 @@ * The list of valid HTTP methods associated with requests that could be routed. | ||
*/ | ||
const validMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT']; | ||
/* | ||
Copyright 2017 Google Inc. All Rights Reserved. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
Copyright 2018 Google LLC | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
Use of this source code is governed by an MIT-style | ||
license that can be found in the LICENSE file or at | ||
https://opensource.org/licenses/MIT. | ||
*/ | ||
/** | ||
@@ -68,2 +53,3 @@ * @param {function()|Object} handler Either a function, or an object with a | ||
*/ | ||
var normalizeHandler = (handler => { | ||
@@ -79,2 +65,3 @@ if (handler && typeof handler === 'object') { | ||
} | ||
return handler; | ||
@@ -90,3 +77,6 @@ } else { | ||
} | ||
return { handle: handler }; | ||
return { | ||
handle: handler | ||
}; | ||
} | ||
@@ -96,16 +86,8 @@ }); | ||
/* | ||
Copyright 2017 Google Inc. All Rights Reserved. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
Copyright 2018 Google LLC | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
Use of this source code is governed by an MIT-style | ||
license that can be found in the LICENSE file or at | ||
https://opensource.org/licenses/MIT. | ||
*/ | ||
/** | ||
@@ -120,2 +102,3 @@ * A `Route` consists of a pair of callback functions, "match" and "handler". | ||
*/ | ||
class Route { | ||
@@ -143,8 +126,10 @@ /** | ||
if (method) { | ||
assert_mjs.assert.isOneOf(method, validMethods, { paramName: 'method' }); | ||
assert_mjs.assert.isOneOf(method, validMethods, { | ||
paramName: 'method' | ||
}); | ||
} | ||
} | ||
} // These values are referenced directly by Router so cannot be | ||
// altered by minifification. | ||
// These values are referenced directly by Router so cannot be | ||
// altered by minifification. | ||
this.handler = normalizeHandler(handler); | ||
@@ -154,19 +139,125 @@ this.match = match; | ||
} | ||
} | ||
/* | ||
Copyright 2017 Google Inc. All Rights Reserved. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
Copyright 2018 Google LLC | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Use of this source code is governed by an MIT-style | ||
license that can be found in the LICENSE file or at | ||
https://opensource.org/licenses/MIT. | ||
*/ | ||
/** | ||
* NavigationRoute makes it easy to create a [Route]{@link | ||
* workbox.routing.Route} that matches for browser | ||
* [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}. | ||
* | ||
* It will only match incoming Requests whose | ||
* [`mode`]{@link https://fetch.spec.whatwg.org/#concept-request-mode} | ||
* is set to `navigate`. | ||
* | ||
* You can optionally only apply this route to a subset of navigation requests | ||
* by using one or both of the `blacklist` and `whitelist` parameters. | ||
* | ||
* @memberof workbox.routing | ||
* @extends workbox.routing.Route | ||
*/ | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
class NavigationRoute extends Route { | ||
/** | ||
* If both `blacklist` and `whiltelist` are provided, the `blacklist` will | ||
* take precedence and the request will not match this route. | ||
* | ||
* The regular expressions in `whitelist` and `blacklist` | ||
* are matched against the concatenated | ||
* [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname} | ||
* and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search} | ||
* portions of the requested URL. | ||
* | ||
* @param {workbox.routing.Route~handlerCallback} handler A callback | ||
* function that returns a Promise resulting in a Response. | ||
* @param {Object} options | ||
* @param {Array<RegExp>} [options.blacklist] If any of these patterns match, | ||
* the route will not handle the request (even if a whitelist RegExp matches). | ||
* @param {Array<RegExp>} [options.whitelist=[/./]] If any of these patterns | ||
* match the URL's pathname and search parameter, the route will handle the | ||
* request (assuming the blacklist doesn't match). | ||
*/ | ||
constructor(handler, { | ||
whitelist = [/./], | ||
blacklist = [] | ||
} = {}) { | ||
{ | ||
assert_mjs.assert.isArrayOfClass(whitelist, RegExp, { | ||
moduleName: 'workbox-routing', | ||
className: 'NavigationRoute', | ||
funcName: 'constructor', | ||
paramName: 'options.whitelist' | ||
}); | ||
assert_mjs.assert.isArrayOfClass(blacklist, RegExp, { | ||
moduleName: 'workbox-routing', | ||
className: 'NavigationRoute', | ||
funcName: 'constructor', | ||
paramName: 'options.blacklist' | ||
}); | ||
} | ||
super(options => this._match(options), handler); | ||
this._whitelist = whitelist; | ||
this._blacklist = blacklist; | ||
} | ||
/** | ||
* Routes match handler. | ||
* | ||
* @param {Object} options | ||
* @param {URL} options.url | ||
* @param {Request} options.request | ||
* @return {boolean} | ||
* | ||
* @private | ||
*/ | ||
_match({ | ||
url, | ||
request | ||
}) { | ||
if (request.mode !== 'navigate') { | ||
return false; | ||
} | ||
const pathnameAndSearch = url.pathname + url.search; | ||
if (this._blacklist.some(regExp => regExp.test(pathnameAndSearch))) { | ||
{ | ||
logger_mjs.logger.debug(`The navigation route is not being used, since the ` + `request URL matches both the whitelist and blacklist.`); | ||
} | ||
return false; | ||
} | ||
if (this._whitelist.some(regExp => regExp.test(pathnameAndSearch))) { | ||
{ | ||
logger_mjs.logger.debug(`The navigation route is being used.`); | ||
} | ||
return true; | ||
} else { | ||
{ | ||
logger_mjs.logger.debug(`The navigation route is not being used, since the ` + `URL being navigated to doesn't match the whitelist.`); | ||
} | ||
} | ||
return false; | ||
} | ||
} | ||
/* | ||
Copyright 2018 Google LLC | ||
Use of this source code is governed by an MIT-style | ||
license that can be found in the LICENSE file or at | ||
https://opensource.org/licenses/MIT. | ||
*/ | ||
/** | ||
@@ -185,2 +276,3 @@ * RegExpRoute makes it easy to create a regular expression based | ||
*/ | ||
class RegExpRoute extends Route { | ||
@@ -210,14 +302,15 @@ /** | ||
const match = ({ url }) => { | ||
const result = regExp.exec(url.href); | ||
const match = ({ | ||
url | ||
}) => { | ||
const result = regExp.exec(url.href); // Return null immediately if there's no match. | ||
// Return null immediately if there's no match. | ||
if (!result) { | ||
return null; | ||
} | ||
// Require that the match start at the first character in the URL string | ||
} // Require that the match start at the first character in the URL string | ||
// if it's a cross-origin request. | ||
// See https://github.com/GoogleChrome/workbox/issues/281 for the context | ||
// behind this behavior. | ||
if (url.origin !== location.origin && result.index !== 0) { | ||
@@ -229,8 +322,8 @@ { | ||
return null; | ||
} | ||
// If the route matches, but there aren't any capture groups defined, then | ||
} // If the route matches, but there aren't any capture groups defined, then | ||
// this will return [], which is truthy and therefore sufficient to | ||
// indicate a match. | ||
// If there are capture groups, then it will return their values. | ||
return result.slice(1); | ||
@@ -241,19 +334,12 @@ }; | ||
} | ||
} | ||
/* | ||
Copyright 2017 Google Inc. All Rights Reserved. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
Copyright 2018 Google LLC | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
Use of this source code is governed by an MIT-style | ||
license that can be found in the LICENSE file or at | ||
https://opensource.org/licenses/MIT. | ||
*/ | ||
/** | ||
@@ -276,2 +362,3 @@ * The Router can be used to process a FetchEvent through one or more | ||
*/ | ||
class Router { | ||
@@ -286,24 +373,81 @@ /** | ||
} | ||
/** | ||
* Adds a fetch event listener to respond to events when a route matches | ||
* the event's request. | ||
*/ | ||
addFetchListener() { | ||
self.addEventListener('fetch', event => { | ||
const { | ||
request | ||
} = event; | ||
const responsePromise = this.handleRequest({ | ||
request, | ||
event | ||
}); | ||
if (responsePromise) { | ||
event.respondWith(responsePromise); | ||
} | ||
}); | ||
} | ||
/** | ||
* Adds a message event listener for URLs to cache from the window. | ||
* This is useful to cache resources loaded prior to when the service worker | ||
* started controlling the page. | ||
*/ | ||
addCacheListener() { | ||
self.addEventListener('message', event => { | ||
if (event.data.type === 'CACHE_URLS' && event.data.meta === 'workbox-window') { | ||
const { | ||
urlsToCache | ||
} = event.data.payload; | ||
{ | ||
logger_mjs.logger.debug(`Caching URLs from the window`, urlsToCache); | ||
} | ||
for (const url of urlsToCache) { | ||
const request = new Request(url); | ||
this.handleRequest({ | ||
request, | ||
event | ||
}); | ||
} | ||
} | ||
}); | ||
} | ||
/** | ||
* Apply the routing rules to a FetchEvent object to get a Response from an | ||
* appropriate Route's handler. | ||
* | ||
* @param {FetchEvent} event The event from a service worker's 'fetch' event | ||
* listener. | ||
* @param {Object} options | ||
* @param {Request} options.request The request to handle (this is usually | ||
* from a fetch event, but it does not have to be). | ||
* @param {FetchEvent} [options.event] The event that triggered the request, | ||
* if applicable. | ||
* @return {Promise<Response>|undefined} A promise is returned if a | ||
* registered route can handle the FetchEvent's request. If there is no | ||
* matching route and there's no `defaultHandler`, `undefined` is returned. | ||
* registered route can handle the request. If there is no matching | ||
* route and there's no `defaultHandler`, `undefined` is returned. | ||
*/ | ||
handleRequest(event) { | ||
handleRequest({ | ||
request, | ||
event | ||
}) { | ||
{ | ||
assert_mjs.assert.isInstance(event, FetchEvent, { | ||
assert_mjs.assert.isInstance(request, Request, { | ||
moduleName: 'workbox-routing', | ||
className: 'Router', | ||
funcName: 'handleRequest', | ||
paramName: 'event' | ||
paramName: 'options.request' | ||
}); | ||
} | ||
const url = new URL(event.request.url); | ||
const url = new URL(request.url, location); | ||
if (!url.protocol.startsWith('http')) { | ||
@@ -313,14 +457,17 @@ { | ||
} | ||
return; | ||
} | ||
let route = null; | ||
let handler = null; | ||
let params = null; | ||
let { | ||
params, | ||
route | ||
} = this.findMatchingRoute({ | ||
url, | ||
request, | ||
event | ||
}); | ||
let handler = route && route.handler; | ||
let debugMessages = []; | ||
const result = this._findHandlerAndParams(event, url); | ||
handler = result.handler; | ||
params = result.params; | ||
route = result.route; | ||
{ | ||
@@ -334,13 +481,13 @@ if (handler) { | ||
} | ||
} | ||
} // If we don't have a handler because there was no matching route, then | ||
// fall back to defaultHandler if that's defined. | ||
// If we don't have a handler because there was no matching route, then | ||
// fall back to defaultHandler if that's defined. | ||
if (!handler && this._defaultHandler) { | ||
{ | ||
debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler.`); | ||
debugMessages.push(`Failed to find a matching route. Falling ` + `back to the default handler.`); // This is used for debugging in logs in the case of an error. | ||
// This is used for debugging in logs in the case of an error. | ||
route = '[Default Handler]'; | ||
} | ||
handler = this._defaultHandler; | ||
@@ -355,2 +502,3 @@ } | ||
} | ||
return; | ||
@@ -369,18 +517,22 @@ } | ||
} | ||
}); | ||
}); // The Request and Response objects contains a great deal of information, | ||
// hide it under a group in case developers want to see it. | ||
// The Request and Response objects contains a great deal of information, | ||
// hide it under a group in case developers want to see it. | ||
logger_mjs.logger.groupCollapsed(`View request details here.`); | ||
logger_mjs.logger.unprefixed.log(event.request); | ||
logger_mjs.logger.unprefixed.log(request); | ||
logger_mjs.logger.groupEnd(); | ||
logger_mjs.logger.groupEnd(); | ||
} | ||
} // Wrap in try and catch in case the handle method throws a synchronous | ||
// error. It should still callback to the catch handler. | ||
// Wrap in try and catch in case the handle method throws a synchronous | ||
// error. It should still callback to the catch handler. | ||
let responsePromise; | ||
try { | ||
responsePromise = handler.handle({ url, event, params }); | ||
responsePromise = handler.handle({ | ||
url, | ||
request, | ||
event, | ||
params | ||
}); | ||
} catch (err) { | ||
@@ -400,3 +552,8 @@ responsePromise = Promise.reject(err); | ||
} | ||
return this._catchHandler.handle({ url, event, err }); | ||
return this._catchHandler.handle({ | ||
url, | ||
event, | ||
err | ||
}); | ||
}); | ||
@@ -407,42 +564,67 @@ } | ||
} | ||
/** | ||
* Checks the incoming `event.request` against the registered routes, and if | ||
* there's a match, returns the corresponding handler along with any params | ||
* generated by the match. | ||
* Checks a request and URL (and optionally an event) against the list of | ||
* registered routes, and if there's a match, returns the corresponding | ||
* route along with any params generated by the match. | ||
* | ||
* @param {FetchEvent} event | ||
* @param {URL} url | ||
* @return {Object} Returns an object with `handler` and `params` properties. | ||
* They are populated if a matching route was found or `undefined` otherwise. | ||
* | ||
* @private | ||
* @param {Object} options | ||
* @param {URL} options.url | ||
* @param {Request} options.request The request to match. | ||
* @param {FetchEvent} [options.event] The corresponding event (unless N/A). | ||
* @return {Object} An object with `route` and `params` properties. | ||
* They are populated if a matching route was found or `undefined` | ||
* otherwise. | ||
*/ | ||
_findHandlerAndParams(event, url) { | ||
const routes = this._routes.get(event.request.method) || []; | ||
findMatchingRoute({ | ||
url, | ||
request, | ||
event | ||
}) { | ||
{ | ||
assert_mjs.assert.isInstance(url, URL, { | ||
moduleName: 'workbox-routing', | ||
className: 'Router', | ||
funcName: 'findMatchingRoute', | ||
paramName: 'options.url' | ||
}); | ||
assert_mjs.assert.isInstance(request, Request, { | ||
moduleName: 'workbox-routing', | ||
className: 'Router', | ||
funcName: 'findMatchingRoute', | ||
paramName: 'options.request' | ||
}); | ||
} | ||
const routes = this._routes.get(request.method) || []; | ||
for (const route of routes) { | ||
let matchResult = route.match({ url, event }); | ||
let params; | ||
let matchResult = route.match({ | ||
url, | ||
request, | ||
event | ||
}); | ||
if (matchResult) { | ||
if (Array.isArray(matchResult) && matchResult.length === 0) { | ||
if (Array.isArray(matchResult) && matchResult.length > 0) { | ||
// Instead of passing an empty array in as params, use undefined. | ||
matchResult = undefined; | ||
} else if (matchResult.constructor === Object && Object.keys(matchResult).length === 0 || matchResult === true) { | ||
params = matchResult; | ||
} else if (matchResult.constructor === Object && Object.keys(matchResult).length > 0) { | ||
// Instead of passing an empty object in as params, use undefined. | ||
matchResult = undefined; | ||
} | ||
params = matchResult; | ||
} // Return early if have a match. | ||
// Break out of the loop and return the appropriate values as soon as | ||
// we have a match. | ||
return { | ||
route, | ||
params: matchResult, | ||
handler: route.handler | ||
params | ||
}; | ||
} | ||
} | ||
} // If no match was found above, return and empty object. | ||
// If we didn't have a match, then return undefined values. | ||
return { handler: undefined, params: undefined }; | ||
return {}; | ||
} | ||
/** | ||
@@ -458,6 +640,7 @@ * Define a default `handler` that's called when no routes explicitly | ||
*/ | ||
setDefaultHandler(handler) { | ||
this._defaultHandler = normalizeHandler(handler); | ||
} | ||
/** | ||
@@ -470,6 +653,7 @@ * If a Route throws an error while handling a request, this `handler` | ||
*/ | ||
setCatchHandler(handler) { | ||
this._catchHandler = normalizeHandler(handler); | ||
} | ||
/** | ||
@@ -480,2 +664,4 @@ * Registers a route with the router. | ||
*/ | ||
registerRoute(route) { | ||
@@ -489,3 +675,2 @@ { | ||
}); | ||
assert_mjs.assert.hasMethod(route, 'match', { | ||
@@ -497,3 +682,2 @@ moduleName: 'workbox-routing', | ||
}); | ||
assert_mjs.assert.isType(route.handler, 'object', { | ||
@@ -505,3 +689,2 @@ moduleName: 'workbox-routing', | ||
}); | ||
assert_mjs.assert.hasMethod(route.handler, 'handle', { | ||
@@ -513,3 +696,2 @@ moduleName: 'workbox-routing', | ||
}); | ||
assert_mjs.assert.isType(route.method, 'string', { | ||
@@ -525,9 +707,8 @@ moduleName: 'workbox-routing', | ||
this._routes.set(route.method, []); | ||
} | ||
} // Give precedence to all of the earlier routes by adding this additional | ||
// route to the end of the array. | ||
// Give precedence to all of the earlier routes by adding this additional | ||
// route to the end of the array. | ||
this._routes.get(route.method).push(route); | ||
} | ||
/** | ||
@@ -538,2 +719,4 @@ * Unregisters a route with the router. | ||
*/ | ||
unregisterRoute(route) { | ||
@@ -547,2 +730,3 @@ if (!this._routes.has(route.method)) { | ||
const routeIndex = this._routes.get(route.method).indexOf(route); | ||
if (routeIndex > -1) { | ||
@@ -554,162 +738,27 @@ this._routes.get(route.method).splice(routeIndex, 1); | ||
} | ||
} | ||
/* | ||
Copyright 2016 Google Inc. All Rights Reserved. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
Copyright 2018 Google LLC | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
Use of this source code is governed by an MIT-style | ||
license that can be found in the LICENSE file or at | ||
https://opensource.org/licenses/MIT. | ||
*/ | ||
/** | ||
* NavigationRoute makes it easy to create a [Route]{@link | ||
* workbox.routing.Route} that matches for browser | ||
* [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}. | ||
* | ||
* It will only match incoming Requests whose | ||
* [`mode`]{@link https://fetch.spec.whatwg.org/#concept-request-mode} | ||
* is set to `navigate`. | ||
* | ||
* You can optionally only apply this route to a subset of navigation requests | ||
* by using one or both of the `blacklist` and `whitelist` parameters. | ||
* | ||
* @memberof workbox.routing | ||
* @extends workbox.routing.Route | ||
* The router class exposed on the routing namespace. | ||
* A single instance of this class is exposed because most users will only | ||
* need one router, and this version offers the most features and flexibility. | ||
*/ | ||
class NavigationRoute extends Route { | ||
/** | ||
* If both `blacklist` and `whiltelist` are provided, the `blacklist` will | ||
* take precedence and the request will not match this route. | ||
* | ||
* The regular expressions in `whitelist` and `blacklist` | ||
* are matched against the concatenated | ||
* [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname} | ||
* and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search} | ||
* portions of the requested URL. | ||
* | ||
* @param {workbox.routing.Route~handlerCallback} handler A callback | ||
* function that returns a Promise resulting in a Response. | ||
* @param {Object} options | ||
* @param {Array<RegExp>} [options.blacklist] If any of these patterns match, | ||
* the route will not handle the request (even if a whitelist RegExp matches). | ||
* @param {Array<RegExp>} [options.whitelist=[/./]] If any of these patterns | ||
* match the URL's pathname and search parameter, the route will handle the | ||
* request (assuming the blacklist doesn't match). | ||
*/ | ||
constructor(handler, { whitelist = [/./], blacklist = [] } = {}) { | ||
{ | ||
assert_mjs.assert.isArrayOfClass(whitelist, RegExp, { | ||
moduleName: 'workbox-routing', | ||
className: 'NavigationRoute', | ||
funcName: 'constructor', | ||
paramName: 'options.whitelist' | ||
}); | ||
assert_mjs.assert.isArrayOfClass(blacklist, RegExp, { | ||
moduleName: 'workbox-routing', | ||
className: 'NavigationRoute', | ||
funcName: 'constructor', | ||
paramName: 'options.blacklist' | ||
}); | ||
} | ||
super((...args) => this._match(...args), handler); | ||
this._whitelist = whitelist; | ||
this._blacklist = blacklist; | ||
} | ||
class DefaultRouter extends Router { | ||
/** | ||
* Routes match handler. | ||
* | ||
* @param {Object} options | ||
* @param {FetchEvent} options.event | ||
* @param {URL} options.url | ||
* @return {boolean} | ||
* | ||
* @private | ||
* The default router automatically adds fetch and cache message listeners. | ||
*/ | ||
_match({ event, url }) { | ||
if (event.request.mode !== 'navigate') { | ||
return false; | ||
} | ||
const pathnameAndSearch = url.pathname + url.search; | ||
if (this._blacklist.some(regExp => regExp.test(pathnameAndSearch))) { | ||
{ | ||
logger_mjs.logger.debug(`The navigation route is not being used, since the ` + `request URL matches both the whitelist and blacklist.`); | ||
} | ||
return false; | ||
} | ||
if (this._whitelist.some(regExp => regExp.test(pathnameAndSearch))) { | ||
{ | ||
logger_mjs.logger.debug(`The navigation route is being used.`); | ||
} | ||
return true; | ||
} else { | ||
{ | ||
logger_mjs.logger.debug(`The navigation route is not being used, since the ` + `URL being navigated to doesn't match the whitelist.`); | ||
} | ||
} | ||
return false; | ||
constructor() { | ||
super(); | ||
this.addFetchListener(); | ||
this.addCacheListener(); | ||
} | ||
} | ||
/* | ||
Copyright 2017 Google Inc. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
https://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
var publicAPI = /*#__PURE__*/Object.freeze({ | ||
RegExpRoute: RegExpRoute, | ||
Route: Route, | ||
Router: Router, | ||
NavigationRoute: NavigationRoute | ||
}); | ||
/* | ||
Copyright 2017 Google Inc. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
https://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
{ | ||
assert_mjs.assert.isSwEnv('workbox-routing'); | ||
} | ||
/** | ||
* @private | ||
*/ | ||
class DefaultRouter extends Router { | ||
/** | ||
@@ -739,2 +788,4 @@ * Easily register a RegExp, string, or function with a caching | ||
*/ | ||
registerRoute(capture, handler, method = 'GET') { | ||
@@ -754,9 +805,10 @@ let route; | ||
}); | ||
} | ||
} // We want to check if Express-style wildcards are in the pathname only. | ||
// TODO: Remove this log message in v4. | ||
// We want to check if Express-style wildcards are in the pathname only. | ||
// TODO: Remove this log message in v4. | ||
const valueToCheck = capture.startsWith('http') ? captureUrl.pathname : capture; | ||
// See https://github.com/pillarjs/path-to-regexp#parameters | ||
const valueToCheck = capture.startsWith('http') ? captureUrl.pathname : capture; // See https://github.com/pillarjs/path-to-regexp#parameters | ||
const wildcards = '[*:?+]'; | ||
if (valueToCheck.match(new RegExp(`${wildcards}`))) { | ||
@@ -767,3 +819,5 @@ logger_mjs.logger.debug(`The '$capture' parameter contains an Express-style wildcard ` + `character (${wildcards}). Strings are now always interpreted as ` + `exact matches; use a RegExp for partial or wildcard matches.`); | ||
const matchCallback = ({ url }) => { | ||
const matchCallback = ({ | ||
url | ||
}) => { | ||
{ | ||
@@ -797,3 +851,2 @@ if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) { | ||
} | ||
/** | ||
@@ -826,2 +879,4 @@ * Register a route that will return a precached file for a navigation | ||
*/ | ||
registerNavigationRoute(cachedAssetUrl, options = {}) { | ||
@@ -838,8 +893,12 @@ { | ||
const cacheName = cacheNames_mjs.cacheNames.getPrecacheName(options.cacheName); | ||
const handler = () => caches.match(cachedAssetUrl, { cacheName }).then(response => { | ||
const handler = () => caches.match(cachedAssetUrl, { | ||
cacheName | ||
}).then(response => { | ||
if (response) { | ||
return response; | ||
} | ||
// This shouldn't normally happen, but there are edge cases: | ||
} // This shouldn't normally happen, but there are edge cases: | ||
// https://github.com/GoogleChrome/workbox/issues/1441 | ||
throw new Error(`The cache ${cacheName} did not have an entry for ` + `${cachedAssetUrl}.`); | ||
@@ -852,6 +911,6 @@ }).catch(error => { | ||
{ | ||
logger_mjs.logger.debug(`Unable to respond to navigation request with cached ` + `response: ${error.message}. Falling back to network.`); | ||
} | ||
logger_mjs.logger.debug(`Unable to respond to navigation request with ` + `cached response: ${error.message}. Falling back to network.`); | ||
} // This might still fail if the browser is offline... | ||
// This might still fail if the browser is offline... | ||
return fetch(cachedAssetUrl); | ||
@@ -865,36 +924,46 @@ }); | ||
super.registerRoute(route); | ||
return route; | ||
} | ||
} | ||
const router = new DefaultRouter(); | ||
/* | ||
Copyright 2018 Google LLC | ||
// By default, register a fetch event listener that will respond to a request | ||
// only if there's a matching route. | ||
self.addEventListener('fetch', event => { | ||
const responsePromise = router.handleRequest(event); | ||
if (responsePromise) { | ||
event.respondWith(responsePromise); | ||
} | ||
Use of this source code is governed by an MIT-style | ||
license that can be found in the LICENSE file or at | ||
https://opensource.org/licenses/MIT. | ||
*/ | ||
var publicAPI = /*#__PURE__*/Object.freeze({ | ||
DefaultRouter: DefaultRouter, | ||
RegExpRoute: RegExpRoute, | ||
Route: Route, | ||
Router: Router, | ||
NavigationRoute: NavigationRoute | ||
}); | ||
/* | ||
Copyright 2017 Google Inc. | ||
Copyright 2018 Google LLC | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
Use of this source code is governed by an MIT-style | ||
license that can be found in the LICENSE file or at | ||
https://opensource.org/licenses/MIT. | ||
*/ | ||
https://www.apache.org/licenses/LICENSE-2.0 | ||
{ | ||
assert_mjs.assert.isSwEnv('workbox-routing'); | ||
} | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
var defaultExport = new DefaultRouter(); | ||
/* | ||
Copyright 2018 Google LLC | ||
Use of this source code is governed by an MIT-style | ||
license that can be found in the LICENSE file or at | ||
https://opensource.org/licenses/MIT. | ||
*/ | ||
const finalExport = Object.assign(defaultExport, publicAPI); | ||
const finalExport = Object.assign(router, publicAPI); | ||
return finalExport; | ||
@@ -901,0 +970,0 @@ |
@@ -1,3 +0,3 @@ | ||
this.workbox=this.workbox||{},this.workbox.routing=function(t,e){"use strict";try{self.workbox.v["workbox:routing:3.6.2"]=1}catch(t){}const r="GET";var s=t=>t&&"object"==typeof t?t:{handle:t};class n{constructor(t,e,n){this.handler=s(e),this.match=t,this.method=n||r}}class o extends n{constructor(t,e,r){super(({url:e})=>{const r=t.exec(e.href);return r?e.origin!==location.origin&&0!==r.index?null:r.slice(1):null},e,r)}}class i{constructor(){this.t=new Map}handleRequest(t){const e=new URL(t.request.url);if(!e.protocol.startsWith("http"))return;let r=null,s=null,n=null;const o=this.e(t,e);if(s=o.handler,n=o.params,r=o.route,!s&&this.r&&(s=this.r),!s)return;let i;try{i=s.handle({url:e,event:t,params:n})}catch(t){i=Promise.reject(t)}return i&&this.s&&(i=i.catch(r=>this.s.handle({url:e,event:t,err:r}))),i}e(t,e){const r=this.t.get(t.request.method)||[];for(const s of r){let r=s.match({url:e,event:t});if(r)return Array.isArray(r)&&0===r.length?r=void 0:(r.constructor===Object&&0===Object.keys(r).length||!0===r)&&(r=void 0),{route:s,params:r,handler:s.handler}}return{handler:void 0,params:void 0}}setDefaultHandler(t){this.r=s(t)}setCatchHandler(t){this.s=s(t)}registerRoute(t){this.t.has(t.method)||this.t.set(t.method,[]),this.t.get(t.method).push(t)}unregisterRoute(e){if(!this.t.has(e.method))throw new t.WorkboxError("unregister-route-but-not-found-with-method",{method:e.method});const r=this.t.get(e.method).indexOf(e);if(!(r>-1))throw new t.WorkboxError("unregister-route-route-not-registered");this.t.get(e.method).splice(r,1)}}class u extends n{constructor(t,{whitelist:e=[/./],blacklist:r=[]}={}){super((...t)=>this.n(...t),t),this.o=e,this.i=r}n({event:t,url:e}){if("navigate"!==t.request.mode)return!1;const r=e.pathname+e.search;return!this.i.some(t=>t.test(r))&&!!this.o.some(t=>t.test(r))}}var a=Object.freeze({RegExpRoute:o,Route:n,Router:i,NavigationRoute:u});const c=new class extends i{registerRoute(e,r,s="GET"){let i;if("string"==typeof e){const t=new URL(e,location);i=new n(({url:e})=>e.href===t.href,r,s)}else if(e instanceof RegExp)i=new o(e,r,s);else if("function"==typeof e)i=new n(e,r,s);else{if(!(e instanceof n))throw new t.WorkboxError("unsupported-route-type",{moduleName:"workbox-routing",className:"DefaultRouter",funcName:"registerRoute",paramName:"capture"});i=e}return super.registerRoute(i),i}registerNavigationRoute(t,r={}){const s=e.cacheNames.getPrecacheName(r.cacheName),n=new u(()=>caches.match(t,{cacheName:s}).then(e=>{if(e)return e;throw new Error(`The cache ${s} did not have an entry for `+`${t}.`)}).catch(e=>fetch(t)),{whitelist:r.whitelist,blacklist:r.blacklist});return super.registerRoute(n),n}};return self.addEventListener("fetch",t=>{const e=c.handleRequest(t);e&&t.respondWith(e)}),Object.assign(c,a)}(workbox.core._private,workbox.core._private); | ||
this.workbox=this.workbox||{},this.workbox.routing=function(t,e){"use strict";try{self.workbox.v["workbox:routing:4.0.0-alpha.0"]=1}catch(t){}const r="GET";var s=t=>t&&"object"==typeof t?t:{handle:t};class n{constructor(t,e,n){this.handler=s(e),this.match=t,this.method=n||r}}class o extends n{constructor(t,{whitelist:e=[/./],blacklist:r=[]}={}){super(t=>this.t(t),t),this.e=e,this.r=r}t({url:t,request:e}){if("navigate"!==e.mode)return!1;const r=t.pathname+t.search;return!this.r.some(t=>t.test(r))&&!!this.e.some(t=>t.test(r))}}class i extends n{constructor(t,e,r){super(({url:e})=>{const r=t.exec(e.href);return r?e.origin!==location.origin&&0!==r.index?null:r.slice(1):null},e,r)}}class u{constructor(){this.s=new Map}addFetchListener(){self.addEventListener("fetch",t=>{const{request:e}=t,r=this.handleRequest({request:e,event:t});r&&t.respondWith(r)})}addCacheListener(){self.addEventListener("message",t=>{if("CACHE_URLS"===t.data.type&&"workbox-window"===t.data.meta){const{urlsToCache:e}=t.data.payload;for(const r of e){const e=new Request(r);this.handleRequest({request:e,event:t})}}})}handleRequest({request:t,event:e}){const r=new URL(t.url,location);if(!r.protocol.startsWith("http"))return;let s,{params:n,route:o}=this.findMatchingRoute({url:r,request:t,event:e}),i=o&&o.handler;if(!i&&this.n&&(i=this.n),i){try{s=i.handle({url:r,request:t,event:e,params:n})}catch(t){s=Promise.reject(t)}return s&&this.o&&(s=s.catch(t=>this.o.handle({url:r,event:e,err:t}))),s}}findMatchingRoute({url:t,request:e,event:r}){const s=this.s.get(e.method)||[];for(const n of s){let s,o=n.match({url:t,request:e,event:r});if(o)return Array.isArray(o)&&o.length>0?s=o:o.constructor===Object&&Object.keys(o).length>0&&(s=o),{route:n,params:s}}return{}}setDefaultHandler(t){this.n=s(t)}setCatchHandler(t){this.o=s(t)}registerRoute(t){this.s.has(t.method)||this.s.set(t.method,[]),this.s.get(t.method).push(t)}unregisterRoute(e){if(!this.s.has(e.method))throw new t.WorkboxError("unregister-route-but-not-found-with-method",{method:e.method});const r=this.s.get(e.method).indexOf(e);if(!(r>-1))throw new t.WorkboxError("unregister-route-route-not-registered");this.s.get(e.method).splice(r,1)}}class c extends u{constructor(){super(),this.addFetchListener(),this.addCacheListener()}registerRoute(e,r,s="GET"){let o;if("string"==typeof e){const t=new URL(e,location);o=new n(({url:e})=>e.href===t.href,r,s)}else if(e instanceof RegExp)o=new i(e,r,s);else if("function"==typeof e)o=new n(e,r,s);else{if(!(e instanceof n))throw new t.WorkboxError("unsupported-route-type",{moduleName:"workbox-routing",className:"DefaultRouter",funcName:"registerRoute",paramName:"capture"});o=e}return super.registerRoute(o),o}registerNavigationRoute(t,r={}){const s=e.cacheNames.getPrecacheName(r.cacheName),n=new o(()=>caches.match(t,{cacheName:s}).then(e=>{if(e)return e;throw new Error(`The cache ${s} did not have an entry for `+`${t}.`)}).catch(e=>fetch(t)),{whitelist:r.whitelist,blacklist:r.blacklist});return super.registerRoute(n),n}}var a=Object.freeze({DefaultRouter:c,RegExpRoute:i,Route:n,Router:u,NavigationRoute:o}),h=new c;return Object.assign(h,a)}(workbox.core._private,workbox.core._private); | ||
//# sourceMappingURL=workbox-routing.prod.js.map |
{ | ||
"name": "workbox-routing", | ||
"version": "3.6.2", | ||
"license": "Apache-2.0", | ||
"version": "4.0.0-alpha.0", | ||
"license": "MIT", | ||
"author": "Google's Web DevRel Team", | ||
@@ -30,4 +30,5 @@ "description": "A service worker helper library to route request URLs to handlers.", | ||
"dependencies": { | ||
"workbox-core": "^3.6.2" | ||
} | ||
"workbox-core": "^4.0.0-alpha.0" | ||
}, | ||
"gitHead": "db1fb73fd32fbd5cbf42e246e6144011a5c6edc2" | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
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
Mixed license
License(Experimental) Package contains multiple licenses.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
Unidentified License
License(Experimental) Something that seems like a license was found, but its contents could not be matched with a known license.
Found 4 instances 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
Unidentified License
License(Experimental) Something that seems like a license was found, but its contents could not be matched with a known license.
Found 1 instance in 1 package
20
1718
112588
5
1
25
+ Addedworkbox-core@4.3.1(transitive)
- Removedworkbox-core@3.6.3(transitive)
Updatedworkbox-core@^4.0.0-alpha.0