From f67bc1a7c69da54b600191b938f809c24881ef51 Mon Sep 17 00:00:00 2001 From: Jeff Posnick Date: Tue, 18 Oct 2016 12:49:48 -0400 Subject: [PATCH] New tagged release - v3.4.0 --- LICENSE | 201 ++++++++++++++++++ README.md | 67 ++++++ bower.json | 14 ++ companion.js | 23 ++ docs/_config.yml | 3 + docs/_data/releases.yml | 1 + docs/api.md | 103 +++++++++ docs/index.md | 60 ++++++ .../_includes/components/footer.html | 27 +++ .../components/nav-drawer-docs-entry.html | 31 +++ .../_includes/components/nav-drawer.html | 31 +++ .../_includes/components/site-header.html | 15 ++ docs/jekyll-theme/_includes/html-head.html | 21 ++ docs/jekyll-theme/_includes/svgs/github.svg | 16 ++ docs/jekyll-theme/_includes/svgs/gplus.svg | 22 ++ docs/jekyll-theme/_includes/svgs/menu.svg | 4 + docs/jekyll-theme/_includes/svgs/twitter.svg | 24 +++ docs/jekyll-theme/_includes/variables.html | 25 +++ docs/jekyll-theme/_layouts/default.html | 14 ++ docs/jekyll-theme/_layouts/index.html | 14 ++ docs/jekyll-theme/_layouts/jsdoc.html | 14 ++ docs/jekyll-theme/scripts/detabinator.js | 70 ++++++ docs/jekyll-theme/scripts/side-nav.js | 146 +++++++++++++ .../styles/components/code-styles.css | 1 + .../jekyll-theme/styles/components/footer.css | 1 + .../styles/components/nav-drawer.css | 1 + .../styles/components/page-header.css | 1 + .../styles/components/site-header.css | 1 + docs/jekyll-theme/styles/jsdoc/details.css | 1 + docs/jekyll-theme/styles/jsdoc/method.css | 1 + docs/jekyll-theme/styles/main.css | 1 + docs/jekyll-theme/styles/variables/colors.css | 0 docs/jekyll-theme/styles/variables/dimens.css | 0 docs/jekyll-theme/third_party/prism/prism.css | 1 + docs/jekyll-theme/third_party/prism/prism.js | 9 + docs/recipes.md | 16 ++ docs/recipes/cache-expiration-options/app.js | 55 +++++ .../cache-expiration-options/index.html | 74 +++++++ .../service-worker.js | 38 ++++ .../cache-expiration-options/styles.css | 10 + docs/usage.md | 132 ++++++++++++ lib/helpers.js | 183 ++++++++++++++++ lib/idb-cache-expiration.js | 158 ++++++++++++++ lib/listeners.js | 75 +++++++ lib/options.js | 40 ++++ lib/route.js | 60 ++++++ lib/router.js | 133 ++++++++++++ lib/strategies/cacheFirst.js | 32 +++ lib/strategies/cacheOnly.js | 26 +++ lib/strategies/fastest.js | 53 +++++ lib/strategies/index.js | 22 ++ lib/strategies/networkFirst.js | 94 ++++++++ lib/strategies/networkOnly.js | 24 +++ lib/sw-toolbox.js | 46 ++++ package.json | 55 +++++ sw-toolbox.js | 16 ++ sw-toolbox.js.map | 1 + 57 files changed, 2307 insertions(+) create mode 100644 LICENSE create mode 100644 README.md create mode 100644 bower.json create mode 100644 companion.js create mode 100644 docs/_config.yml create mode 100644 docs/_data/releases.yml create mode 100644 docs/api.md create mode 100644 docs/index.md create mode 100644 docs/jekyll-theme/_includes/components/footer.html create mode 100644 docs/jekyll-theme/_includes/components/nav-drawer-docs-entry.html create mode 100644 docs/jekyll-theme/_includes/components/nav-drawer.html create mode 100644 docs/jekyll-theme/_includes/components/site-header.html create mode 100644 docs/jekyll-theme/_includes/html-head.html create mode 100644 docs/jekyll-theme/_includes/svgs/github.svg create mode 100644 docs/jekyll-theme/_includes/svgs/gplus.svg create mode 100644 docs/jekyll-theme/_includes/svgs/menu.svg create mode 100644 docs/jekyll-theme/_includes/svgs/twitter.svg create mode 100644 docs/jekyll-theme/_includes/variables.html create mode 100644 docs/jekyll-theme/_layouts/default.html create mode 100644 docs/jekyll-theme/_layouts/index.html create mode 100644 docs/jekyll-theme/_layouts/jsdoc.html create mode 100644 docs/jekyll-theme/scripts/detabinator.js create mode 100644 docs/jekyll-theme/scripts/side-nav.js create mode 100644 docs/jekyll-theme/styles/components/code-styles.css create mode 100644 docs/jekyll-theme/styles/components/footer.css create mode 100644 docs/jekyll-theme/styles/components/nav-drawer.css create mode 100644 docs/jekyll-theme/styles/components/page-header.css create mode 100644 docs/jekyll-theme/styles/components/site-header.css create mode 100644 docs/jekyll-theme/styles/jsdoc/details.css create mode 100644 docs/jekyll-theme/styles/jsdoc/method.css create mode 100644 docs/jekyll-theme/styles/main.css create mode 100644 docs/jekyll-theme/styles/variables/colors.css create mode 100644 docs/jekyll-theme/styles/variables/dimens.css create mode 100644 docs/jekyll-theme/third_party/prism/prism.css create mode 100644 docs/jekyll-theme/third_party/prism/prism.js create mode 100644 docs/recipes.md create mode 100644 docs/recipes/cache-expiration-options/app.js create mode 100644 docs/recipes/cache-expiration-options/index.html create mode 100644 docs/recipes/cache-expiration-options/service-worker.js create mode 100644 docs/recipes/cache-expiration-options/styles.css create mode 100644 docs/usage.md create mode 100644 lib/helpers.js create mode 100644 lib/idb-cache-expiration.js create mode 100644 lib/listeners.js create mode 100644 lib/options.js create mode 100644 lib/route.js create mode 100644 lib/router.js create mode 100644 lib/strategies/cacheFirst.js create mode 100644 lib/strategies/cacheOnly.js create mode 100644 lib/strategies/fastest.js create mode 100644 lib/strategies/index.js create mode 100644 lib/strategies/networkFirst.js create mode 100644 lib/strategies/networkOnly.js create mode 100644 lib/sw-toolbox.js create mode 100644 package.json create mode 100644 sw-toolbox.js create mode 100644 sw-toolbox.js.map diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3338b3f --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright ${copyright_attribution} + + 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 + + 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3695a33 --- /dev/null +++ b/README.md @@ -0,0 +1,67 @@ +# Service Worker Toolbox + +[![Build Status](https://travis-ci.org/GoogleChrome/sw-toolbox.svg?branch=master)](https://travis-ci.org/GoogleChrome/sw-toolbox) [![Dependency Status](https://david-dm.org/googlechrome/sw-toolbox.svg)](https://david-dm.org/googlechrome/sw-toolbox) [![devDependency Status](https://david-dm.org/googlechrome/sw-toolbox/dev-status.svg)](https://david-dm.org/googlechrome/sw-toolbox#info=devDependencies) + +> A collection of tools for [service workers](https://w3c.github.io/ServiceWorker/) + +Service Worker Toolbox provides some simple helpers for use in creating your own service workers. Specifically, it provides common caching patterns and an [expressive approach](https://googlechrome.github.io/sw-toolbox/docs/master/tutorial-api.html#expressive-approach) to using those strategies for runtime requests. If you're not sure what service workers are or what they are for, start with [the explainer doc](https://github.com/slightlyoff/ServiceWorker/blob/master/explainer.md). + +## Install + +Service Worker Toolbox is available through Bower, npm or direct from GitHub: + +`bower install --save sw-toolbox` + +`npm install --save sw-toolbox` + +`git clone https://github.com/GoogleChrome/sw-toolbox.git` + +### Register your service worker + +From your registering page, register your service worker in the normal way. For example: + +```javascript +navigator.serviceWorker.register('my-service-worker.js'); +``` + +As implemented in Chrome 40 or later, a service worker must exist at the root of the scope that you intend it to control, or higher. So if you want all of the pages under `/myapp/` to be controlled by the worker, the worker script itself must be served from either `/` or `/myapp/`. The default scope is the containing path of the service worker script. + +For even lower friction, you can instead include the Service Worker Toolbox companion script in your HTML as shown below. Be aware that this is not customizable. If you need to do anything fancier than register with a default scope, you'll need to use the standard registration. + +```html + +``` + +### Add Service Worker Toolbox to your service worker script + +In your service worker you just need to use `importScripts` to load Service Worker Toolbox: + +```javascript +importScripts('bower_components/sw-toolbox/sw-toolbox.js'); // Update path to match your own setup. +``` + +### Use the toolbox + +To understand how to use the toolbox read the [Usage](https://googlechrome.github.io/sw-toolbox/docs/master/tutorial-usage) and [API](https://googlechrome.github.io/sw-toolbox/docs/master/tutorial-api) documentation. + +## Support + +If you’ve found an error in this library, please file an issue at https://github.com/GoogleChrome/sw-toolbox/issues. + +Patches are encouraged, and may be submitted by forking this project and submitting a [pull request through this GitHub repo](https://github.com/GoogleChrome/sw-toolbox/pulls). + +## License + +Copyright 2015-2016 Google, Inc. + +Licensed under the [Apache License, Version 2.0](LICENSE) (the "License"); +you may not use this file except in compliance with the License. You may +obtain a copy of the License at + + 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. diff --git a/bower.json b/bower.json new file mode 100644 index 0000000..43bb552 --- /dev/null +++ b/bower.json @@ -0,0 +1,14 @@ +{ + "name": "sw-toolbox", + "main": "sw-toolbox.js", + "moduleType": [ + "globals" + ], + "license": "Apache-2.0", + "ignore": [ + "**/.*", + "lib", + "tests", + "gulpfile.js" + ] +} diff --git a/companion.js b/companion.js new file mode 100644 index 0000000..a332ecc --- /dev/null +++ b/companion.js @@ -0,0 +1,23 @@ +/* + 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 + + 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. +*/ +(function() { + 'use strict'; + var workerScript = document.currentScript && document.currentScript.dataset.serviceWorker; + + if (workerScript && 'serviceWorker' in navigator) { + navigator.serviceWorker.register(workerScript); + } +})(); diff --git a/docs/_config.yml b/docs/_config.yml new file mode 100644 index 0000000..c0b7009 --- /dev/null +++ b/docs/_config.yml @@ -0,0 +1,3 @@ +source: . +layouts_dir: ./jekyll-theme/_layouts/ +includes_dir: ./jekyll-theme/_includes/ diff --git a/docs/_data/releases.yml b/docs/_data/releases.yml new file mode 100644 index 0000000..5310c86 --- /dev/null +++ b/docs/_data/releases.yml @@ -0,0 +1 @@ +# Auto-generated from the npm-publish-scripts module diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..9e9e3e6 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,103 @@ +--- +layout: index +title: "API" +navigation_weight: 1 +--- + +## Options + +All options can be specified globally via properties of `toolbox.options`. +Any individual options can be configured on a per-handler basis, via the `Object` passed as the +third parameter to `toolbox.router` methods. + +### debug [Boolean] +Determines whether extra information is logged to the browser's console. + +_Default_: `false` + +### networkTimeoutSeconds [Number] +A timeout that applies to the `toolbox.networkFirst` built-in handler. +If `networkTimeoutSeconds` is set, then any network requests that take longer than that amount of time +will automatically fall back to the cached response if one exists. When +`networkTimeoutSeconds` is not set, the browser's native networking timeout logic applies. + +_Default_: `null` + +### cache [Object] +Various properties of `cache` control the behavior of the default cache when set via +`toolbox.options.cache`, or the cache used by a specific request handler. + +### cache.name [String] +The name of the [`Cache`](https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cache) +used to store [`Response`](https://fetch.spec.whatwg.org/#response-class) objects. Using a unique name +allows you to customize the cache's maximum size and age of entries. + +_Default_: Generated at runtime based on the service worker's `registration.scope` value. + +### cache.maxEntries [Number] +Imposes a least-recently used cache expiration policy +on entries cached via the various built-in handlers. You can use this with a cache that's dedicated +to storing entries for a dynamic set of resources with no natural limit. Setting `cache.maxEntries` to, e.g., +`10` would mean that after the 11th entry is cached, the least-recently used entry would be +automatically deleted. The cache should never end up growing beyond `cache.maxEntries` entries. +This option will only take effect if `cache.name` is also set. +It can be used alone or in conjunction with `cache.maxAgeSeconds`. + +_Default_: `null` + +### cache.maxAgeSeconds [Number] +Imposes a maximum age for cache entries, in seconds. +You can use this with a cache that's dedicated to storing entries for a dynamic set of resources +with no natural limit. Setting `cache.maxAgeSeconds` to, e.g., `60 * 60 * 24` would mean that any +entries older than a day would automatically be deleted. +This option will only take effect if `cache.name` is also set. +It can be used alone or in conjunction with `cache.maxEntries`. + +_Default_: `null` + +## Handlers + +There are five built-in handlers to cover the most common network strategies. For more information about offline strategies see the [Offline Cookbook](http://jakearchibald.com/2014/offline-cookbook/). + +### `toolbox.networkFirst` +Try to handle the request by fetching from the network. If it succeeds, store the response in the cache. Otherwise, try to fulfill the request from the cache. This is the strategy to use for basic read-through caching. It's also good for API requests where you always want the freshest data when it is available but would rather have stale data than no data. + +### `toolbox.cacheFirst` +If the request matches a cache entry, respond with that. Otherwise try to fetch the resource from the network. If the network request succeeds, update the cache. This option is good for resources that don't change, or have some other update mechanism. + +### `toolbox.fastest` +Request the resource from both the cache and the network in parallel. Respond with whichever returns first. Usually this will be the cached version, if there is one. On the one hand this strategy will always make a network request, even if the resource is cached. On the other hand, if/when the network request completes the cache is updated, so that future cache reads will be more up-to-date. + +### `toolbox.cacheOnly` +Resolve the request from the cache, or fail. This option is good for when you need to guarantee that no network request will be made, for example saving battery on mobile. + +### `toolbox.networkOnly` +Handle the request by trying to fetch the URL from the network. If the fetch fails, fail the request. Essentially the same as not creating a route for the URL at all. + +

Methods

+ +### `toolbox.router.get(urlPattern, handler, options)` +### `toolbox.router.post(urlPattern, handler, options)` +### `toolbox.router.put(urlPattern, handler, options)` +### `toolbox.router.delete(urlPattern, handler, options)` +### `toolbox.router.head(urlPattern, handler, options)` +Create a route that causes requests for URLs matching `urlPattern` to be resolved by calling `handler`. Matches requests using the GET, POST, PUT, DELETE or HEAD HTTP methods respectively. + +- `urlPattern` - an Express style route. See the docs for the [path-to-regexp](https://github.com/pillarjs/path-to-regexp) module for the full syntax +- `handler` - a request handler, as [described above](#using-request-handlers) +- `options` - an object containing options for the route. This options object will be passed to the request handler. The `origin` option is specific to the router methods, and can be either an exact string or a Regexp against which the origin of the Request must match for the route to be used. + +### `toolbox.router.any(urlPattern, handler, options)` +Like `toolbox.router.get`, etc., but matches any HTTP method. + +### `toolbox.router.default` +Takes a function to use as the request handler for any GET request that does not match a route. + +### `toolbox.precache(arrayOfURLs)` +Add each URL in arrayOfURLs to the list of resources that should be cached during the service worker install step. Note that this needs to be called before the install event is triggered, so you should do it on the first run of your script. + +### `toolbox.cache(url, options)` +Causes the resource at `url` to be added to the cache and returns a Promise that resolves with void. The `options` parameter supports the `debug` and `cache` [global options](#global-options). + +### `toolbox.uncache(url, options)` +Causes the resource at `url` to be removed from the cache and returns a Promise that resolves to true if the cache entry is deleted. The `options` parameter supports the `debug` and `cache` [global options](#global-options). diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..4be0931 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,60 @@ +--- +layout: index +title: "SW Toolbox" +navigation_weight: 0 +--- + +# Why + +Service Worker Toolbox (or SW-Toolbox) provides some simple helpers for use +in creating your own service workers. Specifically, it provides common caching +patterns and an [expressive approach]({{ project_root_url }}/api#expressive-approach) +to using those strategies for runtime requests. If you're not sure what +service workers are or what they are for, start with +[the explainer doc](https://github.com/slightlyoff/ServiceWorker/blob/master/explainer.md). + +# Install + +Service Worker Toolbox is available through Bower, npm or direct from GitHub: + +`bower install --save sw-toolbox` + +`npm install --save sw-toolbox` + +`git clone https://github.com/GoogleChrome/sw-toolbox.git` + +# Usage + +### Register your service worker + +From your registering page, register your service worker in the normal way. +For example: + +```javascript +navigator.serviceWorker.register('my-service-worker.js'); +``` +As implemented in Chrome 40 or later, a service worker must exist at the root +of the scope that you intend it to control, or higher. So if you want all of +the pages under `/myapp/` to be controlled by the worker, the worker script +itself must be served from either `/` or `/myapp/`. The default scope is the +containing path of the service worker script. + +For even lower friction you can instead include the Service Worker Toolbox +companion script in your HTML as shown below. Be aware that this is not +customizable. If you need to do anything fancier than registering with a +default scope, you'll need to use the standard registration. + +```html + +``` + +### Add Service Worker Toolbox to your service worker script + +In your service worker you just need to use `importScripts` to load Service Worker Toolbox + +```javascript +importScripts('bower_components/sw-toolbox/sw-toolbox.js'); // Update path to match your own setup +``` + +For more information on how to use the toolbox read +the [usage]({{ project_root_url }}/usage) and [api]({{ project_root_url }}/api) documentation. diff --git a/docs/jekyll-theme/_includes/components/footer.html b/docs/jekyll-theme/_includes/components/footer.html new file mode 100644 index 0000000..85d924f --- /dev/null +++ b/docs/jekyll-theme/_includes/components/footer.html @@ -0,0 +1,27 @@ + diff --git a/docs/jekyll-theme/_includes/components/nav-drawer-docs-entry.html b/docs/jekyll-theme/_includes/components/nav-drawer-docs-entry.html new file mode 100644 index 0000000..fb52009 --- /dev/null +++ b/docs/jekyll-theme/_includes/components/nav-drawer-docs-entry.html @@ -0,0 +1,31 @@ +{% if include.docsPath %} + {% capture docsUrl %}{{ project_root_url }}{{ include.docsPath }}{% endcapture %} +
  • + + {{ include.text }} + +
  • + + {% capture filename %}{{ page.url | split: "/" | last }}{% endcapture %} + {% capture currentUrl %}{{ page.url | remove: filename | remove: "//" }}{% endcapture %} + {% capture filteredDocsUrl %}{{ docsUrl | append: "/" }}{% endcapture %} + + {% if filteredDocsUrl == currentUrl and page.jsdocNav %} +
  • + +
  • + {% endif %} +{% endif %} diff --git a/docs/jekyll-theme/_includes/components/nav-drawer.html b/docs/jekyll-theme/_includes/components/nav-drawer.html new file mode 100644 index 0000000..567564a --- /dev/null +++ b/docs/jekyll-theme/_includes/components/nav-drawer.html @@ -0,0 +1,31 @@ +{% include variables.html %} + diff --git a/docs/jekyll-theme/_includes/components/site-header.html b/docs/jekyll-theme/_includes/components/site-header.html new file mode 100644 index 0000000..f09a498 --- /dev/null +++ b/docs/jekyll-theme/_includes/components/site-header.html @@ -0,0 +1,15 @@ + diff --git a/docs/jekyll-theme/_includes/html-head.html b/docs/jekyll-theme/_includes/html-head.html new file mode 100644 index 0000000..6ff1c35 --- /dev/null +++ b/docs/jekyll-theme/_includes/html-head.html @@ -0,0 +1,21 @@ +{% include variables.html %} + + + + + + {% if page.title %}{{ page.title | escape }}{% else %}{{ project_title | escape }}{% endif %} + + + + + + + + + + {% if page.layout == 'jsdoc' %} + + + {% endif %} + diff --git a/docs/jekyll-theme/_includes/svgs/github.svg b/docs/jekyll-theme/_includes/svgs/github.svg new file mode 100644 index 0000000..14625a5 --- /dev/null +++ b/docs/jekyll-theme/_includes/svgs/github.svg @@ -0,0 +1,16 @@ + + + + Shape + Created with Sketch. + + + + + + + + + + + \ No newline at end of file diff --git a/docs/jekyll-theme/_includes/svgs/gplus.svg b/docs/jekyll-theme/_includes/svgs/gplus.svg new file mode 100644 index 0000000..19320e7 --- /dev/null +++ b/docs/jekyll-theme/_includes/svgs/gplus.svg @@ -0,0 +1,22 @@ + +image/svg+xml \ No newline at end of file diff --git a/docs/jekyll-theme/_includes/svgs/menu.svg b/docs/jekyll-theme/_includes/svgs/menu.svg new file mode 100644 index 0000000..3521f19 --- /dev/null +++ b/docs/jekyll-theme/_includes/svgs/menu.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/docs/jekyll-theme/_includes/svgs/twitter.svg b/docs/jekyll-theme/_includes/svgs/twitter.svg new file mode 100644 index 0000000..30aa314 --- /dev/null +++ b/docs/jekyll-theme/_includes/svgs/twitter.svg @@ -0,0 +1,24 @@ + +image/svg+xml \ No newline at end of file diff --git a/docs/jekyll-theme/_includes/variables.html b/docs/jekyll-theme/_includes/variables.html new file mode 100644 index 0000000..978e21c --- /dev/null +++ b/docs/jekyll-theme/_includes/variables.html @@ -0,0 +1,25 @@ +{% if site.data.customize.project_title %} + {% assign project_title = site.data.customize.project_title %} +{% elsif site.github.project_title %} + {% assign project_title = site.github.project_title %} +{% endif %} + +{% if jekyll.environment == 'development' %} + {% assign project_root_url = '' %} +{% else %} + {% assign project_root_url = site.github.url | replace: 'http://', '//'%} +{% endif %} + +{% if site.data.customize.project_owner %} + {% assign project_owner = site.data.customize.project_owner %} + {% assign project_owner_url = site.data.customize.project_owner_url %} +{% elsif site.github.owner_name %} + {% assign project_owner = site.github.owner_name %} + {% assign project_owner_url = site.github.owner_url %} +{% endif %} + +{% if site.data.customize.project_tagline %} + {% assign project_tagline = site.data.customize.project_tagline %} +{% elsif site.github.project_tagline %} + {% assign project_tagline = site.github.project_tagline %} +{% endif %} diff --git a/docs/jekyll-theme/_layouts/default.html b/docs/jekyll-theme/_layouts/default.html new file mode 100644 index 0000000..6819ed3 --- /dev/null +++ b/docs/jekyll-theme/_layouts/default.html @@ -0,0 +1,14 @@ + + + + {% include html-head.html %} + + + + {{ content }} + + + + + + diff --git a/docs/jekyll-theme/_layouts/index.html b/docs/jekyll-theme/_layouts/index.html new file mode 100644 index 0000000..9ec6f1d --- /dev/null +++ b/docs/jekyll-theme/_layouts/index.html @@ -0,0 +1,14 @@ +--- +layout: default +--- +{% include variables.html %} + +{% include components/site-header.html title=project_title subtitle=project_tagline %} + +{% include components/nav-drawer.html %} + +
    + {{ content }} +
    + +{% include components/footer.html made_by='variables.project_owner' made_by_url='varaibles.project_owner_url' %} diff --git a/docs/jekyll-theme/_layouts/jsdoc.html b/docs/jekyll-theme/_layouts/jsdoc.html new file mode 100644 index 0000000..6094063 --- /dev/null +++ b/docs/jekyll-theme/_layouts/jsdoc.html @@ -0,0 +1,14 @@ +--- +layout: default +--- +{% include variables.html %} + +{% include components/site-header.html title=project_title subtitle=project_tagline %} + +{% include components/nav-drawer.html %} + +
    + {{ content }} +
    + +{% include components/footer.html made_by='variables.project_owner' made_by_url='varaibles.project_owner_url' %} diff --git a/docs/jekyll-theme/scripts/detabinator.js b/docs/jekyll-theme/scripts/detabinator.js new file mode 100644 index 0000000..a67325c --- /dev/null +++ b/docs/jekyll-theme/scripts/detabinator.js @@ -0,0 +1,70 @@ +/** + * + * 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 + * + * 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. + */ + + +/** + * Usage: + * const detabinator = new Detabinator(element); + * detabinator.inert = true; // Sets all focusable children of element to tabindex=-1 + * detabinator.inert = false; // Restores all focusable children of element + * Limitations: Doesn't support Shadow DOM v0 :P + */ + +class Detabinator { + constructor(element) { + if (!element) { + throw new Error('Missing required argument. new Detabinator needs an element reference'); + } + this._inert = false; + this._focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex], [contenteditable]'; + this._focusableElements = Array.from( + element.querySelectorAll(this._focusableElementsString) + ); + } + + get inert() { + return this._inert; + } + + set inert(isInert) { + if (this._inert === isInert) { + return; + } + + this._inert = isInert; + + this._focusableElements.forEach((child) => { + if (isInert) { + // If the child has an explict tabindex save it + if (child.hasAttribute('tabindex')) { + child.__savedTabindex = child.tabIndex; + } + // Set ALL focusable children to tabindex -1 + child.setAttribute('tabindex', -1); + } else { + // If the child has a saved tabindex, restore it + // Because the value could be 0, explicitly check that it's not false + if (child.__savedTabindex === 0 || child.__savedTabindex) { + return child.setAttribute('tabindex', child.__savedTabindex); + } else { + // Remove tabindex from ANY REMAINING children + child.removeAttribute('tabindex'); + } + } + }); + } +} diff --git a/docs/jekyll-theme/scripts/side-nav.js b/docs/jekyll-theme/scripts/side-nav.js new file mode 100644 index 0000000..b3d9f5d --- /dev/null +++ b/docs/jekyll-theme/scripts/side-nav.js @@ -0,0 +1,146 @@ +/** + * + * 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 + * + * 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 strict'; + +class SideNav { + constructor () { + this.showButtonEl = document.querySelector('.js-menu-show'); + this.hideButtonEl = document.querySelector('.js-menu-hide'); + this.sideNavEl = document.querySelector('.js-side-nav'); + this.sideNavContainerEl = document.querySelector('.js-side-nav-container'); + // Control whether the container's children can be focused + // Set initial state to inert since the drawer is offscreen + this.detabinator = new Detabinator(this.sideNavContainerEl); + this.detabinator.inert = true; + + this.showSideNav = this.showSideNav.bind(this); + this.hideSideNav = this.hideSideNav.bind(this); + this.blockClicks = this.blockClicks.bind(this); + this.onTouchStart = this.onTouchStart.bind(this); + this.onTouchMove = this.onTouchMove.bind(this); + this.onTouchEnd = this.onTouchEnd.bind(this); + this.onTransitionEnd = this.onTransitionEnd.bind(this); + this.update = this.update.bind(this); + + this.startX = 0; + this.currentX = 0; + this.touchingSideNav = false; + + this.supportsPassive = undefined; + this.addEventListeners(); + } + + // apply passive event listening if it's supported + applyPassive () { + if (this.supportsPassive !== undefined) { + return this.supportsPassive ? {passive: true} : false; + } + // feature detect + let isSupported = false; + try { + document.addEventListener('test', null, {get passive () { + isSupported = true; + }}); + } catch (e) { } + this.supportsPassive = isSupported; + return this.applyPassive(); + } + + addEventListeners () { + this.showButtonEl.addEventListener('click', this.showSideNav); + this.hideButtonEl.addEventListener('click', this.hideSideNav); + this.sideNavEl.addEventListener('click', this.hideSideNav); + this.sideNavContainerEl.addEventListener('click', this.blockClicks); + + this.sideNavEl.addEventListener('touchstart', this.onTouchStart, this.applyPassive()); + this.sideNavEl.addEventListener('touchmove', this.onTouchMove, this.applyPassive()); + this.sideNavEl.addEventListener('touchend', this.onTouchEnd); + } + + onTouchStart (evt) { + if (!this.sideNavEl.classList.contains('side-nav--visible')) + return; + + this.startX = evt.touches[0].pageX; + this.currentX = this.startX; + + this.touchingSideNav = true; + requestAnimationFrame(this.update); + } + + onTouchMove (evt) { + if (!this.touchingSideNav) + return; + + this.currentX = evt.touches[0].pageX; + const translateX = Math.min(0, this.currentX - this.startX); + + if (translateX < 0) { + evt.preventDefault(); + } + } + + onTouchEnd (evt) { + if (!this.touchingSideNav) + return; + + this.touchingSideNav = false; + + const translateX = Math.min(0, this.currentX - this.startX); + this.sideNavContainerEl.style.transform = ''; + + if (translateX < 0) { + this.hideSideNav(); + } + } + + update () { + if (!this.touchingSideNav) + return; + + requestAnimationFrame(this.update); + + const translateX = Math.min(0, this.currentX - this.startX); + this.sideNavContainerEl.style.transform = `translateX(${translateX}px)`; + } + + blockClicks (evt) { + evt.stopPropagation(); + } + + onTransitionEnd (evt) { + this.sideNavEl.classList.remove('side-nav--animatable'); + this.sideNavEl.removeEventListener('transitionend', this.onTransitionEnd); + } + + showSideNav () { + this.sideNavEl.classList.add('side-nav--animatable'); + this.sideNavEl.classList.add('side-nav--visible'); + this.detabinator.inert = false; + this.sideNavEl.addEventListener('transitionend', this.onTransitionEnd); + } + + hideSideNav () { + this.sideNavEl.classList.add('side-nav--animatable'); + this.sideNavEl.classList.remove('side-nav--visible'); + this.detabinator.inert = true; + this.sideNavEl.addEventListener('transitionend', this.onTransitionEnd); + } +} + +new SideNav(); diff --git a/docs/jekyll-theme/styles/components/code-styles.css b/docs/jekyll-theme/styles/components/code-styles.css new file mode 100644 index 0000000..08ce23d --- /dev/null +++ b/docs/jekyll-theme/styles/components/code-styles.css @@ -0,0 +1 @@ +code[class*=language-],pre[class*=language-]{color:#000;background:none;text-shadow:0 1px #fff;font-family:Consolas,Monaco,Andale Mono,Ubuntu Mono,monospace;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;tab-size:4;-webkit-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-]::-moz-selection,code[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-]::selection,code[class*=language-] ::selection,pre[class*=language-]::selection,pre[class*=language-] ::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#a67f59;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}figure.highlight{margin:0}code,code[class*=language-],pre,pre[class*=language-]{background-color:rgba(0,0,0,.06);border-radius:3px;white-space:pre-wrap;text-shadow:none}pre,pre[class*=language-]{padding:16px}code,code[class*=language-]{display:inline-block;font-size:12px}code[class*=language-],pre[class*=language-]{color:rgba(0,0,0,.87)}code:after,code:before,code[class*=language-]:after,code[class*=language-]:before{letter-spacing:-.2em;content:"\00a0"}pre[class*=language-] code[class*=language-],pre code{width:100%;font-size:inherit;background-color:transparent;padding:0;box-sizing:border-box;word-break:break-word}pre code:after,pre code:before{content:none}.token.attr-name,.token.builtin,.token.selector,.token.string{color:#e91e63}.token.boolean,.token.constant,.token.number,.token.property,.token.symbol,.token.tag{color:#9d1db3}.token.atrule,.token.attr-value,.token.keyword{color:#00bcd4}.token.cr:before,.token.lf:before{display:none}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url,.token.variable{color:#9d1db3;background:none}.token.function{color:#009688} \ No newline at end of file diff --git a/docs/jekyll-theme/styles/components/footer.css b/docs/jekyll-theme/styles/components/footer.css new file mode 100644 index 0000000..b2ffebd --- /dev/null +++ b/docs/jekyll-theme/styles/components/footer.css @@ -0,0 +1 @@ +footer{height:120px;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-align:stretch;align-items:stretch;-ms-flex-pack:center;justify-content:center;background-color:#212121;color:var(--callout-text-color);padding:32px 40px;font-size:12px}footer a{color:inherit;text-decoration:none}footer .footer-links,footer .social-btns{display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;list-style:none;padding:0;margin:14px 0}footer .social-btn{margin:0 40px}footer .social-btn>svg{width:24px;height:24px} \ No newline at end of file diff --git a/docs/jekyll-theme/styles/components/nav-drawer.css b/docs/jekyll-theme/styles/components/nav-drawer.css new file mode 100644 index 0000000..83fcc3c --- /dev/null +++ b/docs/jekyll-theme/styles/components/nav-drawer.css @@ -0,0 +1 @@ +.side-nav{position:fixed;left:0;top:0;width:100%;height:100%;overflow:hidden;pointer-events:none}.side-nav--visible{pointer-events:auto}.side-nav:before{content:'';display:block;position:absolute;left:0;top:0;width:100%;height:100%;background:rgba(0,0,0,.4);opacity:0;will-change:opacity;transition:opacity .3s cubic-bezier(0,0,.3,1)}.side-nav__container{position:relative;width:90%;max-width:260px;background:#fff;height:100%;box-shadow:2px 0 12px rgba(0,0,0,.4);transform:translateX(-102%);display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;will-change:transform}.side-nav--animatable .side-nav__container{transition:transform .13s cubic-bezier(0,0,.3,1)}.side-nav--visible.side-nav--animatable .side-nav__container{transition:transform .33s cubic-bezier(0,0,.3,1)}.side-nav--visible:before{opacity:1}.side-nav--visible .side-nav__container{transform:none}.side-nav__hide{position:absolute;left:16px;top:16px;background:none;border:none;color:#fff;width:24px;height:24px;padding:0;margin:0} \ No newline at end of file diff --git a/docs/jekyll-theme/styles/components/page-header.css b/docs/jekyll-theme/styles/components/page-header.css new file mode 100644 index 0000000..87181dc --- /dev/null +++ b/docs/jekyll-theme/styles/components/page-header.css @@ -0,0 +1 @@ +.page-header{height:64px;display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;background-color:#37474f;color:#fff;padding:0}.page-header .menu-btn{width:64px;height:64px;min-width:auto;background:none;border:none;padding:20px}.page-header .menu-btn svg{width:24px;height:24px}.page-header h1{width:100%;font-size:13px;line-height:64px;margin:0;padding-right:40px} \ No newline at end of file diff --git a/docs/jekyll-theme/styles/components/site-header.css b/docs/jekyll-theme/styles/components/site-header.css new file mode 100644 index 0000000..59db3b7 --- /dev/null +++ b/docs/jekyll-theme/styles/components/site-header.css @@ -0,0 +1 @@ +.site-header{height:288px;position:relative;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;background-color:#37474f;color:#fff;padding:0}.site-header,.site-header__heading{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.site-header__heading{text-align:center}.site-header__heading h1,.site-header__heading h2{margin:0;padding:0}.site-header__heading h2{opacity:.6}.site-header .menu-btn{position:absolute;top:0;left:0;width:64px;height:64px;min-width:auto;background:none;border:none;padding:20px}.site-header .menu-btn svg{width:24px;height:24px} \ No newline at end of file diff --git a/docs/jekyll-theme/styles/jsdoc/details.css b/docs/jekyll-theme/styles/jsdoc/details.css new file mode 100644 index 0000000..12bd86f --- /dev/null +++ b/docs/jekyll-theme/styles/jsdoc/details.css @@ -0,0 +1 @@ +.is-jsdoc-page .details dd,.is-jsdoc-page .details dt{display:inline-block;margin:0}.is-jsdoc-page .details dd ul{list-style:none;margin:0;padding:0} \ No newline at end of file diff --git a/docs/jekyll-theme/styles/jsdoc/method.css b/docs/jekyll-theme/styles/jsdoc/method.css new file mode 100644 index 0000000..4dbb3fd --- /dev/null +++ b/docs/jekyll-theme/styles/jsdoc/method.css @@ -0,0 +1 @@ +.jsdoc-method p{margin-bottom:8px}.jsdoc-params-heading,.jsdoc-returns-heading{margin:0;padding:8px;background-color:#37474f;color:#fff}.jsdoc-method{margin-bottom:64px} \ No newline at end of file diff --git a/docs/jekyll-theme/styles/main.css b/docs/jekyll-theme/styles/main.css new file mode 100644 index 0000000..c91df49 --- /dev/null +++ b/docs/jekyll-theme/styles/main.css @@ -0,0 +1 @@ +@font-face{font-family:Roboto;font-style:normal;font-weight:300;src:local('Roboto Light'),local('Roboto-Light'),url(https://fonts.gstatic.com/s/roboto/v15/Hgo13k-tfSpn0qi1SFdUfaCWcynf_cDxXwCLxiixG1c.ttf) format('truetype')}@font-face{font-family:Roboto;font-style:normal;font-weight:400;src:local('Roboto'),local('Roboto-Regular'),url(https://fonts.gstatic.com/s/roboto/v15/zN7GBFwfMP4uA6AR0HCoLQ.ttf) format('truetype')}@font-face{font-family:Roboto;font-style:normal;font-weight:500;src:local('Roboto Medium'),local('Roboto-Medium'),url(https://fonts.gstatic.com/s/roboto/v15/RxZJdnzeo3R5zSexge8UUaCWcynf_cDxXwCLxiixG1c.ttf) format('truetype')}@font-face{font-family:Roboto;font-style:normal;font-weight:700;src:local('Roboto Bold'),local('Roboto-Bold'),url(https://fonts.gstatic.com/s/roboto/v15/d-6IYplOFocCacKzxwXSOKCWcynf_cDxXwCLxiixG1c.ttf) format('truetype')}.page-header{height:64px;display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;background-color:#37474f;color:#fff;padding:0}.page-header .menu-btn{width:64px;height:64px;min-width:auto;background:none;border:none;padding:20px}.page-header .menu-btn svg{width:24px;height:24px}.page-header h1{width:100%;font-size:13px;line-height:64px;margin:0;padding-right:40px}.site-header{height:288px;position:relative;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;background-color:#37474f;color:#fff;padding:0}.site-header,.site-header__heading{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.site-header__heading{text-align:center}.site-header__heading h1,.site-header__heading h2{margin:0;padding:0}.site-header__heading h2{opacity:.6}.site-header .menu-btn{position:absolute;top:0;left:0;width:64px;height:64px;min-width:auto;background:none;border:none;padding:20px}.site-header .menu-btn svg{width:24px;height:24px}footer{height:120px;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-align:stretch;align-items:stretch;-ms-flex-pack:center;justify-content:center;background-color:#212121;color:#fff;padding:32px 40px;font-size:12px}footer a{color:inherit;text-decoration:none}footer .footer-links,footer .social-btns{display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;list-style:none;padding:0;margin:14px 0}footer .social-btn{margin:0 40px}footer .social-btn>svg{width:24px;height:24px}code[class*=language-],pre[class*=language-]{color:#000;background:none;text-shadow:0 1px #fff;font-family:Consolas,Monaco,Andale Mono,Ubuntu Mono,monospace;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;tab-size:4;-webkit-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-]::-moz-selection,code[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-]::selection,code[class*=language-] ::selection,pre[class*=language-]::selection,pre[class*=language-] ::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#a67f59;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}figure.highlight{margin:0}code,code[class*=language-],pre,pre[class*=language-]{background-color:rgba(0,0,0,.06);border-radius:3px;white-space:pre-wrap;text-shadow:none}pre,pre[class*=language-]{padding:16px}code,code[class*=language-]{display:inline-block;font-size:12px}code[class*=language-],pre[class*=language-]{color:rgba(0,0,0,.87)}code:after,code:before,code[class*=language-]:after,code[class*=language-]:before{letter-spacing:-.2em;content:"\00a0"}pre[class*=language-] code[class*=language-],pre code{width:100%;font-size:inherit;background-color:transparent;padding:0;box-sizing:border-box;word-break:break-word}pre code:after,pre code:before{content:none}.token.attr-name,.token.builtin,.token.selector,.token.string{color:#e91e63}.token.boolean,.token.constant,.token.number,.token.property,.token.symbol,.token.tag{color:#9d1db3}.token.atrule,.token.attr-value,.token.keyword{color:#00bcd4}.token.cr:before,.token.lf:before{display:none}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url,.token.variable{color:#9d1db3;background:none}.token.function{color:#009688}body,html{width:100%;margin:0;padding:0}body{font-family:Roboto,sans-serif;font-weight:400;line-height:2em;color:#757575}main{max-width:720px;padding:40px;box-sizing:border-box;margin-left:auto;margin-right:auto}p{margin-top:0;margin-bottom:32px}a{color:#37474f;text-decoration:none;font-weight:500}.button,button{display:inline-block;min-width:64px;height:36px;color:#fff;background-color:#37474f;border:none;padding:0 16px;font-size:14px;font-weight:500;text-transform:uppercase;letter-spacing:0;text-align:center;line-height:36px;cursor:pointer}ol,ul{padding-left:20px;line-height:24px}h1{text-transform:uppercase}h1,h2{font-size:16px;font-weight:500;padding-right:60px;margin:40px 0}h3{margin:24px 0}h3,h4{font-size:15px;line-height:25px;font-weight:500;padding-right:60px}h4{margin-top:24px;margin-bottom:16px}h5{margin-bottom:8px}h5,h6{font-size:12px;line-height:25px;font-weight:700;padding-right:60px;margin-top:24px}h6{margin-bottom:0}table{width:100%;margin-bottom:8px}table,td,th{border-style:solid;border-width:1px;border-collapse:collapse}td{padding:4px}td code{background:inherit}.u-center{text-align:center}.side-nav__container ul{padding:0;margin:0 0 0 16px;list-style-type:none}.side-nav__container>ul{margin:0}.side-nav__container ul li.side-nav__title,.side-nav__container ul li a{display:block;padding:12px 16px}.side-nav__container .subheading{display:block;padding:0 16px} \ No newline at end of file diff --git a/docs/jekyll-theme/styles/variables/colors.css b/docs/jekyll-theme/styles/variables/colors.css new file mode 100644 index 0000000..e69de29 diff --git a/docs/jekyll-theme/styles/variables/dimens.css b/docs/jekyll-theme/styles/variables/dimens.css new file mode 100644 index 0000000..e69de29 diff --git a/docs/jekyll-theme/third_party/prism/prism.css b/docs/jekyll-theme/third_party/prism/prism.css new file mode 100644 index 0000000..12218df --- /dev/null +++ b/docs/jekyll-theme/third_party/prism/prism.css @@ -0,0 +1 @@ +code[class*=language-],pre[class*=language-]{color:#000;background:none;text-shadow:0 1px #fff;font-family:Consolas,Monaco,Andale Mono,Ubuntu Mono,monospace;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;tab-size:4;-webkit-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-]::-moz-selection,code[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-]::selection,code[class*=language-] ::selection,pre[class*=language-]::selection,pre[class*=language-] ::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#a67f59;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help} \ No newline at end of file diff --git a/docs/jekyll-theme/third_party/prism/prism.js b/docs/jekyll-theme/third_party/prism/prism.js new file mode 100644 index 0000000..7a5a86a --- /dev/null +++ b/docs/jekyll-theme/third_party/prism/prism.js @@ -0,0 +1,9 @@ +/* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript+bash+git+markdown */ +var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(){var e=/\blang(?:uage)?-(\w+)\b/i,t=0,n=_self.Prism={util:{encode:function(e){return e instanceof a?new a(e.type,n.util.encode(e.content),e.alias):"Array"===n.util.type(e)?e.map(n.util.encode):e.replace(/&/g,"&").replace(/e.length)break e;if(!(v instanceof a)){u.lastIndex=0;var b=u.exec(v),k=1;if(!b&&h&&m!=r.length-1){if(u.lastIndex=y,b=u.exec(e),!b)break;for(var w=b.index+(g?b[1].length:0),_=b.index+b[0].length,A=m,S=y,P=r.length;P>A&&_>S;++A)S+=(r[A].matchedStr||r[A]).length,w>=S&&(++m,y=S);if(r[m]instanceof a||r[A-1].greedy)continue;k=A-m,v=e.slice(y,S),b.index-=y}if(b){g&&(f=b[1].length);var w=b.index+f,b=b[0].slice(f),_=w+b.length,x=v.slice(0,w),O=v.slice(_),j=[m,k];x&&j.push(x);var N=new a(l,c?n.tokenize(b,c):b,d,b,h);j.push(N),O&&j.push(O),Array.prototype.splice.apply(r,j)}}}}}return r},hooks:{all:{},add:function(e,t){var a=n.hooks.all;a[e]=a[e]||[],a[e].push(t)},run:function(e,t){var a=n.hooks.all[e];if(a&&a.length)for(var r,i=0;r=a[i++];)r(t)}}},a=n.Token=function(e,t,n,a,r){this.type=e,this.content=t,this.alias=n,this.matchedStr=a||null,this.greedy=!!r};if(a.stringify=function(e,t,r){if("string"==typeof e)return e;if("Array"===n.util.type(e))return e.map(function(n){return a.stringify(n,t,e)}).join("");var i={type:e.type,content:a.stringify(e.content,t,r),tag:"span",classes:["token",e.type],attributes:{},language:t,parent:r};if("comment"==i.type&&(i.attributes.spellcheck="true"),e.alias){var l="Array"===n.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(i.classes,l)}n.hooks.run("wrap",i);var o="";for(var s in i.attributes)o+=(o?" ":"")+s+'="'+(i.attributes[s]||"")+'"';return"<"+i.tag+' class="'+i.classes.join(" ")+'" '+o+">"+i.content+""},!_self.document)return _self.addEventListener?(_self.addEventListener("message",function(e){var t=JSON.parse(e.data),a=t.language,r=t.code,i=t.immediateClose;_self.postMessage(n.highlight(r,n.languages[a],a)),i&&_self.close()},!1),_self.Prism):_self.Prism;var r=document.currentScript||[].slice.call(document.getElementsByTagName("script")).pop();return r&&(n.filename=r.src,document.addEventListener&&!r.hasAttribute("data-manual")&&("loading"!==document.readyState?window.requestAnimationFrame?window.requestAnimationFrame(n.highlightAll):window.setTimeout(n.highlightAll,16):document.addEventListener("DOMContentLoaded",n.highlightAll))),_self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism); +Prism.languages.markup={comment://,prolog:/<\?[\w\W]+?\?>/,doctype://,cdata://i,tag:{pattern:/<\/?(?!\d)[^\s>\/=$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i,inside:{tag:{pattern:/^<\/?[^\s>\/]+/i,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i,inside:{punctuation:/[=>"']/}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:/&#?[\da-z]{1,8};/i},Prism.hooks.add("wrap",function(a){"entity"===a.type&&(a.attributes.title=a.content.replace(/&/,"&"))}),Prism.languages.xml=Prism.languages.markup,Prism.languages.html=Prism.languages.markup,Prism.languages.mathml=Prism.languages.markup,Prism.languages.svg=Prism.languages.markup; +Prism.languages.css={comment:/\/\*[\w\W]*?\*\//,atrule:{pattern:/@[\w-]+?.*?(;|(?=\s*\{))/i,inside:{rule:/@[\w-]+/}},url:/url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,selector:/[^\{\}\s][^\{\};]*?(?=\s*\{)/,string:/("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/,property:/(\b|\B)[\w-]+(?=\s*:)/i,important:/\B!important\b/i,"function":/[-a-z0-9]+(?=\()/i,punctuation:/[(){};:]/},Prism.languages.css.atrule.inside.rest=Prism.util.clone(Prism.languages.css),Prism.languages.markup&&(Prism.languages.insertBefore("markup","tag",{style:{pattern:/()[\w\W]*?(?=<\/style>)/i,lookbehind:!0,inside:Prism.languages.css,alias:"language-css"}}),Prism.languages.insertBefore("inside","attr-value",{"style-attr":{pattern:/\s*style=("|').*?\1/i,inside:{"attr-name":{pattern:/^\s*style/i,inside:Prism.languages.markup.tag.inside},punctuation:/^\s*=\s*['"]|['"]\s*$/,"attr-value":{pattern:/.+/i,inside:Prism.languages.css}},alias:"language-css"}},Prism.languages.markup.tag)); +Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\w\W]*?\*\//,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0}],string:{pattern:/(["'])(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,"boolean":/\b(true|false)\b/,"function":/[a-z0-9_]+(?=\()/i,number:/\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)\b/i,operator:/--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,punctuation:/[{}[\];(),.:]/}; +Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/,number:/\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/,"function":/[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*(?=\()/i,operator:/--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*\*?|\/|~|\^|%|\.{3}/}),Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^\/])\/(?!\/)(\[.+?]|\\.|[^\/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/,lookbehind:!0,greedy:!0}}),Prism.languages.insertBefore("javascript","string",{"template-string":{pattern:/`(?:\\\\|\\?[^\\])*?`/,greedy:!0,inside:{interpolation:{pattern:/\$\{[^}]+\}/,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}}}),Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/()[\w\W]*?(?=<\/script>)/i,lookbehind:!0,inside:Prism.languages.javascript,alias:"language-javascript"}}),Prism.languages.js=Prism.languages.javascript; +!function(e){var t={variable:[{pattern:/\$?\(\([\w\W]+?\)\)/,inside:{variable:[{pattern:/(^\$\(\([\w\W]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b-?(?:0x[\dA-Fa-f]+|\d*\.?\d+(?:[Ee]-?\d+)?)\b/,operator:/--?|-=|\+\+?|\+=|!=?|~|\*\*?|\*=|\/=?|%=?|<<=?|>>=?|<=?|>=?|==?|&&?|&=|\^=?|\|\|?|\|=|\?|:/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\([^)]+\)|`[^`]+`/,inside:{variable:/^\$\(|^`|\)$|`$/}},/\$(?:[a-z0-9_#\?\*!@]+|\{[^}]+\})/i]};e.languages.bash={shebang:{pattern:/^#!\s*\/bin\/bash|^#!\s*\/bin\/sh/,alias:"important"},comment:{pattern:/(^|[^"{\\])#.*/,lookbehind:!0},string:[{pattern:/((?:^|[^<])<<\s*)(?:"|')?(\w+?)(?:"|')?\s*\r?\n(?:[\s\S])*?\r?\n\2/g,lookbehind:!0,greedy:!0,inside:t},{pattern:/(["'])(?:\\\\|\\?[^\\])*?\1/g,greedy:!0,inside:t}],variable:t.variable,"function":{pattern:/(^|\s|;|\||&)(?:alias|apropos|apt-get|aptitude|aspell|awk|basename|bash|bc|bg|builtin|bzip2|cal|cat|cd|cfdisk|chgrp|chmod|chown|chroot|chkconfig|cksum|clear|cmp|comm|command|cp|cron|crontab|csplit|cut|date|dc|dd|ddrescue|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|du|egrep|eject|enable|env|ethtool|eval|exec|expand|expect|export|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|getopts|git|grep|groupadd|groupdel|groupmod|groups|gzip|hash|head|help|hg|history|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|jobs|join|kill|killall|less|link|ln|locate|logname|logout|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|make|man|mkdir|mkfifo|mkisofs|mknod|more|most|mount|mtools|mtr|mv|mmv|nano|netstat|nice|nl|nohup|notify-send|npm|nslookup|open|op|passwd|paste|pathchk|ping|pkill|popd|pr|printcap|printenv|printf|ps|pushd|pv|pwd|quota|quotacheck|quotactl|ram|rar|rcp|read|readarray|readonly|reboot|rename|renice|remsync|rev|rm|rmdir|rsync|screen|scp|sdiff|sed|seq|service|sftp|shift|shopt|shutdown|sleep|slocate|sort|source|split|ssh|stat|strace|su|sudo|sum|suspend|sync|tail|tar|tee|test|time|timeout|times|touch|top|traceroute|trap|tr|tsort|tty|type|ulimit|umask|umount|unalias|uname|unexpand|uniq|units|unrar|unshar|uptime|useradd|userdel|usermod|users|uuencode|uudecode|v|vdir|vi|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yes|zip)(?=$|\s|;|\||&)/,lookbehind:!0},keyword:{pattern:/(^|\s|;|\||&)(?:let|:|\.|if|then|else|elif|fi|for|break|continue|while|in|case|function|select|do|done|until|echo|exit|return|set|declare)(?=$|\s|;|\||&)/,lookbehind:!0},"boolean":{pattern:/(^|\s|;|\||&)(?:true|false)(?=$|\s|;|\||&)/,lookbehind:!0},operator:/&&?|\|\|?|==?|!=?|<<>|<=?|>=?|=~/,punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];]/};var a=t.variable[1].inside;a["function"]=e.languages.bash["function"],a.keyword=e.languages.bash.keyword,a.boolean=e.languages.bash.boolean,a.operator=e.languages.bash.operator,a.punctuation=e.languages.bash.punctuation}(Prism); +Prism.languages.git={comment:/^#.*/m,deleted:/^[-–].*/m,inserted:/^\+.*/m,string:/("|')(\\?.)*?\1/m,command:{pattern:/^.*\$ git .*$/m,inside:{parameter:/\s(--|-)\w+/m}},coord:/^@@.*@@$/m,commit_sha1:/^commit \w{40}$/m}; +Prism.languages.markdown=Prism.languages.extend("markup",{}),Prism.languages.insertBefore("markdown","prolog",{blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},code:[{pattern:/^(?: {4}|\t).+/m,alias:"keyword"},{pattern:/``.+?``|`[^`\n]+`/,alias:"keyword"}],title:[{pattern:/\w+.*(?:\r?\n|\r)(?:==+|--+)/,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#+.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])([\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:/(^|[^\\])(\*\*|__)(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/,lookbehind:!0,inside:{punctuation:/^\*\*|^__|\*\*$|__$/}},italic:{pattern:/(^|[^\\])([*_])(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/,lookbehind:!0,inside:{punctuation:/^[*_]|[*_]$/}},url:{pattern:/!?\[[^\]]+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)| ?\[[^\]\n]*\])/,inside:{variable:{pattern:/(!?\[)[^\]]+(?=\]$)/,lookbehind:!0},string:{pattern:/"(?:\\.|[^"\\])*"(?=\)$)/}}}}),Prism.languages.markdown.bold.inside.url=Prism.util.clone(Prism.languages.markdown.url),Prism.languages.markdown.italic.inside.url=Prism.util.clone(Prism.languages.markdown.url),Prism.languages.markdown.bold.inside.italic=Prism.util.clone(Prism.languages.markdown.italic),Prism.languages.markdown.italic.inside.bold=Prism.util.clone(Prism.languages.markdown.bold); diff --git a/docs/recipes.md b/docs/recipes.md new file mode 100644 index 0000000..1e2483e --- /dev/null +++ b/docs/recipes.md @@ -0,0 +1,16 @@ +--- +layout: index +title: "SW Toolbox Recipes" +navigation_weight: 3 +--- + +
      +
    • +

      Cache Expiration

      +

      + Demonstrates using the maxEntries and maxAgeSeconds options + to limit the number and age of entries stored in a cache dedicated to images fetched + from an API. +

      +
    • +
    diff --git a/docs/recipes/cache-expiration-options/app.js b/docs/recipes/cache-expiration-options/app.js new file mode 100644 index 0000000..28acc85 --- /dev/null +++ b/docs/recipes/cache-expiration-options/app.js @@ -0,0 +1,55 @@ +/* eslint-env browser */ +'use strict'; + +// Please register for your own YouTube API key! +// https://developers.google.com/youtube/v3/getting-started#before-you-start +const API_KEY = 'AIzaSyC4trKMxwT42TUFHmikCc4xxQTWWxq5S0g'; +const API_URL = 'https://www.googleapis.com/youtube/v3/search'; + +function serializeUrlParams(params) { + return Object.keys(params).map(key => { + return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); + }).join('&'); +} + +function youtubeSearch(searchTerm, maxResults) { + let params = { + part: 'snippet', + maxResults: maxResults, + order: 'date', + key: API_KEY, + q: searchTerm + }; + + let url = new URL(API_URL); + url.search = serializeUrlParams(params); + + return fetch(url).then(response => { + if (response.ok) { + return response.json(); + } + throw new Error(`${response.status}: ${response.statusText}`); + }).then(function(json) { + return json.items; + }); +} + +document.querySelector('#search').addEventListener('submit', event => { + event.preventDefault(); + + var results = document.querySelector('#results'); + while (results.firstChild) { + results.removeChild(results.firstChild); + } + + let searchTerm = document.querySelector('#searchTerm').value; + let maxResults = document.querySelector('#maxResults').value; + + youtubeSearch(searchTerm, maxResults).then(videos => { + videos.forEach(video => { + let img = document.createElement('img'); + img.src = video.snippet.thumbnails.medium.url; + results.appendChild(img); + }); + }).catch(error => console.warn('YouTube search failed due to', error)); +}); diff --git a/docs/recipes/cache-expiration-options/index.html b/docs/recipes/cache-expiration-options/index.html new file mode 100644 index 0000000..e30b37c --- /dev/null +++ b/docs/recipes/cache-expiration-options/index.html @@ -0,0 +1,74 @@ + + + Cache Expiration Demo + + + + + +

    Cache Expiration Demo

    + +

    Background

    +

    + The service worker in this example + demonstrates using the maxCacheEntries and maxCacheAgeSeconds + options. It uses a dedicated cache to hold YouTube video thumbnails. That + dedicated cache will purge entries once they're older than 30 seconds, and store at most 10 + entries. It uses the cacheFirst strategy, so any responses that are still in the + cache will be used directly, without going against the network. +

    + +

    + While this example uses both maxCacheEntries and maxCacheAgeSeconds, + it's possible to use each of those options independently. +

    + +

    + The cache used for YouTube thumbnail URLs is separate from the "default" cache, which is + used for all other requests, like YouTube API responses and this page's CSS, JavaScript, and + HTML. The page doesn't impose any upper limit on the size of that default cache, and we can + use a networkFirst strategy for it. +

    + +

    + Creating a dedicated cache with expiration options for dynamic, unbounded requests is a useful + pattern to follow. If we just used the default cache without imposing a cache expiration, + then that cache would grow in size as more and more searches were performed, needlessly + consuming disk space for old thumbnails that are likely no longer needed. +

    + +

    Live Demo

    +

    + Try increasing the number of thumbnails returned, or changing the search term, and then + observe the cache expirations logged in the developer console. +

    + + +
    + + + + + diff --git a/docs/recipes/cache-expiration-options/service-worker.js b/docs/recipes/cache-expiration-options/service-worker.js new file mode 100644 index 0000000..a69822c --- /dev/null +++ b/docs/recipes/cache-expiration-options/service-worker.js @@ -0,0 +1,38 @@ +(global => { + 'use strict'; + + // Load the sw-tookbox library. + importScripts('/build/sw-toolbox.js'); + + // Turn on debug logging, visible in the Developer Tools' console. + global.toolbox.options.debug = true; + + // Set up a handler for HTTP GET requests: + // - /\.ytimg\.com\// will match any requests whose URL contains 'ytimg.com'. + // A narrower RegExp could be used, but just checking for ytimg.com anywhere + // in the URL should be fine for this sample. + // - toolbox.cacheFirst let us to use the predefined cache strategy for those + // requests. + global.toolbox.router.get(/\.ytimg\.com\//, global.toolbox.cacheFirst, { + // Use a dedicated cache for the responses, separate from the default cache. + cache: { + name: 'youtube-thumbnails', + // Store up to 10 entries in that cache. + maxEntries: 10, + // Expire any entries that are older than 30 seconds. + maxAgeSeconds: 30 + } + }); + + // By default, all requests that don't match our custom handler will use the + // toolbox.networkFirst cache strategy, and their responses will be stored in + // the default cache. + global.toolbox.router.default = global.toolbox.networkFirst; + + // Boilerplate to ensure our service worker takes control of the page as soon + // as possible. + global.addEventListener('install', + event => event.waitUntil(global.skipWaiting())); + global.addEventListener('activate', + event => event.waitUntil(global.clients.claim())); +})(self); diff --git a/docs/recipes/cache-expiration-options/styles.css b/docs/recipes/cache-expiration-options/styles.css new file mode 100644 index 0000000..699f63a --- /dev/null +++ b/docs/recipes/cache-expiration-options/styles.css @@ -0,0 +1,10 @@ +#results { + display: flex; + flex-direction: row; + flex-wrap: wrap; +} + +#results > img { + margin: 4px; + width: 320px; +} diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..7ccf601 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,132 @@ +--- +layout: index +title: "Usage" +navigation_weight: 2 +--- + +## Basic Routes + +A _route_ is a URL pattern and request method associated with a handler. +It defines the behaviour for a section of the site. +_Routing_ is the process of matching an incoming request with the most +appropriate route. To define a route you call the appropriate method on +`toolbox.router`. + +For example, to send `GET` requests for the URL `'/myapp/index.html'` to the +built-in `toolbox.networkFirst` handler, you would write the following in your +service worker file: + +`toolbox.router.get('/myapp/index.html', toolbox.networkFirst);` + +If you don't need wildcards in your route, and your route applies to the same +domain as your main site, then you can use a string like `'/myapp/index.html'`. +However, if you need wildcards (e.g. match _any_ URL that begins with +`/myapp/`), or if you need to match URLs that belong to different domains (e.g. +match `https://othersite.com/api/`), `sw-toolbox` has two options for +configuring your routes. + +## Express-style Routes + +For developers familiar with [Express routing](http://expressjs.com/en/guide/routing.html), +`sw-toolbox` offers support for similar named wildcards, via the +[`path-to-regexp`](https://github.com/pillarjs/path-to-regexp) library. + +If you use a `String` to define your route, it's assumed you're using +Express-style routes. + +By default, a route will only match URLs on the same origin as the service +worker. If you'd like your Express-style routes to match URLs on different +origins, you need to pass in a value for the `origin` option. The value could be +either a `String` (which is checked for an exact match) or a `RegExp` object. +In both cases, it's matched against the full origin of the URL +(e.g. `'https://example.com'`). + +Some examples of using Express-style routing include: + +```javascript +// URL patterns are the same syntax as Express routes +// (http://expressjs.com/guide/routing.html) +toolbox.router.get(':foo/index.html', function(request, values) { + return new Response('Handled a request for ' + request.url + + ', where foo is "' + values.foo + '"'); +}); + +// For requests to other origins, specify the origin as an option +toolbox.router.post('/(.*)', apiHandler, {origin: 'https://api.example.com'}); +``` + +## Regular Expression Routes + +Developers who are more comfortable using [regular expressions](https://regex101.com/) +can use an alternative syntax to define routes, passing in a +[`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) +object as the first parameter. This `RegExp` will be matched against the full +request URL when determining whether the route applies, including the origin and +path. This can lead to simpler cross-origin routing vs. Express-style routes, +since both the origin and the path are matched simultaneously, without having +to specify a separate `origin` option. + +Note that while Express-style routes allow you to name path fragment +parameters that will be passed to your handler (see `values.foo` in the previous +example), that functionality is not supported while using regular expression +routes. + +Some examples of using Regular Expression routing include: + +```javascript +// Match URLs that end in index.html +toolbox.router.get(/index.html$/, function(request) { + return new Response('Handled a request for ' + request.url); +}); + +// Match URLs that begin with https://api.example.com +toolbox.router.post(/^https:\/\/api.example.com\//, apiHandler); +``` + +## The Default Route + +`sw-toolbox` supports defining an optional "default" route via +`toolbox.router.default` that is used whenever there is no alternative route for +a given URL. If `toolbox.router.default` is not set, then `sw-toolbox` will +just ignore requests for URLs that don't match any alternative routes, and the +requests will potentially be handled by the browser as if there were no +service worker involvement. + +```javascript +// Provide a default handler for GET requests +toolbox.router.default = myDefaultRequestHandler; +``` + +## Precaching + +You can provide a list of resources which will be cached at service worker install time + +```javascript +toolbox.precache(['/index.html', '/site.css', '/images/logo.png']); +``` + +## Defining Request Handlers +A request handler takes three arguments. + +```javascript +var myHandler = function(request, values, options) { + // ... +} +``` + +- `request` - The [Request](https://fetch.spec.whatwg.org/#request) object that +triggered the `fetch` event +- `values` - When using Express-style routing paths, this will be an object +whose keys are the placeholder names in the URL pattern, with the values being +the corresponding part of the request URL. For example, with a URL pattern of +`'/images/:size/:name.jpg'` and an actual URL of `'/images/large/unicorns.jpg'`, +`values` would be `{size: 'large', name: 'unicorns'}`. +When using a RegExp for the path, `values` will not be set. +- `options` - the [options](#options) passed to one of the [router methods](#methods). + +The return value should be a [Response](https://fetch.spec.whatwg.org/#response), +or a [Promise](http://www.html5rocks.com/en/tutorials/es6/promises/) that +resolves with a Response. If another value is returned, or if the returned +Promise is rejected, the Request will fail which will appear to be a +[NetworkError](https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-NetworkError) +to the page that made the request. diff --git a/lib/helpers.js b/lib/helpers.js new file mode 100644 index 0000000..7b91296 --- /dev/null +++ b/lib/helpers.js @@ -0,0 +1,183 @@ +/* + Copyright 2014 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 + + 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 strict'; + +var globalOptions = require('./options'); +var idbCacheExpiration = require('./idb-cache-expiration'); + +function debug(message, options) { + options = options || {}; + var flag = options.debug || globalOptions.debug; + if (flag) { + console.log('[sw-toolbox] ' + message); + } +} + +function openCache(options) { + var cacheName; + if (options && options.cache) { + cacheName = options.cache.name; + } + cacheName = cacheName || globalOptions.cache.name; + + return caches.open(cacheName); +} + +function fetchAndCache(request, options) { + options = options || {}; + var successResponses = options.successResponses || + globalOptions.successResponses; + + return fetch(request.clone()).then(function(response) { + // Only cache GET requests with successful responses. + // Since this is not part of the promise chain, it will be done + // asynchronously and will not block the response from being returned to the + // page. + if (request.method === 'GET' && successResponses.test(response.status)) { + openCache(options).then(function(cache) { + cache.put(request, response).then(function() { + // If any of the options are provided in options.cache then use them. + // Do not fallback to the global options for any that are missing + // unless they are all missing. + var cacheOptions = options.cache || globalOptions.cache; + + // Only run the cache expiration logic if at least one of the maximums + // is set, and if we have a name for the cache that the options are + // being applied to. + if ((cacheOptions.maxEntries || cacheOptions.maxAgeSeconds) && + cacheOptions.name) { + queueCacheExpiration(request, cache, cacheOptions); + } + }); + }); + } + + return response.clone(); + }); +} + +var cleanupQueue; +function queueCacheExpiration(request, cache, cacheOptions) { + var cleanup = cleanupCache.bind(null, request, cache, cacheOptions); + + if (cleanupQueue) { + cleanupQueue = cleanupQueue.then(cleanup); + } else { + cleanupQueue = cleanup(); + } +} + +function cleanupCache(request, cache, cacheOptions) { + var requestUrl = request.url; + var maxAgeSeconds = cacheOptions.maxAgeSeconds; + var maxEntries = cacheOptions.maxEntries; + var cacheName = cacheOptions.name; + + var now = Date.now(); + debug('Updating LRU order for ' + requestUrl + '. Max entries is ' + + maxEntries + ', max age is ' + maxAgeSeconds); + + return idbCacheExpiration.getDb(cacheName).then(function(db) { + return idbCacheExpiration.setTimestampForUrl(db, requestUrl, now); + }).then(function(db) { + return idbCacheExpiration.expireEntries(db, maxEntries, maxAgeSeconds, now); + }).then(function(urlsToDelete) { + debug('Successfully updated IDB.'); + + var deletionPromises = urlsToDelete.map(function(urlToDelete) { + return cache.delete(urlToDelete); + }); + + return Promise.all(deletionPromises).then(function() { + debug('Done with cache cleanup.'); + }); + }).catch(function(error) { + debug(error); + }); +} + +function renameCache(source, destination, options) { + debug('Renaming cache: [' + source + '] to [' + destination + ']', options); + return caches.delete(destination).then(function() { + return Promise.all([ + caches.open(source), + caches.open(destination) + ]).then(function(results) { + var sourceCache = results[0]; + var destCache = results[1]; + + return sourceCache.keys().then(function(requests) { + return Promise.all(requests.map(function(request) { + return sourceCache.match(request).then(function(response) { + return destCache.put(request, response); + }); + })); + }).then(function() { + return caches.delete(source); + }); + }); + }); +} + +function cache(url, options) { + return openCache(options).then(function(cache) { + return cache.add(url); + }); +} + +function uncache(url, options) { + return openCache(options).then(function(cache) { + return cache.delete(url); + }); +} + +function precache(items) { + if (!(items instanceof Promise)) { + validatePrecacheInput(items); + } + + globalOptions.preCacheItems = globalOptions.preCacheItems.concat(items); +} + +function validatePrecacheInput(items) { + var isValid = Array.isArray(items); + if (isValid) { + items.forEach(function(item) { + if (!(typeof item === 'string' || (item instanceof Request))) { + isValid = false; + } + }); + } + + if (!isValid) { + throw new TypeError('The precache method expects either an array of ' + + 'strings and/or Requests or a Promise that resolves to an array of ' + + 'strings and/or Requests.'); + } + + return items; +} + +module.exports = { + debug: debug, + fetchAndCache: fetchAndCache, + openCache: openCache, + renameCache: renameCache, + cache: cache, + uncache: uncache, + precache: precache, + validatePrecacheInput: validatePrecacheInput +}; diff --git a/lib/idb-cache-expiration.js b/lib/idb-cache-expiration.js new file mode 100644 index 0000000..1dae626 --- /dev/null +++ b/lib/idb-cache-expiration.js @@ -0,0 +1,158 @@ +/* + Copyright 2015 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 + + 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 strict'; + +var DB_PREFIX = 'sw-toolbox-'; +var DB_VERSION = 1; +var STORE_NAME = 'store'; +var URL_PROPERTY = 'url'; +var TIMESTAMP_PROPERTY = 'timestamp'; +var cacheNameToDbPromise = {}; + +function openDb(cacheName) { + return new Promise(function(resolve, reject) { + var request = indexedDB.open(DB_PREFIX + cacheName, DB_VERSION); + + request.onupgradeneeded = function() { + var objectStore = request.result.createObjectStore(STORE_NAME, + {keyPath: URL_PROPERTY}); + objectStore.createIndex(TIMESTAMP_PROPERTY, TIMESTAMP_PROPERTY, + {unique: false}); + }; + + request.onsuccess = function() { + resolve(request.result); + }; + + request.onerror = function() { + reject(request.error); + }; + }); +} + +function getDb(cacheName) { + if (!(cacheName in cacheNameToDbPromise)) { + cacheNameToDbPromise[cacheName] = openDb(cacheName); + } + + return cacheNameToDbPromise[cacheName]; +} + +function setTimestampForUrl(db, url, now) { + return new Promise(function(resolve, reject) { + var transaction = db.transaction(STORE_NAME, 'readwrite'); + var objectStore = transaction.objectStore(STORE_NAME); + objectStore.put({url: url, timestamp: now}); + + transaction.oncomplete = function() { + resolve(db); + }; + + transaction.onabort = function() { + reject(transaction.error); + }; + }); +} + +function expireOldEntries(db, maxAgeSeconds, now) { + // Bail out early by resolving with an empty array if we're not using + // maxAgeSeconds. + if (!maxAgeSeconds) { + return Promise.resolve([]); + } + + return new Promise(function(resolve, reject) { + var maxAgeMillis = maxAgeSeconds * 1000; + var urls = []; + + var transaction = db.transaction(STORE_NAME, 'readwrite'); + var objectStore = transaction.objectStore(STORE_NAME); + var index = objectStore.index(TIMESTAMP_PROPERTY); + + index.openCursor().onsuccess = function(cursorEvent) { + var cursor = cursorEvent.target.result; + if (cursor) { + if (now - maxAgeMillis > cursor.value[TIMESTAMP_PROPERTY]) { + var url = cursor.value[URL_PROPERTY]; + urls.push(url); + objectStore.delete(url); + cursor.continue(); + } + } + }; + + transaction.oncomplete = function() { + resolve(urls); + }; + + transaction.onabort = reject; + }); +} + +function expireExtraEntries(db, maxEntries) { + // Bail out early by resolving with an empty array if we're not using + // maxEntries. + if (!maxEntries) { + return Promise.resolve([]); + } + + return new Promise(function(resolve, reject) { + var urls = []; + + var transaction = db.transaction(STORE_NAME, 'readwrite'); + var objectStore = transaction.objectStore(STORE_NAME); + var index = objectStore.index(TIMESTAMP_PROPERTY); + + var countRequest = index.count(); + index.count().onsuccess = function() { + var initialCount = countRequest.result; + + if (initialCount > maxEntries) { + index.openCursor().onsuccess = function(cursorEvent) { + var cursor = cursorEvent.target.result; + if (cursor) { + var url = cursor.value[URL_PROPERTY]; + urls.push(url); + objectStore.delete(url); + if (initialCount - urls.length > maxEntries) { + cursor.continue(); + } + } + }; + } + }; + + transaction.oncomplete = function() { + resolve(urls); + }; + + transaction.onabort = reject; + }); +} + +function expireEntries(db, maxEntries, maxAgeSeconds, now) { + return expireOldEntries(db, maxAgeSeconds, now).then(function(oldUrls) { + return expireExtraEntries(db, maxEntries).then(function(extraUrls) { + return oldUrls.concat(extraUrls); + }); + }); +} + +module.exports = { + getDb: getDb, + setTimestampForUrl: setTimestampForUrl, + expireEntries: expireEntries +}; diff --git a/lib/listeners.js b/lib/listeners.js new file mode 100644 index 0000000..2f60c5f --- /dev/null +++ b/lib/listeners.js @@ -0,0 +1,75 @@ +/* + Copyright 2014 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 + + 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 strict'; + +// For cache.addAll. +require('serviceworker-cache-polyfill'); + +var helpers = require('./helpers'); +var router = require('./router'); +var options = require('./options'); + +// Event listeners + +function fetchListener(event) { + var handler = router.match(event.request); + + if (handler) { + event.respondWith(handler(event.request)); + } else if (router.default && + event.request.method === 'GET' && + // Ensure that chrome-extension:// requests don't trigger the default route. + event.request.url.indexOf('http') === 0) { + event.respondWith(router.default(event.request)); + } +} + +function activateListener(event) { + helpers.debug('activate event fired'); + var inactiveCache = options.cache.name + '$$$inactive$$$'; + event.waitUntil(helpers.renameCache(inactiveCache, options.cache.name)); +} + +function flatten(items) { + return items.reduce(function(a, b) { + return a.concat(b); + }, []); +} + +function installListener(event) { + var inactiveCache = options.cache.name + '$$$inactive$$$'; + helpers.debug('install event fired'); + helpers.debug('creating cache [' + inactiveCache + ']'); + event.waitUntil( + helpers.openCache({cache: {name: inactiveCache}}) + .then(function(cache) { + return Promise.all(options.preCacheItems) + .then(flatten) + .then(helpers.validatePrecacheInput) + .then(function(preCacheItems) { + helpers.debug('preCache list: ' + + (preCacheItems.join(', ') || '(none)')); + return cache.addAll(preCacheItems); + }); + }) + ); +} + +module.exports = { + fetchListener: fetchListener, + activateListener: activateListener, + installListener: installListener +}; diff --git a/lib/options.js b/lib/options.js new file mode 100644 index 0000000..283584f --- /dev/null +++ b/lib/options.js @@ -0,0 +1,40 @@ +/* + Copyright 2015 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 + + 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 strict'; + +// TODO: This is necessary to handle different implementations in the wild +// The spec defines self.registration, but it was not implemented in Chrome 40. +var scope; +if (self.registration) { + scope = self.registration.scope; +} else { + scope = self.scope || new URL('./', self.location).href; +} + +module.exports = { + cache: { + name: '$$$toolbox-cache$$$' + scope + '$$$', + maxAgeSeconds: null, + maxEntries: null + }, + debug: false, + networkTimeoutSeconds: null, + preCacheItems: [], + // A regular expression to apply to HTTP response codes. Codes that match + // will be considered successes, while others will not, and will not be + // cached. + successResponses: /^0|([123]\d\d)|(40[14567])|410$/ +}; diff --git a/lib/route.js b/lib/route.js new file mode 100644 index 0000000..57f1b3c --- /dev/null +++ b/lib/route.js @@ -0,0 +1,60 @@ +/* + Copyright 2014 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 + + 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 strict'; + +// TODO: Use self.registration.scope instead of self.location +var url = new URL('./', self.location); +var basePath = url.pathname; +var pathRegexp = require('path-to-regexp'); + +var Route = function(method, path, handler, options) { + if (path instanceof RegExp) { + this.fullUrlRegExp = path; + } else { + // The URL() constructor can't parse express-style routes as they are not + // valid urls. This means we have to manually manipulate relative urls into + // absolute ones. This check is extremely naive but implementing a tweaked + // version of the full algorithm seems like overkill + // (https://url.spec.whatwg.org/#concept-basic-url-parser) + if (path.indexOf('/') !== 0) { + path = basePath + path; + } + + this.keys = []; + this.regexp = pathRegexp(path, this.keys); + } + + this.method = method; + this.options = options; + this.handler = handler; +}; + +Route.prototype.makeHandler = function(url) { + var values; + if (this.regexp) { + var match = this.regexp.exec(url); + values = {}; + this.keys.forEach(function(key, index) { + values[key.name] = match[index + 1]; + }); + } + + return function(request) { + return this.handler(request, values, this.options); + }.bind(this); +}; + +module.exports = Route; diff --git a/lib/router.js b/lib/router.js new file mode 100644 index 0000000..788118e --- /dev/null +++ b/lib/router.js @@ -0,0 +1,133 @@ +/* + Copyright 2014 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 + + 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 strict'; + +var Route = require('./route'); +var helpers = require('./helpers'); + +function regexEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); +} + +var keyMatch = function(map, string) { + // This would be better written as a for..of loop, but that would break the + // minifyify process in the build. + var entriesIterator = map.entries(); + var item = entriesIterator.next(); + var matches = []; + while (!item.done) { + var pattern = new RegExp(item.value[0]); + if (pattern.test(string)) { + matches.push(item.value[1]); + } + item = entriesIterator.next(); + } + return matches; +}; + +var Router = function() { + this.routes = new Map(); + // Create the dummy origin for RegExp-based routes + this.routes.set(RegExp, new Map()); + this.default = null; +}; + +['get', 'post', 'put', 'delete', 'head', 'any'].forEach(function(method) { + Router.prototype[method] = function(path, handler, options) { + return this.add(method, path, handler, options); + }; +}); + +Router.prototype.add = function(method, path, handler, options) { + options = options || {}; + var origin; + + if (path instanceof RegExp) { + // We need a unique key to use in the Map to distinguish RegExp paths + // from Express-style paths + origins. Since we can use any object as the + // key in a Map, let's use the RegExp constructor! + origin = RegExp; + } else { + origin = options.origin || self.location.origin; + if (origin instanceof RegExp) { + origin = origin.source; + } else { + origin = regexEscape(origin); + } + } + + method = method.toLowerCase(); + + var route = new Route(method, path, handler, options); + + if (!this.routes.has(origin)) { + this.routes.set(origin, new Map()); + } + + var methodMap = this.routes.get(origin); + if (!methodMap.has(method)) { + methodMap.set(method, new Map()); + } + + var routeMap = methodMap.get(method); + var regExp = route.regexp || route.fullUrlRegExp; + + if (routeMap.has(regExp.source)) { + helpers.debug('"' + path + '" resolves to same regex as existing route.'); + } + + routeMap.set(regExp.source, route); +}; + +Router.prototype.matchMethod = function(method, url) { + var urlObject = new URL(url); + var origin = urlObject.origin; + var path = urlObject.pathname; + + // We want to first check to see if there's a match against any + // "Express-style" routes (string for the path, RegExp for the origin). + // Checking for Express-style matches first maintains the legacy behavior. + // If there's no match, we next check for a match against any RegExp routes, + // where the RegExp in question matches the full URL (both origin and path). + return this._match(method, keyMatch(this.routes, origin), path) || + this._match(method, [this.routes.get(RegExp)], url); +}; + +Router.prototype._match = function(method, methodMaps, pathOrUrl) { + if (methodMaps.length === 0) { + return null; + } + + for (var i = 0; i < methodMaps.length; i++) { + var methodMap = methodMaps[i]; + var routeMap = methodMap && methodMap.get(method.toLowerCase()); + if (routeMap) { + var routes = keyMatch(routeMap, pathOrUrl); + if (routes.length > 0) { + return routes[0].makeHandler(pathOrUrl); + } + } + } + + return null; +}; + +Router.prototype.match = function(request) { + return this.matchMethod(request.method, request.url) || + this.matchMethod('any', request.url); +}; + +module.exports = new Router(); diff --git a/lib/strategies/cacheFirst.js b/lib/strategies/cacheFirst.js new file mode 100644 index 0000000..3bc5f5a --- /dev/null +++ b/lib/strategies/cacheFirst.js @@ -0,0 +1,32 @@ +/* + Copyright 2014 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 + + 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 strict'; +var helpers = require('../helpers'); + +function cacheFirst(request, values, options) { + helpers.debug('Strategy: cache first [' + request.url + ']', options); + return helpers.openCache(options).then(function(cache) { + return cache.match(request).then(function(response) { + if (response) { + return response; + } + + return helpers.fetchAndCache(request, options); + }); + }); +} + +module.exports = cacheFirst; diff --git a/lib/strategies/cacheOnly.js b/lib/strategies/cacheOnly.js new file mode 100644 index 0000000..a85a38e --- /dev/null +++ b/lib/strategies/cacheOnly.js @@ -0,0 +1,26 @@ +/* + Copyright 2014 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 + + 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 strict'; +var helpers = require('../helpers'); + +function cacheOnly(request, values, options) { + helpers.debug('Strategy: cache only [' + request.url + ']', options); + return helpers.openCache(options).then(function(cache) { + return cache.match(request); + }); +} + +module.exports = cacheOnly; diff --git a/lib/strategies/fastest.js b/lib/strategies/fastest.js new file mode 100644 index 0000000..4454f8c --- /dev/null +++ b/lib/strategies/fastest.js @@ -0,0 +1,53 @@ +/* + Copyright 2014 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 + + 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 strict'; +var helpers = require('../helpers'); +var cacheOnly = require('./cacheOnly'); + +function fastest(request, values, options) { + helpers.debug('Strategy: fastest [' + request.url + ']', options); + + return new Promise(function(resolve, reject) { + var rejected = false; + var reasons = []; + + var maybeReject = function(reason) { + reasons.push(reason.toString()); + if (rejected) { + reject(new Error('Both cache and network failed: "' + + reasons.join('", "') + '"')); + } else { + rejected = true; + } + }; + + var maybeResolve = function(result) { + if (result instanceof Response) { + resolve(result); + } else { + maybeReject('No result returned'); + } + }; + + helpers.fetchAndCache(request.clone(), options) + .then(maybeResolve, maybeReject); + + cacheOnly(request, values, options) + .then(maybeResolve, maybeReject); + }); +} + +module.exports = fastest; diff --git a/lib/strategies/index.js b/lib/strategies/index.js new file mode 100644 index 0000000..f98ccc5 --- /dev/null +++ b/lib/strategies/index.js @@ -0,0 +1,22 @@ +/* + Copyright 2014 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 + + 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. +*/ +module.exports = { + networkOnly: require('./networkOnly'), + networkFirst: require('./networkFirst'), + cacheOnly: require('./cacheOnly'), + cacheFirst: require('./cacheFirst'), + fastest: require('./fastest') +}; diff --git a/lib/strategies/networkFirst.js b/lib/strategies/networkFirst.js new file mode 100644 index 0000000..e35ee42 --- /dev/null +++ b/lib/strategies/networkFirst.js @@ -0,0 +1,94 @@ +/* + Copyright 2015 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 + + 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 strict'; +var globalOptions = require('../options'); +var helpers = require('../helpers'); + +function networkFirst(request, values, options) { + options = options || {}; + var successResponses = options.successResponses || + globalOptions.successResponses; + // This will bypass options.networkTimeout if it's set to a false-y value like + // 0, but that's the sane thing to do anyway. + var networkTimeoutSeconds = options.networkTimeoutSeconds || + globalOptions.networkTimeoutSeconds; + helpers.debug('Strategy: network first [' + request.url + ']', options); + + return helpers.openCache(options).then(function(cache) { + var timeoutId; + var promises = []; + var originalResponse; + + if (networkTimeoutSeconds) { + var cacheWhenTimedOutPromise = new Promise(function(resolve) { + timeoutId = setTimeout(function() { + cache.match(request).then(function(response) { + if (response) { + // Only resolve this promise if there's a valid response in the + // cache. This ensures that we won't time out a network request + // unless there's a cached entry to fallback on, which is arguably + // the preferable behavior. + resolve(response); + } + }); + }, networkTimeoutSeconds * 1000); + }); + promises.push(cacheWhenTimedOutPromise); + } + + var networkPromise = helpers.fetchAndCache(request, options) + .then(function(response) { + // We've got a response, so clear the network timeout if there is one. + if (timeoutId) { + clearTimeout(timeoutId); + } + + if (successResponses.test(response.status)) { + return response; + } + + helpers.debug('Response was an HTTP error: ' + response.statusText, + options); + originalResponse = response; + throw new Error('Bad response'); + }).catch(function(error) { + helpers.debug('Network or response error, fallback to cache [' + + request.url + ']', options); + return cache.match(request).then(function(response) { + // If there's a match in the cache, resolve with that. + if (response) { + return response; + } + + // If we have a Response object from the previous fetch, then resolve + // with that, even though it corresponds to an error status code. + if (originalResponse) { + return originalResponse; + } + + // If we don't have a Response object from the previous fetch, likely + // due to a network failure, then reject with the failure error. + throw error; + }); + }); + + promises.push(networkPromise); + + return Promise.race(promises); + }); +} + +module.exports = networkFirst; diff --git a/lib/strategies/networkOnly.js b/lib/strategies/networkOnly.js new file mode 100644 index 0000000..d8bb0d5 --- /dev/null +++ b/lib/strategies/networkOnly.js @@ -0,0 +1,24 @@ +/* + Copyright 2014 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 + + 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 strict'; +var helpers = require('../helpers'); + +function networkOnly(request, values, options) { + helpers.debug('Strategy: network only [' + request.url + ']', options); + return fetch(request); +} + +module.exports = networkOnly; diff --git a/lib/sw-toolbox.js b/lib/sw-toolbox.js new file mode 100644 index 0000000..69c1116 --- /dev/null +++ b/lib/sw-toolbox.js @@ -0,0 +1,46 @@ +/* + Copyright 2014 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 + + 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 strict'; + +// This is the entrypoint for the sw-toolbox bundle. All code with +// side effects (e.g. adding event listeners) should be in this file. + +var options = require('./options'); +var router = require('./router'); +var helpers = require('./helpers'); +var strategies = require('./strategies'); +var listeners = require('./listeners'); + +helpers.debug('Service Worker Toolbox is loading'); + +// Set up listeners. + +self.addEventListener('install', listeners.installListener); +self.addEventListener('activate', listeners.activateListener); +self.addEventListener('fetch', listeners.fetchListener); + +module.exports = { + networkOnly: strategies.networkOnly, + networkFirst: strategies.networkFirst, + cacheOnly: strategies.cacheOnly, + cacheFirst: strategies.cacheFirst, + fastest: strategies.fastest, + router: router, + options: options, + cache: helpers.cache, + uncache: helpers.uncache, + precache: helpers.precache +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..7b3cd2f --- /dev/null +++ b/package.json @@ -0,0 +1,55 @@ +{ + "name": "sw-toolbox", + "version": "3.4.0", + "description": "Service Worker Toolbox provides some simple helpers for use in creating your own service workers.", + "license": "Apache-2.0", + "scripts": { + "publish-release": "publish-release.sh", + "publish-docs": "publish-docs.sh", + "build": "gulp default", + "build-docs": "echo No Reference Docs to Build.", + "test": "gulp lint default && node ./test/helpers/download-browsers.js && mocha", + "bundle": "./project/create-release-bundle.sh" + }, + "main": "lib/sw-toolbox.js", + "repository": "https://github.com/GoogleChrome/sw-toolbox", + "dependencies": { + "serviceworker-cache-polyfill": "^4.0.0", + "path-to-regexp": "^1.0.1" + }, + "devDependencies": { + "browserify": "^13.1.0", + "chai": "^3.4.1", + "chromedriver": "^2.24.1", + "cookie-parser": "^1.4.1", + "eslint": "^1.10.3", + "eslint-config-google": "^0.3.0", + "express": "^4.13.3", + "geckodriver": "^1.1.2", + "gulp": "^3.9.0", + "gulp-eslint": "^1.1.1", + "gulp-gh-pages": "^0.5.4", + "gulp-header": "^1.8.8", + "gulp-sourcemaps": "^1.6.0", + "gulp-uglify": "^2.0.0", + "jsdoc": "^3.4.0", + "jshint-stylish": "^2.1.0", + "mocha": "^2.3.4", + "npm-publish-scripts": "^2.0.7", + "operadriver": "^0.2.2", + "qunitjs": "^1.20.0", + "selenium-assistant": "^1.0.0", + "selenium-webdriver": "^3.0.0-beta-2", + "sw-testing-helpers": "0.1.4", + "temp": "^0.8.3", + "vinyl-buffer": "^1.0.0", + "vinyl-source-stream": "^1.1.0", + "which": "^1.2.4" + }, + "files": [ + "lib/", + "companion.js", + "sw-toolbox.js", + "sw-toolbox.js.map" + ] +} diff --git a/sw-toolbox.js b/sw-toolbox.js new file mode 100644 index 0000000..413fc72 --- /dev/null +++ b/sw-toolbox.js @@ -0,0 +1,16 @@ +/* + 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 + + 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. +*/!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.toolbox=e()}}(function(){return function e(t,n,r){function o(c,s){if(!n[c]){if(!t[c]){var a="function"==typeof require&&require;if(!s&&a)return a(c,!0);if(i)return i(c,!0);var u=new Error("Cannot find module '"+c+"'");throw u.code="MODULE_NOT_FOUND",u}var f=n[c]={exports:{}};t[c][0].call(f.exports,function(e){var n=t[c][1][e];return o(n?n:e)},f,f.exports,e,t,n,r)}return n[c].exports}for(var i="function"==typeof require&&require,c=0;ct.value[l]){var r=t.value[p];c.push(r),a.delete(r),t.continue()}},s.oncomplete=function(){r(c)},s.onabort=o}):Promise.resolve([])}function s(e,t){return t?new Promise(function(n,r){var o=[],i=e.transaction(h,"readwrite"),c=i.objectStore(h),s=c.index(l),a=s.count();s.count().onsuccess=function(){var e=a.result;e>t&&(s.openCursor().onsuccess=function(n){var r=n.target.result;if(r){var i=r.value[p];o.push(i),c.delete(i),e-o.length>t&&r.continue()}})},i.oncomplete=function(){n(o)},i.onabort=r}):Promise.resolve([])}function a(e,t,n,r){return c(e,n,r).then(function(n){return s(e,t).then(function(e){return n.concat(e)})})}var u="sw-toolbox-",f=1,h="store",p="url",l="timestamp",d={};t.exports={getDb:o,setTimestampForUrl:i,expireEntries:a}},{}],3:[function(e,t,n){"use strict";function r(e){var t=a.match(e.request);t?e.respondWith(t(e.request)):a.default&&"GET"===e.request.method&&0===e.request.url.indexOf("http")&&e.respondWith(a.default(e.request))}function o(e){s.debug("activate event fired");var t=u.cache.name+"$$$inactive$$$";e.waitUntil(s.renameCache(t,u.cache.name))}function i(e){return e.reduce(function(e,t){return e.concat(t)},[])}function c(e){var t=u.cache.name+"$$$inactive$$$";s.debug("install event fired"),s.debug("creating cache ["+t+"]"),e.waitUntil(s.openCache({cache:{name:t}}).then(function(e){return Promise.all(u.preCacheItems).then(i).then(s.validatePrecacheInput).then(function(t){return s.debug("preCache list: "+(t.join(", ")||"(none)")),e.addAll(t)})}))}e("serviceworker-cache-polyfill");var s=e("./helpers"),a=e("./router"),u=e("./options");t.exports={fetchListener:r,activateListener:o,installListener:c}},{"./helpers":1,"./options":4,"./router":6,"serviceworker-cache-polyfill":16}],4:[function(e,t,n){"use strict";var r;r=self.registration?self.registration.scope:self.scope||new URL("./",self.location).href,t.exports={cache:{name:"$$$toolbox-cache$$$"+r+"$$$",maxAgeSeconds:null,maxEntries:null},debug:!1,networkTimeoutSeconds:null,preCacheItems:[],successResponses:/^0|([123]\d\d)|(40[14567])|410$/}},{}],5:[function(e,t,n){"use strict";var r=new URL("./",self.location),o=r.pathname,i=e("path-to-regexp"),c=function(e,t,n,r){t instanceof RegExp?this.fullUrlRegExp=t:(0!==t.indexOf("/")&&(t=o+t),this.keys=[],this.regexp=i(t,this.keys)),this.method=e,this.options=r,this.handler=n};c.prototype.makeHandler=function(e){var t;if(this.regexp){var n=this.regexp.exec(e);t={},this.keys.forEach(function(e,r){t[e.name]=n[r+1]})}return function(e){return this.handler(e,t,this.options)}.bind(this)},t.exports=c},{"path-to-regexp":15}],6:[function(e,t,n){"use strict";function r(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var o=e("./route"),i=e("./helpers"),c=function(e,t){for(var n=e.entries(),r=n.next(),o=[];!r.done;){var i=new RegExp(r.value[0]);i.test(t)&&o.push(r.value[1]),r=n.next()}return o},s=function(){this.routes=new Map,this.routes.set(RegExp,new Map),this.default=null};["get","post","put","delete","head","any"].forEach(function(e){s.prototype[e]=function(t,n,r){return this.add(e,t,n,r)}}),s.prototype.add=function(e,t,n,c){c=c||{};var s;t instanceof RegExp?s=RegExp:(s=c.origin||self.location.origin,s=s instanceof RegExp?s.source:r(s)),e=e.toLowerCase();var a=new o(e,t,n,c);this.routes.has(s)||this.routes.set(s,new Map);var u=this.routes.get(s);u.has(e)||u.set(e,new Map);var f=u.get(e),h=a.regexp||a.fullUrlRegExp;f.has(h.source)&&i.debug('"'+t+'" resolves to same regex as existing route.'),f.set(h.source,a)},s.prototype.matchMethod=function(e,t){var n=new URL(t),r=n.origin,o=n.pathname;return this._match(e,c(this.routes,r),o)||this._match(e,[this.routes.get(RegExp)],t)},s.prototype._match=function(e,t,n){if(0===t.length)return null;for(var r=0;r0)return s[0].makeHandler(n)}}return null},s.prototype.match=function(e){return this.matchMethod(e.method,e.url)||this.matchMethod("any",e.url)},t.exports=new s},{"./helpers":1,"./route":5}],7:[function(e,t,n){"use strict";function r(e,t,n){return o.debug("Strategy: cache first ["+e.url+"]",n),o.openCache(n).then(function(t){return t.match(e).then(function(t){return t?t:o.fetchAndCache(e,n)})})}var o=e("../helpers");t.exports=r},{"../helpers":1}],8:[function(e,t,n){"use strict";function r(e,t,n){return o.debug("Strategy: cache only ["+e.url+"]",n),o.openCache(n).then(function(t){return t.match(e)})}var o=e("../helpers");t.exports=r},{"../helpers":1}],9:[function(e,t,n){"use strict";function r(e,t,n){return o.debug("Strategy: fastest ["+e.url+"]",n),new Promise(function(r,c){var s=!1,a=[],u=function(e){a.push(e.toString()),s?c(new Error('Both cache and network failed: "'+a.join('", "')+'"')):s=!0},f=function(e){e instanceof Response?r(e):u("No result returned")};o.fetchAndCache(e.clone(),n).then(f,u),i(e,t,n).then(f,u)})}var o=e("../helpers"),i=e("./cacheOnly");t.exports=r},{"../helpers":1,"./cacheOnly":8}],10:[function(e,t,n){t.exports={networkOnly:e("./networkOnly"),networkFirst:e("./networkFirst"),cacheOnly:e("./cacheOnly"),cacheFirst:e("./cacheFirst"),fastest:e("./fastest")}},{"./cacheFirst":7,"./cacheOnly":8,"./fastest":9,"./networkFirst":11,"./networkOnly":12}],11:[function(e,t,n){"use strict";function r(e,t,n){n=n||{};var r=n.successResponses||o.successResponses,c=n.networkTimeoutSeconds||o.networkTimeoutSeconds;return i.debug("Strategy: network first ["+e.url+"]",n),i.openCache(n).then(function(t){var o,s,a=[];if(c){var u=new Promise(function(n){o=setTimeout(function(){t.match(e).then(function(e){e&&n(e)})},1e3*c)});a.push(u)}var f=i.fetchAndCache(e,n).then(function(e){if(o&&clearTimeout(o),r.test(e.status))return e;throw i.debug("Response was an HTTP error: "+e.statusText,n),s=e,new Error("Bad response")}).catch(function(r){return i.debug("Network or response error, fallback to cache ["+e.url+"]",n),t.match(e).then(function(e){if(e)return e;if(s)return s;throw r})});return a.push(f),Promise.race(a)})}var o=e("../options"),i=e("../helpers");t.exports=r},{"../helpers":1,"../options":4}],12:[function(e,t,n){"use strict";function r(e,t,n){return o.debug("Strategy: network only ["+e.url+"]",n),fetch(e)}var o=e("../helpers");t.exports=r},{"../helpers":1}],13:[function(e,t,n){"use strict";var r=e("./options"),o=e("./router"),i=e("./helpers"),c=e("./strategies"),s=e("./listeners");i.debug("Service Worker Toolbox is loading"),self.addEventListener("install",s.installListener),self.addEventListener("activate",s.activateListener),self.addEventListener("fetch",s.fetchListener),t.exports={networkOnly:c.networkOnly,networkFirst:c.networkFirst,cacheOnly:c.cacheOnly,cacheFirst:c.cacheFirst,fastest:c.fastest,router:o,options:r,cache:i.cache,uncache:i.uncache,precache:i.precache}},{"./helpers":1,"./listeners":3,"./options":4,"./router":6,"./strategies":10}],14:[function(e,t,n){t.exports=Array.isArray||function(e){return"[object Array]"==Object.prototype.toString.call(e)}},{}],15:[function(e,t,n){function r(e){for(var t,n=[],r=0,o=0,i="";null!=(t=x.exec(e));){var c=t[0],s=t[1],a=t.index;if(i+=e.slice(o,a),o=a+c.length,s)i+=s[1];else{var f=e[o],h=t[2],p=t[3],l=t[4],d=t[5],g=t[6],m=t[7];i&&(n.push(i),i="");var v=null!=h&&null!=f&&f!==h,w="+"===g||"*"===g,y="?"===g||"*"===g,b=t[2]||"/",E=l||d||(m?".*":"[^"+b+"]+?");n.push({name:p||r++,prefix:h||"",delimiter:b,optional:y,repeat:w,partial:v,asterisk:!!m,pattern:u(E)})}}return o=46||"Chrome"===n&&r>=50)||(Cache.prototype.addAll=function(e){function t(e){this.name="NetworkError",this.code=19,this.message=e}var n=this;return t.prototype=Object.create(Error.prototype),Promise.resolve().then(function(){if(arguments.length<1)throw new TypeError;return e=e.map(function(e){return e instanceof Request?e:String(e)}),Promise.all(e.map(function(e){"string"==typeof e&&(e=new Request(e));var n=new URL(e.url).protocol;if("http:"!==n&&"https:"!==n)throw new t("Invalid scheme");return fetch(e.clone())}))}).then(function(r){if(r.some(function(e){return!e.ok}))throw new t("Incorrect response status");return Promise.all(r.map(function(t,r){return n.put(e[r],t)}))}).then(function(){})},Cache.prototype.add=function(e){return this.addAll([e])})}()},{}]},{},[13])(13)}); +//# sourceMappingURL=sw-toolbox.js.map diff --git a/sw-toolbox.js.map b/sw-toolbox.js.map new file mode 100644 index 0000000..e869f6f --- /dev/null +++ b/sw-toolbox.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["node_modules/browser-pack/_prelude.js","lib/helpers.js","lib/idb-cache-expiration.js","lib/listeners.js","lib/options.js","lib/route.js","lib/router.js","lib/strategies/cacheFirst.js","lib/strategies/cacheOnly.js","lib/strategies/fastest.js","lib/strategies/index.js","lib/strategies/networkFirst.js","lib/strategies/networkOnly.js","lib/sw-toolbox.js","node_modules/isarray/index.js","node_modules/path-to-regexp/index.js","node_modules/serviceworker-cache-polyfill/index.js"],"names":["f","exports","module","define","amd","g","window","global","self","this","toolbox","e","t","n","r","s","o","u","a","require","i","Error","code","l","call","length","1","debug","message","options","flag","globalOptions","console","log","openCache","cacheName","cache","name","caches","open","fetchAndCache","request","successResponses","fetch","clone","then","response","method","test","status","put","cacheOptions","maxEntries","maxAgeSeconds","queueCacheExpiration","cleanup","cleanupCache","bind","cleanupQueue","requestUrl","url","now","Date","idbCacheExpiration","getDb","db","setTimestampForUrl","expireEntries","urlsToDelete","deletionPromises","map","urlToDelete","delete","Promise","all","catch","error","renameCache","source","destination","results","sourceCache","destCache","keys","requests","match","add","uncache","precache","items","validatePrecacheInput","preCacheItems","concat","isValid","Array","isArray","forEach","item","Request","TypeError","openDb","resolve","reject","indexedDB","DB_PREFIX","DB_VERSION","onupgradeneeded","objectStore","result","createObjectStore","STORE_NAME","keyPath","URL_PROPERTY","createIndex","TIMESTAMP_PROPERTY","unique","onsuccess","onerror","cacheNameToDbPromise","transaction","timestamp","oncomplete","onabort","expireOldEntries","maxAgeMillis","urls","index","openCursor","cursorEvent","cursor","target","value","push","continue","expireExtraEntries","countRequest","count","initialCount","oldUrls","extraUrls","fetchListener","event","handler","router","respondWith","default","indexOf","activateListener","helpers","inactiveCache","waitUntil","flatten","reduce","b","installListener","join","addAll","scope","registration","URL","location","href","networkTimeoutSeconds","basePath","pathname","pathRegexp","Route","path","RegExp","fullUrlRegExp","regexp","prototype","makeHandler","values","exec","key","regexEscape","replace","keyMatch","string","entriesIterator","entries","next","matches","done","pattern","Router","routes","Map","set","origin","toLowerCase","route","has","methodMap","get","routeMap","regExp","matchMethod","urlObject","_match","methodMaps","pathOrUrl","cacheFirst","cacheOnly","fastest","rejected","reasons","maybeReject","reason","toString","maybeResolve","Response","networkOnly","networkFirst","timeoutId","originalResponse","promises","cacheWhenTimedOutPromise","setTimeout","networkPromise","clearTimeout","statusText","race","strategies","listeners","addEventListener","arr","Object","parse","str","res","tokens","PATH_REGEXP","m","escaped","offset","slice","prefix","capture","group","modifier","asterisk","partial","repeat","optional","delimiter","escapeGroup","substr","compile","tokensToFunction","encodeURIComponentPretty","encodeURI","c","charCodeAt","toUpperCase","encodeAsterisk","obj","opts","data","encode","pretty","encodeURIComponent","token","segment","isarray","JSON","stringify","j","escapeString","attachKeys","re","flags","sensitive","regexpToRegexp","groups","arrayToRegexp","parts","pathToRegexp","stringToRegexp","tokensToRegExp","strict","end","lastToken","endsWithSlash","nativeAddAll","Cache","userAgent","navigator","agent","version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AD,GAAA,WAAAA,EACA,KAAA,IAAAJ,GAAA,iBAGA,OAAAzP,OAAAF,EAAAG,cAGAC,KAAA,SAAA6P,GAGA,GAAAA,EAAAC,KAAA,SAAA7P,GACA,OAAAA,EAAA8P,KAEA,KAAA,IAAAR,GAAA,4BAKA,OAAA3N,SAAAC,IACAgO,EAAApO,IAAA,SAAAxB,EAAA1B,GACA,MAAAgB,GAAAc,IAAAkC,EAAAhE,GAAA0B,QAGAD,KAAA,eAKAiP,MAAAnH,UAAArF,IAAA,SAAA7C,GACA,MAAAhC,MAAAmJ,QAAAnH","file":"sw-toolbox.js","sourcesContent":["(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o cursor.value[TIMESTAMP_PROPERTY]) {\n var url = cursor.value[URL_PROPERTY];\n urls.push(url);\n objectStore.delete(url);\n cursor.continue();\n }\n }\n };\n\n transaction.oncomplete = function() {\n resolve(urls);\n };\n\n transaction.onabort = reject;\n });\n}\n\nfunction expireExtraEntries(db, maxEntries) {\n // Bail out early by resolving with an empty array if we're not using\n // maxEntries.\n if (!maxEntries) {\n return Promise.resolve([]);\n }\n\n return new Promise(function(resolve, reject) {\n var urls = [];\n\n var transaction = db.transaction(STORE_NAME, 'readwrite');\n var objectStore = transaction.objectStore(STORE_NAME);\n var index = objectStore.index(TIMESTAMP_PROPERTY);\n\n var countRequest = index.count();\n index.count().onsuccess = function() {\n var initialCount = countRequest.result;\n\n if (initialCount > maxEntries) {\n index.openCursor().onsuccess = function(cursorEvent) {\n var cursor = cursorEvent.target.result;\n if (cursor) {\n var url = cursor.value[URL_PROPERTY];\n urls.push(url);\n objectStore.delete(url);\n if (initialCount - urls.length > maxEntries) {\n cursor.continue();\n }\n }\n };\n }\n };\n\n transaction.oncomplete = function() {\n resolve(urls);\n };\n\n transaction.onabort = reject;\n });\n}\n\nfunction expireEntries(db, maxEntries, maxAgeSeconds, now) {\n return expireOldEntries(db, maxAgeSeconds, now).then(function(oldUrls) {\n return expireExtraEntries(db, maxEntries).then(function(extraUrls) {\n return oldUrls.concat(extraUrls);\n });\n });\n}\n\nmodule.exports = {\n getDb: getDb,\n setTimestampForUrl: setTimestampForUrl,\n expireEntries: expireEntries\n};\n","/*\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\n\n// For cache.addAll.\nrequire('serviceworker-cache-polyfill');\n\nvar helpers = require('./helpers');\nvar router = require('./router');\nvar options = require('./options');\n\n// Event listeners\n\nfunction fetchListener(event) {\n var handler = router.match(event.request);\n\n if (handler) {\n event.respondWith(handler(event.request));\n } else if (router.default &&\n event.request.method === 'GET' &&\n // Ensure that chrome-extension:// requests don't trigger the default route.\n event.request.url.indexOf('http') === 0) {\n event.respondWith(router.default(event.request));\n }\n}\n\nfunction activateListener(event) {\n helpers.debug('activate event fired');\n var inactiveCache = options.cache.name + '$$$inactive$$$';\n event.waitUntil(helpers.renameCache(inactiveCache, options.cache.name));\n}\n\nfunction flatten(items) {\n return items.reduce(function(a, b) {\n return a.concat(b);\n }, []);\n}\n\nfunction installListener(event) {\n var inactiveCache = options.cache.name + '$$$inactive$$$';\n helpers.debug('install event fired');\n helpers.debug('creating cache [' + inactiveCache + ']');\n event.waitUntil(\n helpers.openCache({cache: {name: inactiveCache}})\n .then(function(cache) {\n return Promise.all(options.preCacheItems)\n .then(flatten)\n .then(helpers.validatePrecacheInput)\n .then(function(preCacheItems) {\n helpers.debug('preCache list: ' +\n (preCacheItems.join(', ') || '(none)'));\n return cache.addAll(preCacheItems);\n });\n })\n );\n}\n\nmodule.exports = {\n fetchListener: fetchListener,\n activateListener: activateListener,\n installListener: installListener\n};\n","/*\n\tCopyright 2015 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\n'use strict';\n\n// TODO: This is necessary to handle different implementations in the wild\n// The spec defines self.registration, but it was not implemented in Chrome 40.\nvar scope;\nif (self.registration) {\n scope = self.registration.scope;\n} else {\n scope = self.scope || new URL('./', self.location).href;\n}\n\nmodule.exports = {\n cache: {\n name: '$$$toolbox-cache$$$' + scope + '$$$',\n maxAgeSeconds: null,\n maxEntries: null\n },\n debug: false,\n networkTimeoutSeconds: null,\n preCacheItems: [],\n // A regular expression to apply to HTTP response codes. Codes that match\n // will be considered successes, while others will not, and will not be\n // cached.\n successResponses: /^0|([123]\\d\\d)|(40[14567])|410$/\n};\n","/*\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\n\n// TODO: Use self.registration.scope instead of self.location\nvar url = new URL('./', self.location);\nvar basePath = url.pathname;\nvar pathRegexp = require('path-to-regexp');\n\nvar Route = function(method, path, handler, options) {\n if (path instanceof RegExp) {\n this.fullUrlRegExp = path;\n } else {\n // The URL() constructor can't parse express-style routes as they are not\n // valid urls. This means we have to manually manipulate relative urls into\n // absolute ones. This check is extremely naive but implementing a tweaked\n // version of the full algorithm seems like overkill\n // (https://url.spec.whatwg.org/#concept-basic-url-parser)\n if (path.indexOf('/') !== 0) {\n path = basePath + path;\n }\n\n this.keys = [];\n this.regexp = pathRegexp(path, this.keys);\n }\n\n this.method = method;\n this.options = options;\n this.handler = handler;\n};\n\nRoute.prototype.makeHandler = function(url) {\n var values;\n if (this.regexp) {\n var match = this.regexp.exec(url);\n values = {};\n this.keys.forEach(function(key, index) {\n values[key.name] = match[index + 1];\n });\n }\n\n return function(request) {\n return this.handler(request, values, this.options);\n }.bind(this);\n};\n\nmodule.exports = Route;\n","/*\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\n\nvar Route = require('./route');\nvar helpers = require('./helpers');\n\nfunction regexEscape(s) {\n return s.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n}\n\nvar keyMatch = function(map, string) {\n // This would be better written as a for..of loop, but that would break the\n // minifyify process in the build.\n var entriesIterator = map.entries();\n var item = entriesIterator.next();\n var matches = [];\n while (!item.done) {\n var pattern = new RegExp(item.value[0]);\n if (pattern.test(string)) {\n matches.push(item.value[1]);\n }\n item = entriesIterator.next();\n }\n return matches;\n};\n\nvar Router = function() {\n this.routes = new Map();\n // Create the dummy origin for RegExp-based routes\n this.routes.set(RegExp, new Map());\n this.default = null;\n};\n\n['get', 'post', 'put', 'delete', 'head', 'any'].forEach(function(method) {\n Router.prototype[method] = function(path, handler, options) {\n return this.add(method, path, handler, options);\n };\n});\n\nRouter.prototype.add = function(method, path, handler, options) {\n options = options || {};\n var origin;\n\n if (path instanceof RegExp) {\n // We need a unique key to use in the Map to distinguish RegExp paths\n // from Express-style paths + origins. Since we can use any object as the\n // key in a Map, let's use the RegExp constructor!\n origin = RegExp;\n } else {\n origin = options.origin || self.location.origin;\n if (origin instanceof RegExp) {\n origin = origin.source;\n } else {\n origin = regexEscape(origin);\n }\n }\n\n method = method.toLowerCase();\n\n var route = new Route(method, path, handler, options);\n\n if (!this.routes.has(origin)) {\n this.routes.set(origin, new Map());\n }\n\n var methodMap = this.routes.get(origin);\n if (!methodMap.has(method)) {\n methodMap.set(method, new Map());\n }\n\n var routeMap = methodMap.get(method);\n var regExp = route.regexp || route.fullUrlRegExp;\n\n if (routeMap.has(regExp.source)) {\n helpers.debug('\"' + path + '\" resolves to same regex as existing route.');\n }\n\n routeMap.set(regExp.source, route);\n};\n\nRouter.prototype.matchMethod = function(method, url) {\n var urlObject = new URL(url);\n var origin = urlObject.origin;\n var path = urlObject.pathname;\n\n // We want to first check to see if there's a match against any\n // \"Express-style\" routes (string for the path, RegExp for the origin).\n // Checking for Express-style matches first maintains the legacy behavior.\n // If there's no match, we next check for a match against any RegExp routes,\n // where the RegExp in question matches the full URL (both origin and path).\n return this._match(method, keyMatch(this.routes, origin), path) ||\n this._match(method, [this.routes.get(RegExp)], url);\n};\n\nRouter.prototype._match = function(method, methodMaps, pathOrUrl) {\n if (methodMaps.length === 0) {\n return null;\n }\n\n for (var i = 0; i < methodMaps.length; i++) {\n var methodMap = methodMaps[i];\n var routeMap = methodMap && methodMap.get(method.toLowerCase());\n if (routeMap) {\n var routes = keyMatch(routeMap, pathOrUrl);\n if (routes.length > 0) {\n return routes[0].makeHandler(pathOrUrl);\n }\n }\n }\n\n return null;\n};\n\nRouter.prototype.match = function(request) {\n return this.matchMethod(request.method, request.url) ||\n this.matchMethod('any', request.url);\n};\n\nmodule.exports = new Router();\n","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\n\nfunction cacheFirst(request, values, options) {\n helpers.debug('Strategy: cache first [' + request.url + ']', options);\n return helpers.openCache(options).then(function(cache) {\n return cache.match(request).then(function(response) {\n if (response) {\n return response;\n }\n\n return helpers.fetchAndCache(request, options);\n });\n });\n}\n\nmodule.exports = cacheFirst;\n","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\n\nfunction cacheOnly(request, values, options) {\n helpers.debug('Strategy: cache only [' + request.url + ']', options);\n return helpers.openCache(options).then(function(cache) {\n return cache.match(request);\n });\n}\n\nmodule.exports = cacheOnly;\n","/*\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\nvar cacheOnly = require('./cacheOnly');\n\nfunction fastest(request, values, options) {\n helpers.debug('Strategy: fastest [' + request.url + ']', options);\n\n return new Promise(function(resolve, reject) {\n var rejected = false;\n var reasons = [];\n\n var maybeReject = function(reason) {\n reasons.push(reason.toString());\n if (rejected) {\n reject(new Error('Both cache and network failed: \"' +\n reasons.join('\", \"') + '\"'));\n } else {\n rejected = true;\n }\n };\n\n var maybeResolve = function(result) {\n if (result instanceof Response) {\n resolve(result);\n } else {\n maybeReject('No result returned');\n }\n };\n\n helpers.fetchAndCache(request.clone(), options)\n .then(maybeResolve, maybeReject);\n\n cacheOnly(request, values, options)\n .then(maybeResolve, maybeReject);\n });\n}\n\nmodule.exports = fastest;\n","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\nmodule.exports = {\n networkOnly: require('./networkOnly'),\n networkFirst: require('./networkFirst'),\n cacheOnly: require('./cacheOnly'),\n cacheFirst: require('./cacheFirst'),\n fastest: require('./fastest')\n};\n","/*\n Copyright 2015 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\nvar globalOptions = require('../options');\nvar helpers = require('../helpers');\n\nfunction networkFirst(request, values, options) {\n options = options || {};\n var successResponses = options.successResponses ||\n globalOptions.successResponses;\n // This will bypass options.networkTimeout if it's set to a false-y value like\n // 0, but that's the sane thing to do anyway.\n var networkTimeoutSeconds = options.networkTimeoutSeconds ||\n globalOptions.networkTimeoutSeconds;\n helpers.debug('Strategy: network first [' + request.url + ']', options);\n\n return helpers.openCache(options).then(function(cache) {\n var timeoutId;\n var promises = [];\n var originalResponse;\n\n if (networkTimeoutSeconds) {\n var cacheWhenTimedOutPromise = new Promise(function(resolve) {\n timeoutId = setTimeout(function() {\n cache.match(request).then(function(response) {\n if (response) {\n // Only resolve this promise if there's a valid response in the\n // cache. This ensures that we won't time out a network request\n // unless there's a cached entry to fallback on, which is arguably\n // the preferable behavior.\n resolve(response);\n }\n });\n }, networkTimeoutSeconds * 1000);\n });\n promises.push(cacheWhenTimedOutPromise);\n }\n\n var networkPromise = helpers.fetchAndCache(request, options)\n .then(function(response) {\n // We've got a response, so clear the network timeout if there is one.\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n if (successResponses.test(response.status)) {\n return response;\n }\n\n helpers.debug('Response was an HTTP error: ' + response.statusText,\n options);\n originalResponse = response;\n throw new Error('Bad response');\n }).catch(function(error) {\n helpers.debug('Network or response error, fallback to cache [' +\n request.url + ']', options);\n return cache.match(request).then(function(response) {\n // If there's a match in the cache, resolve with that.\n if (response) {\n return response;\n }\n\n // If we have a Response object from the previous fetch, then resolve\n // with that, even though it corresponds to an error status code.\n if (originalResponse) {\n return originalResponse;\n }\n\n // If we don't have a Response object from the previous fetch, likely\n // due to a network failure, then reject with the failure error.\n throw error;\n });\n });\n\n promises.push(networkPromise);\n\n return Promise.race(promises);\n });\n}\n\nmodule.exports = networkFirst;\n","/*\n\tCopyright 2014 Google Inc. All Rights Reserved.\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n*/\n'use strict';\nvar helpers = require('../helpers');\n\nfunction networkOnly(request, values, options) {\n helpers.debug('Strategy: network only [' + request.url + ']', options);\n return fetch(request);\n}\n\nmodule.exports = networkOnly;\n","/*\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n'use strict';\n\n// This is the entrypoint for the sw-toolbox bundle. All code with\n// side effects (e.g. adding event listeners) should be in this file.\n\nvar options = require('./options');\nvar router = require('./router');\nvar helpers = require('./helpers');\nvar strategies = require('./strategies');\nvar listeners = require('./listeners');\n\nhelpers.debug('Service Worker Toolbox is loading');\n\n// Set up listeners.\n\nself.addEventListener('install', listeners.installListener);\nself.addEventListener('activate', listeners.activateListener);\nself.addEventListener('fetch', listeners.fetchListener);\n\nmodule.exports = {\n networkOnly: strategies.networkOnly,\n networkFirst: strategies.networkFirst,\n cacheOnly: strategies.cacheOnly,\n cacheFirst: strategies.cacheFirst,\n fastest: strategies.fastest,\n router: router,\n options: options,\n cache: helpers.cache,\n uncache: helpers.uncache,\n precache: helpers.precache\n};\n","module.exports = Array.isArray || function (arr) {\n return Object.prototype.toString.call(arr) == '[object Array]';\n};\n","var isarray = require('isarray')\n\n/**\n * Expose `pathToRegexp`.\n */\nmodule.exports = pathToRegexp\nmodule.exports.parse = parse\nmodule.exports.compile = compile\nmodule.exports.tokensToFunction = tokensToFunction\nmodule.exports.tokensToRegExp = tokensToRegExp\n\n/**\n * The main path matching regexp utility.\n *\n * @type {RegExp}\n */\nvar PATH_REGEXP = new RegExp([\n // Match escaped characters that would otherwise appear in future matches.\n // This allows the user to escape special characters that won't transform.\n '(\\\\\\\\.)',\n // Match Express-style parameters and un-named parameters with a prefix\n // and optional suffixes. Matches appear as:\n //\n // \"/:test(\\\\d+)?\" => [\"/\", \"test\", \"\\d+\", undefined, \"?\", undefined]\n // \"/route(\\\\d+)\" => [undefined, undefined, undefined, \"\\d+\", undefined, undefined]\n // \"/*\" => [\"/\", undefined, undefined, undefined, undefined, \"*\"]\n '([\\\\/.])?(?:(?:\\\\:(\\\\w+)(?:\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))?|\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))([+*?])?|(\\\\*))'\n].join('|'), 'g')\n\n/**\n * Parse a string for the raw tokens.\n *\n * @param {string} str\n * @return {!Array}\n */\nfunction parse (str) {\n var tokens = []\n var key = 0\n var index = 0\n var path = ''\n var res\n\n while ((res = PATH_REGEXP.exec(str)) != null) {\n var m = res[0]\n var escaped = res[1]\n var offset = res.index\n path += str.slice(index, offset)\n index = offset + m.length\n\n // Ignore already escaped sequences.\n if (escaped) {\n path += escaped[1]\n continue\n }\n\n var next = str[index]\n var prefix = res[2]\n var name = res[3]\n var capture = res[4]\n var group = res[5]\n var modifier = res[6]\n var asterisk = res[7]\n\n // Push the current path onto the tokens.\n if (path) {\n tokens.push(path)\n path = ''\n }\n\n var partial = prefix != null && next != null && next !== prefix\n var repeat = modifier === '+' || modifier === '*'\n var optional = modifier === '?' || modifier === '*'\n var delimiter = res[2] || '/'\n var pattern = capture || group || (asterisk ? '.*' : '[^' + delimiter + ']+?')\n\n tokens.push({\n name: name || key++,\n prefix: prefix || '',\n delimiter: delimiter,\n optional: optional,\n repeat: repeat,\n partial: partial,\n asterisk: !!asterisk,\n pattern: escapeGroup(pattern)\n })\n }\n\n // Match any characters still remaining.\n if (index < str.length) {\n path += str.substr(index)\n }\n\n // If the path exists, push it onto the end.\n if (path) {\n tokens.push(path)\n }\n\n return tokens\n}\n\n/**\n * Compile a string to a template function for the path.\n *\n * @param {string} str\n * @return {!function(Object=, Object=)}\n */\nfunction compile (str) {\n return tokensToFunction(parse(str))\n}\n\n/**\n * Prettier encoding of URI path segments.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeURIComponentPretty (str) {\n return encodeURI(str).replace(/[\\/?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeAsterisk (str) {\n return encodeURI(str).replace(/[?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Expose a method for transforming tokens into the path function.\n */\nfunction tokensToFunction (tokens) {\n // Compile all the tokens into regexps.\n var matches = new Array(tokens.length)\n\n // Compile all the patterns before compilation.\n for (var i = 0; i < tokens.length; i++) {\n if (typeof tokens[i] === 'object') {\n matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$')\n }\n }\n\n return function (obj, opts) {\n var path = ''\n var data = obj || {}\n var options = opts || {}\n var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent\n\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n path += token\n\n continue\n }\n\n var value = data[token.name]\n var segment\n\n if (value == null) {\n if (token.optional) {\n // Prepend partial segment prefixes.\n if (token.partial) {\n path += token.prefix\n }\n\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to be defined')\n }\n }\n\n if (isarray(value)) {\n if (!token.repeat) {\n throw new TypeError('Expected \"' + token.name + '\" to not repeat, but received `' + JSON.stringify(value) + '`')\n }\n\n if (value.length === 0) {\n if (token.optional) {\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to not be empty')\n }\n }\n\n for (var j = 0; j < value.length; j++) {\n segment = encode(value[j])\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected all \"' + token.name + '\" to match \"' + token.pattern + '\", but received `' + JSON.stringify(segment) + '`')\n }\n\n path += (j === 0 ? token.prefix : token.delimiter) + segment\n }\n\n continue\n }\n\n segment = token.asterisk ? encodeAsterisk(value) : encode(value)\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected \"' + token.name + '\" to match \"' + token.pattern + '\", but received \"' + segment + '\"')\n }\n\n path += token.prefix + segment\n }\n\n return path\n }\n}\n\n/**\n * Escape a regular expression string.\n *\n * @param {string} str\n * @return {string}\n */\nfunction escapeString (str) {\n return str.replace(/([.+*?=^!:${}()[\\]|\\/\\\\])/g, '\\\\$1')\n}\n\n/**\n * Escape the capturing group by escaping special characters and meaning.\n *\n * @param {string} group\n * @return {string}\n */\nfunction escapeGroup (group) {\n return group.replace(/([=!:$\\/()])/g, '\\\\$1')\n}\n\n/**\n * Attach the keys as a property of the regexp.\n *\n * @param {!RegExp} re\n * @param {Array} keys\n * @return {!RegExp}\n */\nfunction attachKeys (re, keys) {\n re.keys = keys\n return re\n}\n\n/**\n * Get the flags for a regexp from the options.\n *\n * @param {Object} options\n * @return {string}\n */\nfunction flags (options) {\n return options.sensitive ? '' : 'i'\n}\n\n/**\n * Pull out keys from a regexp.\n *\n * @param {!RegExp} path\n * @param {!Array} keys\n * @return {!RegExp}\n */\nfunction regexpToRegexp (path, keys) {\n // Use a negative lookahead to match only capturing groups.\n var groups = path.source.match(/\\((?!\\?)/g)\n\n if (groups) {\n for (var i = 0; i < groups.length; i++) {\n keys.push({\n name: i,\n prefix: null,\n delimiter: null,\n optional: false,\n repeat: false,\n partial: false,\n asterisk: false,\n pattern: null\n })\n }\n }\n\n return attachKeys(path, keys)\n}\n\n/**\n * Transform an array into a regexp.\n *\n * @param {!Array} path\n * @param {Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction arrayToRegexp (path, keys, options) {\n var parts = []\n\n for (var i = 0; i < path.length; i++) {\n parts.push(pathToRegexp(path[i], keys, options).source)\n }\n\n var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options))\n\n return attachKeys(regexp, keys)\n}\n\n/**\n * Create a path regexp from string input.\n *\n * @param {string} path\n * @param {!Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction stringToRegexp (path, keys, options) {\n var tokens = parse(path)\n var re = tokensToRegExp(tokens, options)\n\n // Attach keys back to the regexp.\n for (var i = 0; i < tokens.length; i++) {\n if (typeof tokens[i] !== 'string') {\n keys.push(tokens[i])\n }\n }\n\n return attachKeys(re, keys)\n}\n\n/**\n * Expose a function for taking tokens and returning a RegExp.\n *\n * @param {!Array} tokens\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction tokensToRegExp (tokens, options) {\n options = options || {}\n\n var strict = options.strict\n var end = options.end !== false\n var route = ''\n var lastToken = tokens[tokens.length - 1]\n var endsWithSlash = typeof lastToken === 'string' && /\\/$/.test(lastToken)\n\n // Iterate over the tokens and create our regexp string.\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n route += escapeString(token)\n } else {\n var prefix = escapeString(token.prefix)\n var capture = '(?:' + token.pattern + ')'\n\n if (token.repeat) {\n capture += '(?:' + prefix + capture + ')*'\n }\n\n if (token.optional) {\n if (!token.partial) {\n capture = '(?:' + prefix + '(' + capture + '))?'\n } else {\n capture = prefix + '(' + capture + ')?'\n }\n } else {\n capture = prefix + '(' + capture + ')'\n }\n\n route += capture\n }\n }\n\n // In non-strict mode we allow a slash at the end of match. If the path to\n // match already ends with a slash, we remove it for consistency. The slash\n // is valid at the end of a path match, not in the middle. This is important\n // in non-ending mode, where \"/test/\" shouldn't match \"/test//route\".\n if (!strict) {\n route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\\\/(?=$))?'\n }\n\n if (end) {\n route += '$'\n } else {\n // In non-ending mode, we need the capturing groups to match as much as\n // possible by using a positive lookahead to the end or next path segment.\n route += strict && endsWithSlash ? '' : '(?=\\\\/|$)'\n }\n\n return new RegExp('^' + route, flags(options))\n}\n\n/**\n * Normalize the given path string, returning a regular expression.\n *\n * An empty array can be passed in for the keys, which will hold the\n * placeholder key descriptions. For example, using `/user/:id`, `keys` will\n * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.\n *\n * @param {(string|RegExp|Array)} path\n * @param {(Array|Object)=} keys\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction pathToRegexp (path, keys, options) {\n keys = keys || []\n\n if (!isarray(keys)) {\n options = /** @type {!Object} */ (keys)\n keys = []\n } else if (!options) {\n options = {}\n }\n\n if (path instanceof RegExp) {\n return regexpToRegexp(path, /** @type {!Array} */ (keys))\n }\n\n if (isarray(path)) {\n return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)\n }\n\n return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)\n}\n","/**\n * Copyright 2015 Google Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n(function() {\n var nativeAddAll = Cache.prototype.addAll;\n var userAgent = navigator.userAgent.match(/(Firefox|Chrome)\\/(\\d+\\.)/);\n\n // Has nice behavior of `var` which everyone hates\n if (userAgent) {\n var agent = userAgent[1];\n var version = parseInt(userAgent[2]);\n }\n\n if (\n nativeAddAll && (!userAgent ||\n (agent === 'Firefox' && version >= 46) ||\n (agent === 'Chrome' && version >= 50)\n )\n ) {\n return;\n }\n\n Cache.prototype.addAll = function addAll(requests) {\n var cache = this;\n\n // Since DOMExceptions are not constructable:\n function NetworkError(message) {\n this.name = 'NetworkError';\n this.code = 19;\n this.message = message;\n }\n\n NetworkError.prototype = Object.create(Error.prototype);\n\n return Promise.resolve().then(function() {\n if (arguments.length < 1) throw new TypeError();\n\n // Simulate sequence<(Request or USVString)> binding:\n var sequence = [];\n\n requests = requests.map(function(request) {\n if (request instanceof Request) {\n return request;\n }\n else {\n return String(request); // may throw TypeError\n }\n });\n\n return Promise.all(\n requests.map(function(request) {\n if (typeof request === 'string') {\n request = new Request(request);\n }\n\n var scheme = new URL(request.url).protocol;\n\n if (scheme !== 'http:' && scheme !== 'https:') {\n throw new NetworkError(\"Invalid scheme\");\n }\n\n return fetch(request.clone());\n })\n );\n }).then(function(responses) {\n // If some of the responses has not OK-eish status,\n // then whole operation should reject\n if (responses.some(function(response) {\n return !response.ok;\n })) {\n throw new NetworkError('Incorrect response status');\n }\n\n // TODO: check that requests don't overwrite one another\n // (don't think this is possible to polyfill due to opaque responses)\n return Promise.all(\n responses.map(function(response, i) {\n return cache.put(requests[i], response);\n })\n );\n }).then(function() {\n return undefined;\n });\n };\n\n Cache.prototype.add = function add(request) {\n return this.addAll([request]);\n };\n}());"],"sourceRoot":"/source/"} \ No newline at end of file