Enable prettier (#2929)

* Deps and config

* Prettier output

* Update hardcoded file sizes

* More file size updates
This commit is contained in:
Jeffrey Posnick
2021-08-26 14:57:20 -07:00
committed by GitHub
parent af5692fd3a
commit 7d4c4434a4
328 changed files with 11459 additions and 7800 deletions
+4 -4
View File
@@ -1,12 +1,12 @@
Welcome! Please use this template for reporting bugs or requesting features. For questions about using Workbox, the best place to ask is Stack Overflow, tagged with `[workbox]`: https://stackoverflow.com/questions/ask?tags=workbox
**Library Affected**:
*workbox-sw, workbox-build, etc.*
_workbox-sw, workbox-build, etc._
**Browser & Platform**:
*E.g. Google Chrome v51.0.1 for Android, or "all browsers".*
_E.g. Google Chrome v51.0.1 for Android, or "all browsers"._
**Issue or Feature Request Description**:
*Your request here.*
_Your request here._
*When reporting bugs, please include relevant JavaScript Console logs and links to public URLs at which the issue could be reproduced.*
_When reporting bugs, please include relevant JavaScript Console logs and links to public URLs at which the issue could be reproduced._
+3 -2
View File
@@ -1,9 +1,10 @@
**Prior to filing a PR, please:**
- [open an issue](https://github.com/GoogleChrome/workbox/issues/new) to discuss your proposed change.
- ensure that `gulp build && gulp lint test` passes locally.
R: @jeffposnick @tropicadri
Fixes #*issue number*
Fixes #_issue number_
*Description of what's changed/fixed.*
_Description of what's changed/fixed._
+35 -35
View File
@@ -7,52 +7,52 @@ jobs:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v2
- uses: actions/cache@v1
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- uses: actions/cache@v1
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- uses: actions/setup-node@v1
with:
node-version: 10.x
- uses: actions/setup-node@v1
with:
node-version: 10.x
- name: Setup
run: |
npm ci
npx gulp build
- name: Setup
run: |
npm ci
npx gulp build
- run: npx gulp test_node
- run: npx gulp test_node
Full_Suite_Mac:
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v2
- uses: actions/cache@v1
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- uses: actions/cache@v1
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- uses: actions/cache@v1
with:
path: ~/.selenium-assistant
key: ${{ runner.os }}
- uses: actions/cache@v1
with:
path: ~/.selenium-assistant
key: ${{ runner.os }}
- uses: actions/setup-node@v1
with:
node-version: 12.x
- uses: actions/setup-node@v1
with:
node-version: 12.x
- name: Setup
run: |
sudo safaridriver --enable
npm ci
npx gulp build
- name: Setup
run: |
sudo safaridriver --enable
npm ci
npx gulp build
- run: npx gulp test
- run: npx gulp test
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run format-staged
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run lint
+13
View File
@@ -0,0 +1,13 @@
.nyc_output
.vscode
*.hbs
*.log
build
coverage
docs
generated-release-files
node_modules
packages/**
!packages/*/src/**
temp
test/workbox-webpack-plugin/static/injected-manifest.json
+4 -3
View File
@@ -5,8 +5,9 @@
We'd love to accept your patches! Before we can take them, we have to jump a couple of legal hurdles.
Please fill out either the individual or corporate Contributor License Agreement (CLA).
* If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual).
* If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate).
- If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual).
- If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate).
Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to
accept your pull requests.
@@ -42,4 +43,4 @@ To do an automated run of the full test suite for the browser-based code against
```
npm run gulp test_integration
```
```
+3 -3
View File
@@ -7,9 +7,9 @@ Workbox is a collection of JavaScript libraries for
## Documentation
* [Overview](https://developers.google.com/web/tools/workbox/) ([site source](https://github.com/google/WebFundamentals/tree/main/src/content/en/tools/workbox))
* [Get started](https://developers.google.com/web/tools/workbox/guides/get-started)
* [Contribute](CONTRIBUTING.md)
- [Overview](https://developers.google.com/web/tools/workbox/) ([site source](https://github.com/google/WebFundamentals/tree/main/src/content/en/tools/workbox))
- [Get started](https://developers.google.com/web/tools/workbox/guides/get-started)
- [Contribute](CONTRIBUTING.md)
## Contributing
@@ -2,30 +2,37 @@
<html lang="en">
<head>
<title>workbox-background-sync demo</title>
<meta name="workbox-background-sync demo" content="An example to demonstrate the workbox-background-sync module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-background-sync demo"
content="An example to demonstrate the workbox-background-sync module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<div>
<h1>workbox-background-sync Demo</h1>
@@ -33,37 +40,49 @@
</header>
<ol>
<li><a href="https://developers.google.com/web/tools/chrome-devtools/#open">Open DevTools.</a></li>
<li>
<a href="https://developers.google.com/web/tools/chrome-devtools/#open"
>Open DevTools.</a
>
</li>
<li>Switch to the Network panel.</li>
<li>Toggle `Disable cache` checkbox on (it's unchecked by default).</li>
<li>Click `Make Fetch request` button below.</li>
<li>Observe that request is successfully completed with status 200.</li>
<li>Disconnect from actual network (DevTools offline doesn't work for background sync).</li>
<li>
Disconnect from actual network (DevTools offline doesn't work for
background sync).
</li>
<li>Again, click `Make Fetch request` button below.</li>
<li>Observe that request is aborted due to no network.</li>
<li>Connect to your network and observe the Network panel in DevTools.</li>
<li>Once the network is connected, you will see that the request is retried automatically upon the `sync` event.</li>
<li>
Connect to your network and observe the Network panel in DevTools.
</li>
<li>
Once the network is connected, you will see that the request is retried
automatically upon the `sync` event.
</li>
</ol>
<button class="fetch">Make fetch request</button><p>
<button class="fetch">Make fetch request</button>
<p>
<script>
document.querySelector('.fetch').addEventListener('click', () => {
fetch('example.txt');
});
<script>
document.querySelector('.fetch').addEventListener('click', () => {
fetch('example.txt');
});
navigator.serviceWorker.register('./sw.js');
</script>
navigator.serviceWorker.register('./sw.js');
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
</p>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
@@ -1,15 +1,15 @@
{
"name": "workbox-background-sync",
"version": "1.0.0",
"description": "Workbox Background Sync Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
"name": "workbox-background-sync",
"version": "1.0.0",
"description": "Workbox Background Sync Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
+9 -6
View File
@@ -1,4 +1,6 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
// Note: Ignore the error that Glitch raises about workbox being undefined.
workbox.setConfig({
@@ -6,13 +8,14 @@ workbox.setConfig({
});
const bgSyncPlugin = new workbox.backgroundSync.BackgroundSyncPlugin(
'myQueueName');
'myQueueName',
);
workbox.routing.registerRoute(
({url}) => url.pathname === '/example.txt',
new workbox.strategies.NetworkOnly({
plugins: [bgSyncPlugin],
}),
({url}) => url.pathname === '/example.txt',
new workbox.strategies.NetworkOnly({
plugins: [bgSyncPlugin],
}),
);
workbox.core.skipWaiting();
@@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
@@ -2,31 +2,38 @@
<html lang="en">
<head>
<title>workbox-broadcast-update demo</title>
<meta name="workbox-broadcast-update demo" content="An example to demonstrate the workbox-broadcast-update module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-broadcast-update demo"
content="An example to demonstrate the workbox-broadcast-update module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<header>
<div>
<h1>workbox-broadcast-update Demo</h1>
</div>
@@ -35,27 +42,30 @@
<ol>
<li>Open DevTools</li>
<li>Go to the Console</li>
<li>Click any of the buttons below and view the logs:
<li>
Click any of the buttons below and view the logs:
<ul>
<li><p><button class="trigger-broadcast">Trigger a Broadcast</button></p></li>
<li>
<p>
<button class="trigger-broadcast">Trigger a Broadcast</button>
</p>
</li>
</ul>
</li>
</ol>
<script>
const triggerBroadcast = document.querySelector('.trigger-broadcast');
window.addEventListener('load', () => {
navigator.serviceWorker.register('./sw.js')
.then((reg) => {
navigator.serviceWorker.register('./sw.js').then((reg) => {
triggerBroadcast.addEventListener('click', () => {
const message = {
command: 'trigger-broadcast',
};
reg.active.postMessage(message);
});
navigator.serviceWorker.addEventListener('message', (event) => {
console.log(`Received a message from workbox-broadcast-update.`);
console.log(event.data);
@@ -64,14 +74,14 @@
});
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
@@ -1,15 +1,15 @@
{
"name": "workbox-broadcast-update",
"version": "1.0.0",
"description": "Workbox Broadcast Update Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
"name": "workbox-broadcast-update",
"version": "1.0.0",
"description": "Workbox Broadcast Update Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
@@ -1,12 +1,13 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
workbox.setConfig({
debug: true,
});
const broadcastUpdate = new workbox.broadcastUpdate.BroadcastCacheUpdate(
'broadcast-update-demo',
'broadcast-update-demo',
);
const initialResponse = new Response('Response 1', {
@@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
+54 -32
View File
@@ -2,31 +2,38 @@
<html lang="en">
<head>
<title>workbox-cacheable-response demo</title>
<meta name="workbox-cacheable-response demo" content="An example to demonstrate the workbox-cacheable-response module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-cacheable-response demo"
content="An example to demonstrate the workbox-cacheable-response module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<header>
<div>
<h1>workbox-cacheable-response Demo</h1>
</div>
@@ -35,16 +42,34 @@
<ol>
<li>Open DevTools</li>
<li>Go to the Console</li>
<li>Click any of the buttons below and view the logs and network responses:
<li>
Click any of the buttons below and view the logs and network responses:
<ul>
<li><p><button class="with-good-header">With 'X-Is-Cacheable: true' Header</button></p></li>
<li><p><button class="with-bad-header">With 'X-Is-Cacheable: false' Header</button></p></li>
<li><p><button class="without-header">Without 'X-Is-Cacheable' Header</button></p></li>
<li>
<p>
<button class="with-good-header">
With 'X-Is-Cacheable: true' Header
</button>
</p>
</li>
<li>
<p>
<button class="with-bad-header">
With 'X-Is-Cacheable: false' Header
</button>
</p>
</li>
<li>
<p>
<button class="without-header">
Without 'X-Is-Cacheable' Header
</button>
</p>
</li>
</ul>
</li>
</ol>
<script>
const withGoodHeaderBtn = document.querySelector('.with-good-header');
const withBadHeaderBtn = document.querySelector('.with-bad-header');
@@ -53,41 +78,38 @@
const DEMO_REQUEST_URL = '/api/is-response-cacheable';
window.addEventListener('load', () => {
navigator.serviceWorker.register('./sw.js')
.then(() => {
navigator.serviceWorker.register('./sw.js').then(() => {
withGoodHeaderBtn.addEventListener('click', () => {
fetch(DEMO_REQUEST_URL, {
headers: {
'X-Is-Cacheable': true
}
'X-Is-Cacheable': true,
},
});
});
withBadHeaderBtn.addEventListener('click', () => {
fetch(DEMO_REQUEST_URL, {
headers: {
'X-Is-Cacheable': false
}
'X-Is-Cacheable': false,
},
});
});
withoutHeaderBtn.addEventListener('click', () => {
fetch(DEMO_REQUEST_URL);
});
});
});
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
@@ -13,4 +13,4 @@
"node": "8.x"
},
"license": "MIT"
}
}
+13 -16
View File
@@ -9,31 +9,28 @@ const app = express();
// but feel free to use whatever libs or frameworks you'd like through `package.json`.
// http://expressjs.com/en/starter/basic-routing.html
app.get('/', function(request, response) {
app.get('/', function (request, response) {
response.sendFile(__dirname + '/index.html');
});
app.get('/sw.js', function(request, response) {
app.get('/sw.js', function (request, response) {
response.sendFile(__dirname + '/sw.js');
});
// listen for requests :)
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
app.get('/api/is-response-cacheable',
function(req, res) {
if (req.headers['x-is-cacheable']) {
const value = req.headers['x-is-cacheable'];
res.set('X-Is-Cacheable', value);
res.send(`This response has 'X-Is-Cacheable' header set to '${value}'`);
} else {
res.send(`This response has no 'X-Is-Cacheable' header`);
}
},
);
app.get('/api/is-response-cacheable', function (req, res) {
if (req.headers['x-is-cacheable']) {
const value = req.headers['x-is-cacheable'];
res.set('X-Is-Cacheable', value);
res.send(`This response has 'X-Is-Cacheable' header set to '${value}'`);
} else {
res.send(`This response has no 'X-Is-Cacheable' header`);
}
});
/* /////////////////////////////////////////////////////////////////////////////
The code below this comment is unrelated to the demo and used for maintenance
@@ -53,7 +50,7 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
+11 -11
View File
@@ -1,10 +1,11 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
workbox.setConfig({
debug: true,
});
const cacheable = new workbox.cacheableResponse.CacheableResponse({
statuses: [200],
headers: {
@@ -13,16 +14,15 @@ const cacheable = new workbox.cacheableResponse.CacheableResponse({
});
const handleCachableResponse = (event) => {
return fetch(event.request)
.then((response) => {
if (cacheable.isResponseCacheable(response)) {
console.log('Response meets the criteria');
} else {
console.log('Response does NOT meet the criteria');
}
return fetch(event.request).then((response) => {
if (cacheable.isResponseCacheable(response)) {
console.log('Response meets the criteria');
} else {
console.log('Response does NOT meet the criteria');
}
return response;
});
return response;
});
};
self.addEventListener('fetch', (event) => {
+57 -36
View File
@@ -2,31 +2,38 @@
<html lang="en">
<head>
<title>workbox-core demo</title>
<meta name="workbox-core demo" content="An example to demonstrate the workbox-core module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-core demo"
content="An example to demonstrate the workbox-core module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
}
ol {
padding-left: 20px
}
li {
margin-bottom: 5px
}
button {
margin: 20px 0;
font-weight: bold
}
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px;
}
li {
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold;
}
</style>
</head>
<body>
<header>
<header>
<div>
<h1>workbox-core demo</h1>
</div>
@@ -35,12 +42,27 @@
<ol>
<li>Open DevTools</li>
<li>Go to the Console</li>
<li>Click this button:<br /><button class="install-sw">Install Service Worker</button></li>
<li>
Click this button:<br /><button class="install-sw">
Install Service Worker
</button>
</li>
<li>Checkout the logs for info on Workbox and getting started.</li>
<li>Click this button to print out various types of logs:<br /><button class="show-logs">Show Me Workbox Logs</button></li>
<li>Click this button to print out the Workbox Cache Names:<br /><button class="show-cache-names">Show Me Workbox Cache Names</button></li>
<li>
Click this button to print out various types of logs:<br /><button
class="show-logs"
>
Show Me Workbox Logs
</button>
</li>
<li>
Click this button to print out the Workbox Cache Names:<br /><button
class="show-cache-names"
>
Show Me Workbox Cache Names
</button>
</li>
</ol>
<script>
const installSWBtn = document.querySelector('.install-sw');
@@ -48,9 +70,8 @@
const cacheNamesBtn = document.querySelector('.show-cache-names');
installSWBtn.addEventListener('click', () => {
console.log("Installing service worker");
navigator.serviceWorker.register('/sw.js')
.then((reg) => {
console.log('Installing service worker');
navigator.serviceWorker.register('/sw.js').then((reg) => {
showLogsBtn.addEventListener('click', () => {
const message = {
command: 'printLogs',
@@ -67,14 +88,14 @@
});
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
+14 -14
View File
@@ -1,15 +1,15 @@
{
"name": "workbox-core",
"version": "1.0.0",
"description": "Workbox Core Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
"name": "workbox-core",
"version": "1.0.0",
"description": "Workbox Core Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
+3 -1
View File
@@ -1,4 +1,6 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
// Note: Ignore the error that Glitch raises about workbox being undefined.
workbox.setConfig({
+2 -2
View File
@@ -28,12 +28,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
+61 -39
View File
@@ -2,66 +2,90 @@
<html lang="en">
<head>
<title>workbox-expiration demo</title>
<meta name="workbox-expiration demo" content="An example to demonstrate the workbox-expiration module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-expiration demo"
content="An example to demonstrate the workbox-expiration module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<header>
<div>
<h1>workbox-expiration Demo</h1>
</div>
</header>
<ol>
<li>Open DevTools</li>
<li>Go to the Console</li>
<li>Click the following buttons and look at the Cache and IndexedDB entries.
<li>
Click the following buttons and look at the Cache and IndexedDB entries.
<ol>
<li><button class="entry-1">Entry 1</button> (Expires in: <span class="entry-expire-1">Not Added Yet</span>)</li>
<li><button class="entry-2">Entry 2</button> (Expires in: <span class="entry-expire-2">Not Added Yet</span>)</li>
<li><button class="entry-3">Entry 3</button> (Expires in: <span class="entry-expire-3">Not Added Yet</span>)</li>
<li><button class="entry-4">Entry 4</button> (Expires in: <span class="entry-expire-4">Not Added Yet</span>)</li>
<li><button class="entry-5">Entry 5</button> (Expires in: <span class="entry-expire-5">Not Added Yet</span>)</li>
<li>
<button class="entry-1">Entry 1</button> (Expires in:
<span class="entry-expire-1">Not Added Yet</span>)
</li>
<li>
<button class="entry-2">Entry 2</button> (Expires in:
<span class="entry-expire-2">Not Added Yet</span>)
</li>
<li>
<button class="entry-3">Entry 3</button> (Expires in:
<span class="entry-expire-3">Not Added Yet</span>)
</li>
<li>
<button class="entry-4">Entry 4</button> (Expires in:
<span class="entry-expire-4">Not Added Yet</span>)
</li>
<li>
<button class="entry-5">Entry 5</button> (Expires in:
<span class="entry-expire-5">Not Added Yet</span>)
</li>
</ol>
</li>
<li>To remove any expired entries click here:<p><button class="expire">Expire Entries</button></li>
<li>
To remove any expired entries click here:
<p><button class="expire">Expire Entries</button></p>
</li>
</ol>
<script>
const expireBtn = document.querySelector('.expire');
const TIMEOUT_IN_SECS = 30;
const MAX_ENTRIES = 3;
var entryQueue = [];
const setupTimeout = (btnElement, textElement) => {
textElement.textContent = `${btnElement.__workbox_timeoutCount}s`;
btnElement.__workbox_timeoutId = setTimeout(() => {
// TODO: FIX THIS TO TAKE FIRST ELEMENT OF CLASS LIST AND CHECK AGAIN ENTRY STACK
if(entryQueue.includes(btnElement.classList[0])){
if (entryQueue.includes(btnElement.classList[0])) {
btnElement.__workbox_timeoutCount -= 1;
if (btnElement.__workbox_timeoutCount > 0) {
setupTimeout(btnElement, textElement);
@@ -69,15 +93,13 @@
textElement.textContent = `Expired (Too Old)`;
}
} else {
textElement.textContent = `Expired (Too Many)`;
textElement.textContent = `Expired (Too Many)`;
}
}, 1000);
};
window.addEventListener('load', () => {
navigator.serviceWorker.register('./sw.js')
.then((reg) => {
navigator.serviceWorker.register('./sw.js').then((reg) => {
for (let i = 0; i < 5; i++) {
const entryBtn = document.querySelector(`.entry-${i + 1}`);
const expireText = document.querySelector(`.entry-expire-${i + 1}`);
@@ -86,16 +108,16 @@
command: 'update-entry',
id: i + 1,
};
var arrayEntry = `entry-${i + 1}`
var arrayEntry = `entry-${i + 1}`;
//If we refresh an entry that has already been added and is not expired
//we reorder it to the front of the queue
if(entryQueue.includes(arrayEntry)){
if (entryQueue.includes(arrayEntry)) {
entryQueue.splice(entryQueue.indexOf(arrayEntry), 1);
}
entryQueue.push(`entry-${i + 1}`);
if(entryQueue.length >= 4){
if (entryQueue.length >= 4) {
entryQueue = entryQueue.slice(MAX_ENTRIES * -1);
}
@@ -120,14 +142,14 @@
});
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
+14 -14
View File
@@ -1,15 +1,15 @@
{
"name": "workbox-expiration",
"version": "1.0.0",
"description": "Workbox Expiration Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
"name": "workbox-expiration",
"version": "1.0.0",
"description": "Workbox Expiration Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
+11 -7
View File
@@ -1,4 +1,6 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
// Note: Ignore the error that Glitch raises about workbox being undefined.
workbox.setConfig({
@@ -6,17 +8,19 @@ workbox.setConfig({
});
const expirationManager = new workbox.expiration.CacheExpiration(
'demo-cache-for-expiration', {
maxEntries: 3,
maxAgeSeconds: 30,
});
'demo-cache-for-expiration',
{
maxEntries: 3,
maxAgeSeconds: 30,
},
);
const updateEntry = async (entryID) => {
const openCache = await caches.open('demo-cache-for-expiration');
openCache.put(
`example-entry-${entryID}`,
new Response(`Hello from entry number ${entryID}`),
`example-entry-${entryID}`,
new Response(`Hello from entry number ${entryID}`),
);
expirationManager.updateTimestamp(`example-entry-${entryID}`);
+2 -2
View File
@@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
+62 -30
View File
@@ -2,31 +2,38 @@
<html lang="en">
<head>
<title>workbox-google-analytics demo</title>
<meta name="workbox-googleAnalytics demo" content="An example to demonstrate the workbox-google-analytics module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-googleAnalytics demo"
content="An example to demonstrate the workbox-google-analytics module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<header>
<div>
<h1>workbox-google-analytics Demo</h1>
</div>
@@ -35,19 +42,45 @@
<ol>
<li>Open DevTools</li>
<li>Go to the Console</li>
<li>Click this button:<p><button class="make-analytics-call">Make Analytics Call</button></li>
<li>Turn off your machine's connection and press the button again. Of course, the requests fail</li>
<li>Upon reconnecting to the network, workbox-googleAnalytics will empty the request queue</li>
<li>
Click this button:
<p><button class="make-analytics-call">Make Analytics Call</button></p>
</li>
<li>
Turn off your machine's connection and press the button again. Of
course, the requests fail
</li>
<li>
Upon reconnecting to the network, workbox-googleAnalytics will empty the
request queue
</li>
</ol>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-77119321-5"></script>
<script
async
src="https://www.googletagmanager.com/gtag/js?id=UA-77119321-5"
></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
(i[r] =
i[r] ||
function () {
(i[r].q = i[r].q || []).push(arguments);
}),
(i[r].l = 1 * new Date());
(a = s.createElement(o)), (m = s.getElementsByTagName(o)[0]);
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m);
})(
window,
document,
'script',
'https://www.google-analytics.com/analytics.js',
'ga',
);
ga('create', 'UA-77119321-5', 'auto');
</script>
@@ -55,22 +88,21 @@
<script>
const analyticsCallBtn = document.querySelector('.make-analytics-call');
navigator.serviceWorker.register('./sw.js')
.then((reg) => {
navigator.serviceWorker.register('./sw.js').then((reg) => {
analyticsCallBtn.addEventListener('click', () => {
ga('send', 'pageview');
});
});
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
+14 -14
View File
@@ -1,15 +1,15 @@
{
"name": "workbox-google-analytics",
"version": "1.0.0",
"description": "Workbox Google Analytics Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
"name": "workbox-google-analytics",
"version": "1.0.0",
"description": "Workbox Google Analytics Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
+3 -2
View File
@@ -1,10 +1,11 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
workbox.setConfig({
debug: true,
});
workbox.googleAnalytics.initialize();
workbox.core.skipWaiting();
@@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
+34 -23
View File
@@ -2,30 +2,37 @@
<html lang="en">
<head>
<title>workbox-navigation-preload demo</title>
<meta name="workbox-navigation-preload demo" content="An example to demonstrate the workbox-navigation-preload module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-navigation-preload demo"
content="An example to demonstrate the workbox-navigation-preload module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<div>
<h1>workbox-navigation-preload Demo</h1>
@@ -33,27 +40,31 @@
</header>
<ol>
<li>workbox-navigation-preload enables navigation preload in browsers that support it</li>
<li>
workbox-navigation-preload enables navigation preload in browsers that
support it
</li>
<li>Open the dev tools console and reload this page</li>
<li>There should be two requests for the HTML document: one initiated by the service worker, and one by Preload</li>
<li>
There should be two requests for the HTML document: one initiated by the
service worker, and one by Preload
</li>
</ol>
<script>
window.addEventListener('load', () => {
navigator.serviceWorker.register('./sw.js')
navigator.serviceWorker.register('./sw.js');
});
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
@@ -1,15 +1,15 @@
{
"name": "workbox-navigation-preload",
"version": "1.0.0",
"description": "Workbox Navigation Preload Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
"name": "workbox-navigation-preload",
"version": "1.0.0",
"description": "Workbox Navigation Preload Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
+3 -1
View File
@@ -1,4 +1,6 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
workbox.setConfig({
debug: true,
@@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
+59 -39
View File
@@ -2,73 +2,93 @@
<html lang="en">
<head>
<title>workbox-precaching demo</title>
<meta name="workbox-precaching demo" content="An example to demonstrate the workbox-precaching module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-precaching demo"
content="An example to demonstrate the workbox-precaching module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<header>
<div>
<h1>workbox-precaching Demo</h1>
</div>
</header>
<ol>
<li>Open DevTools</li>
<li>Go to the Console</li>
<li>Click this button:<br /><button class="install-sw-1">Install Service Worker</button></li>
<li>Checkout the logs for info on what was precached.</li>
<li>Explore Cache in the "Application" tab in DevTools. <i>Note: You may need to right-click and refresh.</i></li>
<li>Click this button:<br /><button class="install-sw-2">Install New Service Worker</button></li>
<li>Check logs, cache to highlight the new, updated and deleted entry.</li>
<li>Open DevTools</li>
<li>Go to the Console</li>
<li>
Click this button:<br /><button class="install-sw-1">
Install Service Worker
</button>
</li>
<li>Checkout the logs for info on what was precached.</li>
<li>
Explore Cache in the "Application" tab in DevTools.
<i>Note: You may need to right-click and refresh.</i>
</li>
<li>
Click this button:<br /><button class="install-sw-2">
Install New Service Worker
</button>
</li>
<li>
Check logs, cache to highlight the new, updated and deleted entry.
</li>
</ol>
<script>
const firstBtn = document.querySelector('.install-sw-1');
const secondBtn = document.querySelector('.install-sw-2');
const firstBtn = document.querySelector('.install-sw-1');
const secondBtn = document.querySelector('.install-sw-2');
firstBtn.addEventListener('click', () => {
navigator.serviceWorker.register('./sw-1.js');
});
secondBtn.addEventListener('click', () => {
navigator.serviceWorker.getRegistration()
.then((reg) => {
firstBtn.addEventListener('click', () => {
navigator.serviceWorker.register('./sw-1.js');
});
secondBtn.addEventListener('click', () => {
navigator.serviceWorker
.getRegistration()
.then((reg) => {
return reg.unregister();
})
.then(() => {
})
.then(() => {
navigator.serviceWorker.register('./sw-2.js');
});
});
});
});
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
+14 -14
View File
@@ -1,15 +1,15 @@
{
"name": "workbox-precaching",
"version": "1.0.0",
"description": "Workbox Precaching Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
"name": "workbox-precaching",
"version": "1.0.0",
"description": "Workbox Precaching Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
+3 -1
View File
@@ -1,4 +1,6 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
workbox.setConfig({
debug: true,
+3 -1
View File
@@ -1,4 +1,6 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
workbox.setConfig({
debug: true,
+2 -2
View File
@@ -34,12 +34,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
+50 -34
View File
@@ -2,31 +2,38 @@
<html lang="en">
<head>
<title>workbox-range-requests demo</title>
<meta name="workbox-range-requests demo" content="An example to demonstrate the workbox-range-requests module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-range-requests demo"
content="An example to demonstrate the workbox-range-requests module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<header>
<div>
<h1>workbox-range-requests Demo</h1>
</div>
@@ -35,41 +42,50 @@
<ol>
<li>Open DevTools</li>
<li>Go to the Console</li>
<li>Click this button to request range 1 - 4 of 'hello, world.':<br /><button class="make-range-request">Make Range Request</button></li>
<li>
Click this button to request range 1 - 4 of 'hello, world.':<br /><button
class="make-range-request"
>
Make Range Request
</button>
</li>
<li>Checkout the logs for info on the range request that was handled.</li>
</ol>
<script>
const makeRequestBtn = document.querySelector('.make-range-request');
caches.open('range-requests-demo')
.then((cache) => cache.put('/range-request-example', new Response('hello, world.')));
caches
.open('range-requests-demo')
.then((cache) =>
cache.put('/range-request-example', new Response('hello, world.')),
);
navigator.serviceWorker.register('./sw.js')
.then(() => {
navigator.serviceWorker.register('./sw.js').then(() => {
makeRequestBtn.addEventListener('click', () => {
fetch(new Request('/range-request-example', {
headers: {
Range: `bytes=1-4`,
}
}))
.then((response) => response.text())
.then((responseText) => {
console.log(`Received response: '${responseText}'`);
});
fetch(
new Request('/range-request-example', {
headers: {
Range: `bytes=1-4`,
},
}),
)
.then((response) => response.text())
.then((responseText) => {
console.log(`Received response: '${responseText}'`);
});
});
});
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
+14 -14
View File
@@ -1,15 +1,15 @@
{
"name": "workbox-range-requests",
"version": "1.0.0",
"description": "Workbox Range Requests Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
"name": "workbox-range-requests",
"version": "1.0.0",
"description": "Workbox Range Requests Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
+8 -8
View File
@@ -1,17 +1,17 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
workbox.setConfig({
debug: true,
});
workbox.routing.registerRoute(
new RegExp('/range-request-example'),
new workbox.strategies.CacheOnly({
cacheName: 'range-requests-demo',
plugins: [
new workbox.rangeRequests.RangeRequestsPlugin(),
],
}),
new RegExp('/range-request-example'),
new workbox.strategies.CacheOnly({
cacheName: 'range-requests-demo',
plugins: [new workbox.rangeRequests.RangeRequestsPlugin()],
}),
);
workbox.core.skipWaiting();
@@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
+45 -32
View File
@@ -2,65 +2,78 @@
<html lang="en">
<head>
<title>workbox-precaching demo</title>
<meta name="workbox-precaching demo" content="An example to demonstrate the workbox-precaching module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-precaching demo"
content="An example to demonstrate the workbox-precaching module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<header>
<div>
<h1>workbox-routing Demo</h1>
</div>
</header>
<ol>
<li>Open DevTools</li>
<li>Go to the Console</li>
<li>Click this button:<br /><button class="install-sw">Install Service Worker</button></li>
<li>
Click this button:<br /><button class="install-sw">
Install Service Worker
</button>
</li>
<li><strong>Refresh the page</strong></li>
<li>Notice that the image '/public/demo-img.png' was routed and is now a party popper</li>
<li>
Notice that the image '/public/demo-img.png' was routed and is now a
party popper
</li>
</ol>
<img src="demo-img.png" style="width: 300px; height: 300px;"/>
<img src="demo-img.png" style="width: 300px; height: 300px" />
<p>
<script>
const firstBtn = document.querySelector('.install-sw');
firstBtn.addEventListener('click', () => {
navigator.serviceWorker.register('./sw.js');
});
</script>
<script>
const firstBtn = document.querySelector('.install-sw');
firstBtn.addEventListener('click', () => {
navigator.serviceWorker.register('./sw.js');
});
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
</p>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
+14 -14
View File
@@ -1,15 +1,15 @@
{
"name": "workbox-routing",
"version": "1.0.0",
"description": "Workbox Routing Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
"name": "workbox-routing",
"version": "1.0.0",
"description": "Workbox Routing Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
+3 -1
View File
@@ -1,4 +1,6 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
workbox.setConfig({
debug: true,
+2 -2
View File
@@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
+87 -44
View File
@@ -2,31 +2,38 @@
<html lang="en">
<head>
<title>workbox-strategies demo</title>
<meta name="workbox-strategies demo" content="An example to demonstrate the workbox-strategies module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-strategies demo"
content="An example to demonstrate the workbox-strategies module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<header>
<div>
<h1>workbox-strategies Demo</h1>
</div>
@@ -35,74 +42,110 @@
<ol>
<li>Open DevTools</li>
<li>Go to the Console</li>
<li>Click any of the buttons below and view the logs:
<li>
Click any of the buttons below and view the logs:
<ul>
<li>
<p>This will attempt to get a request from an empty cache.</p>
<p><button class="cache-only-empty-cache">Cache Only Request (To Empty Cache)</button></p>
<p>
<button class="cache-only-empty-cache">
Cache Only Request (To Empty Cache)
</button>
</p>
</li>
<li>
<p>
<button class="cache-only-populated-cache">
Cache Only Request (To Populated Cache)
</button>
</p>
</li>
<li>
<p>
<button class="cache-first">
Cache First Request (Try it Several Times)
</button>
</p>
</li>
<li>
<p><button class="network-only">Network Only Request</button></p>
</li>
<li>
<p>
<button class="network-first-valid">
Network First Request (Valid URL)
</button>
</p>
</li>
<li>
<p>
<button class="network-first-failing">
Network First Request (Failing URL)
</button>
</p>
</li>
<li>
<p>
<button class="stale-while-revalidate">
Stale While Revalidate Request
</button>
</p>
</li>
<li><p><button class="cache-only-populated-cache">Cache Only Request (To Populated Cache)</button></p></li>
<li><p><button class="cache-first">Cache First Request (Try it Several Times)</button></p></li>
<li><p><button class="network-only">Network Only Request</button></p></li>
<li><p><button class="network-first-valid">Network First Request (Valid URL)</button></p></li>
<li><p><button class="network-first-failing">Network First Request (Failing URL)</button></p></li>
<li><p><button class="stale-while-revalidate">Stale While Revalidate Request</button></p></li>
</ul>
</li>
</ol>
<script>
const cacheOnlyEmpty = document.querySelector('.cache-only-empty-cache');
const cacheOnlyPopulated = document.querySelector('.cache-only-populated-cache');
const cacheOnlyPopulated = document.querySelector(
'.cache-only-populated-cache',
);
const cacheFirst = document.querySelector('.cache-first');
const networkOnly = document.querySelector('.network-only');
const networkFirstValid = document.querySelector('.network-first-valid');
const networkFirstFailing = document.querySelector('.network-first-failing');
const staleWhileRevalidate = document.querySelector('.stale-while-revalidate');
const networkFirstFailing = document.querySelector(
'.network-first-failing',
);
const staleWhileRevalidate = document.querySelector(
'.stale-while-revalidate',
);
window.addEventListener('load', () => {
navigator.serviceWorker.register('./sw.js')
.then(() => {
navigator.serviceWorker.register('./sw.js').then(() => {
cacheOnlyEmpty.addEventListener('click', () => {
fetch('cache-only-empty-cache.txt').catch(() => {});
});
cacheOnlyPopulated.addEventListener('click', () => {
fetch('cache-only-populated-cache')
.then((response) => {
fetch('cache-only-populated-cache').then((response) => {
return response.text();
});
});
cacheFirst.addEventListener('click', () => {
fetch('cache-first.txt')
.then((response) => {
fetch('cache-first.txt').then((response) => {
return response.text();
});
});
networkOnly.addEventListener('click', () => {
fetch('network-only.txt')
.then((response) => {
fetch('network-only.txt').then((response) => {
return response.text();
});
});
networkFirstValid.addEventListener('click', () => {
fetch('network-first.txt')
.then((response) => {
fetch('network-first.txt').then((response) => {
return response.text();
});
});
networkFirstFailing.addEventListener('click', () => {
fetch('network-first-404.txt')
.catch(() => {});
fetch('network-first-404.txt').catch(() => {});
});
staleWhileRevalidate.addEventListener('click', () => {
fetch('stale-while-revalidate.txt')
.then((response) => {
fetch('stale-while-revalidate.txt').then((response) => {
return response.text();
});
});
@@ -110,14 +153,14 @@
});
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
+10 -9
View File
@@ -1,4 +1,6 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
// To avoid async issues, we load strategies before we call it in the event listener
workbox.loadModule('workbox-strategies');
// Note: Ignore the error that Glitch raises about workbox being undefined.
@@ -41,7 +43,7 @@ self.addEventListener('fetch', (event) => {
}
case '/stale-while-revalidate.txt': {
const staleWhileRevalidate =
new workbox.strategies.StaleWhileRevalidate();
new workbox.strategies.StaleWhileRevalidate();
event.respondWith(staleWhileRevalidate.handle({event, request}));
break;
}
@@ -55,12 +57,11 @@ workbox.core.clientsClaim();
// Populate the cache to illustrate cache-only-populated-cache route
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(workbox.core.cacheNames.runtime)
.then((cache) => {
return cache.put(
new Request('/cache-only-populated-cache'),
new Response('Hello from the populated cache.'),
);
}),
caches.open(workbox.core.cacheNames.runtime).then((cache) => {
return cache.put(
new Request('/cache-only-populated-cache'),
new Response('Hello from the populated cache.'),
);
}),
);
});
+2 -2
View File
@@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
+32 -24
View File
@@ -2,31 +2,38 @@
<html lang="en">
<head>
<title>workbox-streams demo</title>
<meta name="workbox-streams demo" content="An example to demonstrate the workbox-streams module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-streams demo"
content="An example to demonstrate the workbox-streams module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<header>
<div>
<h1>workbox-workbox-streams Demo</h1>
</div>
@@ -36,15 +43,16 @@
<li>Open DevTools</li>
<li>Go to the Console</li>
<li>
Click this button to add an <code>iframe</code> to this page, whose
body is created from multiple streamed sources:<br/>
Click this button to add an <code>iframe</code> to this page, whose body
is created from multiple streamed sources:<br />
<button class="make-streams-request">Add iframe</button>
</li>
<li>Checkout the logs for info on how the streamed response was generated.</li>
<li>
Checkout the logs for info on how the streamed response was generated.
</li>
</ol>
<div id="iframes">
<div id="iframes"></div>
<script>
const makeRequestBtn = document.querySelector('.make-streams-request');
@@ -59,14 +67,14 @@
});
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
+1 -1
View File
@@ -12,4 +12,4 @@
"node": "8.x"
},
"license": "MIT"
}
}
+5 -5
View File
@@ -9,20 +9,20 @@ const app = express();
// but feel free to use whatever libs or frameworks you'd like through `package.json`.
// http://expressjs.com/en/starter/basic-routing.html
app.get('/', function(request, response) {
app.get('/', function (request, response) {
response.sendFile(__dirname + '/index.html');
});
app.get('/sw.js', function(request, response) {
app.get('/sw.js', function (request, response) {
response.sendFile(__dirname + '/sw.js');
});
// listen for requests :)
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
app.get('/api/date', function(req, res) {
app.get('/api/date', function (req, res) {
res.header('Content-Type', 'text/plain');
res.header('Cache-Control', 'no-cache');
res.send(`Received from the server at ${new Date().toLocaleString()}`);
@@ -46,7 +46,7 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
+18 -16
View File
@@ -1,4 +1,6 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
workbox.setConfig({
debug: true,
@@ -9,13 +11,15 @@ const START_CACHE_KEY = 'start';
const END_CACHE_KEY = 'end';
self.addEventListener('install', (event) => {
event.waitUntil((async () => {
const cache = await caches.open(CACHE_NAME);
await Promise.all([
cache.put(START_CACHE_KEY, new Response('<html><head></head><body>')),
cache.put(END_CACHE_KEY, new Response('</body></html>')),
]);
})());
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE_NAME);
await Promise.all([
cache.put(START_CACHE_KEY, new Response('<html><head></head><body>')),
cache.put(END_CACHE_KEY, new Response('</body></html>')),
]);
})(),
);
});
// Use a stale-while-revalidate strategy as a source for part of the response.
@@ -28,18 +32,16 @@ const streamsStrategy = workbox.streams.strategy([
() => caches.match(START_CACHE_KEY, {cacheName: CACHE_NAME}),
() => `<p>🎉 This <code>iframe</code> is composed of multiple streams.</p>`,
() => `<p>Here's an API call, using a stale-while-revalidate strategy:</p>`,
({event}) => apiStrategy.handle({
event: event,
request: new Request('/api/date'),
}),
({event}) =>
apiStrategy.handle({
event: event,
request: new Request('/api/date'),
}),
() => caches.match(END_CACHE_KEY, {cacheName: CACHE_NAME}),
]);
// Once the strategy is configured, the actual routing looks clean.
workbox.routing.registerRoute(
new RegExp('iframe$'),
streamsStrategy,
);
workbox.routing.registerRoute(new RegExp('iframe$'), streamsStrategy);
workbox.core.skipWaiting();
workbox.core.clientsClaim();
+46 -31
View File
@@ -2,30 +2,37 @@
<html lang="en">
<head>
<title>workbox-sw demo</title>
<meta name="workbox-sw demo" content="An example to demonstrate the workbox-sw module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-sw demo"
content="An example to demonstrate the workbox-sw module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
}
ol {
padding-left: 20px
}
li {
margin-bottom: 5px
}
button {
margin: 20px 0;
font-weight: bold
}
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px;
}
li {
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold;
}
</style>
</head>
<body>
<header>
<div>
<h1>workbox-sw demo</h1>
@@ -34,14 +41,21 @@
<ol>
<li>Open DevTools and go to the console</li>
<li>Click this button:<br /><button class="install-sw">Install Service Worker</button></li>
<li>
Click this button:<br /><button class="install-sw">
Install Service Worker
</button>
</li>
<li>You should see a workbox message appear</li>
<li>Refresh the page, go to the network tab, and check the "Size" of demo-img.png. It should read (ServiceWorker)</li>
<li>
Refresh the page, go to the network tab, and check the "Size" of
demo-img.png. It should read (ServiceWorker)
</li>
</ol>
<!-- Image will be stored in a custom cache -->
<img src="demo-img.png" style="width: 300px; height: 300px;"/>
<img src="demo-img.png" style="width: 300px; height: 300px" />
<script>
const installSWBtn = document.querySelector('.install-sw');
installSWBtn.addEventListener('click', () => {
@@ -50,14 +64,15 @@
</script>
<p>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
</p>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
+14 -14
View File
@@ -1,15 +1,15 @@
{
"name": "workbox-sw",
"version": "1.0.0",
"description": "Workbox SW Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
"name": "workbox-sw",
"version": "1.0.0",
"description": "Workbox SW Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
+14 -12
View File
@@ -1,4 +1,6 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
// Note: Ignore the error that Glitch raises about workbox being undefined.
workbox.setConfig({
@@ -11,19 +13,19 @@ workbox.precaching.precacheAndRoute([
// Demonstrates using default cache
workbox.routing.registerRoute(
new RegExp('.*\\.(?:js)'),
new workbox.strategies.NetworkFirst(),
new RegExp('.*\\.(?:js)'),
new workbox.strategies.NetworkFirst(),
);
// Demonstrates a custom cache name for a route.
workbox.routing.registerRoute(
new RegExp('.*\\.(?:png|jpg|jpeg|svg|gif)'),
new workbox.strategies.CacheFirst({
cacheName: 'image-cache',
plugins: [
new workbox.expiration.ExpirationPlugin({
maxEntries: 3,
}),
],
}),
new RegExp('.*\\.(?:png|jpg|jpeg|svg|gif)'),
new workbox.strategies.CacheFirst({
cacheName: 'image-cache',
plugins: [
new workbox.expiration.ExpirationPlugin({
maxEntries: 3,
}),
],
}),
);
+2 -2
View File
@@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
+34 -29
View File
@@ -2,30 +2,37 @@
<html lang="en">
<head>
<title>workbox-window demo</title>
<meta name="workbox-window demo" content="An example to demonstrate the workbox-window module">
<link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta
name="workbox-window demo"
content="An example to demonstrate the workbox-window module"
/>
<link
id="favicon"
rel="icon"
href="https://glitch.com/edit/favicon-app.ico"
type="image/x-icon"
/>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin-left: 5%;
font-family: 'Open Sans', sans-serif
font-family: 'Open Sans', sans-serif;
}
ol {
padding-left: 20px
padding-left: 20px;
}
li {
margin-bottom: 5px
margin-bottom: 5px;
}
button {
margin: 20px 0;
font-weight: bold
font-weight: bold;
}
</style>
</head>
<body>
<header>
<div>
<h1>workbox-window Demo</h1>
@@ -37,12 +44,10 @@
<li>Open up DevTools and go to the console</li>
</ol>
<script type="module">
import {Workbox} from 'https://storage.googleapis.com/workbox-cdn/releases/5.0.0-beta.1/workbox-window.prod.mjs';
if ('serviceWorker' in navigator) {
if ('serviceWorker' in navigator) {
const wb = new Workbox('/sw.js');
wb.addEventListener('activated', (event) => {
@@ -55,34 +60,34 @@
// assets should all be available now.
}
});
wb.addEventListener('waiting', (event) => {
console.log(`A new service worker has installed, but it can't activate` +
`until all tabs running the current version have fully unloaded.`);
console.log(
`A new service worker has installed, but it can't activate` +
`until all tabs running the current version have fully unloaded.`,
);
});
// Register the service worker after event listeners have been added.
wb.register();
const message = async () => {
const swVersion = await wb.messageSW({type: 'GET_VERSION'});
console.log('Service Worker version:', swVersion);
}
};
message();
}
</script>
<a href="https://developers.google.com/web/tools/workbox/modules">Back to Demos</a>
<a href="https://developers.google.com/web/tools/workbox/modules"
>Back to Demos</a
>
<p>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
<a href="https://developers.google.com/web/tools/workbox">Docs</a> |
<a href="https://github.com/googlechrome/workbox">GitHub</a> |
<a href="https://twitter.com/workboxjs">@workboxjs</a>
</p>
</body>
</html>
</html>
+14 -14
View File
@@ -1,15 +1,15 @@
{
"name": "workbox-window",
"version": "1.0.0",
"description": "Workbox Window Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
"name": "workbox-window",
"version": "1.0.0",
"description": "Workbox Window Demo Git Listener",
"scripts": {
"start": "node updateServer.js"
},
"dependencies": {
"express": "^4.17.1"
},
"engines": {
"node": "8.x"
},
"license": "MIT"
}
+3 -1
View File
@@ -1,4 +1,6 @@
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js',
);
workbox.setConfig({
debug: true,
+2 -2
View File
@@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => {
const repoUrl = request.query.repo;
execSync(
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`git checkout -- ./ && git pull -X theirs ${repoUrl} ` +
`glitch && refresh && git branch -D glitch`,
);
response.status(200).send();
});
const listener = app.listen(process.env.PORT, function() {
const listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
+26 -23
View File
@@ -17,27 +17,27 @@ const packageRunner = require('./utils/package-runner');
async function buildNodePackage(packagePath) {
const outputDirectory = upath.join(
packagePath,
constants.PACKAGE_BUILD_DIRNAME,
packagePath,
constants.PACKAGE_BUILD_DIRNAME,
);
const configFile = upath.join(
__dirname,
'utils',
'node-projects-babel.config.json',
__dirname,
'utils',
'node-projects-babel.config.json',
);
await execa(
'babel',
[
'--config-file',
configFile,
`${packagePath}/src`,
'--out-dir',
outputDirectory,
'--copy-files',
],
{preferLocal: true},
'babel',
[
'--config-file',
configFile,
`${packagePath}/src`,
'--out-dir',
outputDirectory,
'--copy-files',
],
{preferLocal: true},
);
}
@@ -49,7 +49,7 @@ async function generateWorkboxBuildJSONSchema(packagePath) {
}
const program = TJS.programFromConfig(
upath.join(packagePath, 'tsconfig.json'),
upath.join(packagePath, 'tsconfig.json'),
);
const generator = TJS.buildGenerator(program, {
noExtraProps: true,
@@ -93,26 +93,29 @@ async function generateWorkboxBuildJSONSchema(packagePath) {
// See https://github.com/GoogleChrome/workbox/issues/2901
if (schema.definitions.WorkboxPlugin) {
for (const plugin of Object.keys(
schema.definitions.WorkboxPlugin.properties,
schema.definitions.WorkboxPlugin.properties,
)) {
schema.definitions.WorkboxPlugin.properties[plugin] = {};
}
}
await fse.writeJSON(
upath.join(packagePath, 'src', 'schema', `${optionType}.json`),
schema,
{spaces: 2},
upath.join(packagePath, 'src', 'schema', `${optionType}.json`),
schema,
{spaces: 2},
);
}
}
module.exports = {
build_node_packages: parallel(
packageRunner('build_node_packages', 'node', buildNodePackage),
packageRunner('build_node_packages', 'node', buildNodePackage),
),
build_node_ts_packages: parallel(
packageRunner('build_node_ts_packages', 'node_ts',
generateWorkboxBuildJSONSchema),
packageRunner(
'build_node_ts_packages',
'node_ts',
generateWorkboxBuildJSONSchema,
),
),
};
+10 -12
View File
@@ -11,8 +11,10 @@ const del = require('del');
const fse = require('fs-extra');
const upath = require('upath');
const {build_node_packages, build_node_ts_packages} =
require('./build-node-packages');
const {
build_node_packages,
build_node_ts_packages,
} = require('./build-node-packages');
const {build_sw_packages} = require('./build-sw-packages');
const {build_window_packages} = require('./build-window-packages');
const {transpile_typescript} = require('./transpile-typescript');
@@ -52,20 +54,16 @@ async function cleanPackage(packagePath) {
// Wrap this in a function since it's used multiple times.
function cleanSequence() {
return parallel(packageRunner('build_packages_clean', 'all',
cleanPackage));
return parallel(packageRunner('build_packages_clean', 'all', cleanPackage));
}
module.exports = {
build_packages_clean: cleanSequence(),
build_packages: series(
// This needs to be a series, not in parallel, so that there isn't a
// race condition with the terser nameCache.
transpile_typescript,
series(build_sw_packages, build_window_packages),
parallel(
build_node_packages,
build_node_ts_packages,
),
// This needs to be a series, not in parallel, so that there isn't a
// race condition with the terser nameCache.
transpile_typescript,
series(build_sw_packages, build_window_packages),
parallel(build_node_packages, build_node_ts_packages),
),
};
+27 -17
View File
@@ -62,10 +62,9 @@ function globals(moduleId) {
// on the global scope (i.e. workbox.<browserNamespace>)
try {
const pkg = require(upath.join(packagePath, 'package.json'));
return [
pkg.workbox.browserNamespace,
additionalNamespace,
].filter((value) => (value && value.length > 0)).join('.');
return [pkg.workbox.browserNamespace, additionalNamespace]
.filter((value) => value && value.length > 0)
.join('.');
} catch (err) {
logHelper.error(`Unable to get browserNamespace for '${packageName}'`);
throw err;
@@ -75,7 +74,7 @@ function globals(moduleId) {
// This ensures all workbox-* modules are treated as external and are
// referenced as globals.
function externalAndPure(importPath) {
return (importPath.indexOf('workbox-') === 0);
return importPath.indexOf('workbox-') === 0;
}
async function buildSWBundle(packagePath, buildType) {
@@ -108,8 +107,10 @@ async function buildSWBundle(packagePath, buildType) {
outputFilename += '.js';
const namespace = pkgJson.workbox.browserNamespace;
const outputDirectory = upath.join(packagePath,
constants.PACKAGE_BUILD_DIRNAME);
const outputDirectory = upath.join(
packagePath,
constants.PACKAGE_BUILD_DIRNAME,
);
const plugins = rollupHelper.getDefaultPlugins(buildType);
@@ -121,8 +122,10 @@ async function buildSWBundle(packagePath, buildType) {
},
plugins,
onwarn: (warning) => {
if (buildType === constants.BUILD_TYPES.prod &&
warning.code === 'UNUSED_EXTERNAL_IMPORT') {
if (
buildType === constants.BUILD_TYPES.prod &&
warning.code === 'UNUSED_EXTERNAL_IMPORT'
) {
// This can occur when using rollup-plugin-replace.
logHelper.warn(`[${warning.code}] ${warning.message}`);
return;
@@ -130,8 +133,9 @@ async function buildSWBundle(packagePath, buildType) {
// The final builds should have no warnings.
if (warning.code && warning.message) {
throw new Error(`Unhandled Rollup Warning: [${warning.code}] ` +
`${warning.message}`);
throw new Error(
`Unhandled Rollup Warning: [${warning.code}] ` + `${warning.message}`,
);
} else {
throw new Error(`Unhandled Rollup Warning: ${warning}`);
}
@@ -150,17 +154,23 @@ async function buildSWBundle(packagePath, buildType) {
// This reads a little cleaner with a function to generate the sub-sequences.
function swBundleSequence() {
const builds = Object.keys(constants.BUILD_TYPES).map((type) => packageRunner(
'build_sw_packages_bundle', 'sw', buildSWBundle,
constants.BUILD_TYPES[type]));
const builds = Object.keys(constants.BUILD_TYPES).map((type) =>
packageRunner(
'build_sw_packages_bundle',
'sw',
buildSWBundle,
constants.BUILD_TYPES[type],
),
);
return series(builds);
}
module.exports = {
build_sw_packages: series(
parallel(packageRunner('build_sw_packages_version_module', 'sw',
versionModule)),
swBundleSequence(),
parallel(
packageRunner('build_sw_packages_version_module', 'sw', versionModule),
),
swBundleSequence(),
),
};
+24 -10
View File
@@ -27,8 +27,10 @@ async function buildWindowBundle(packagePath, buildType) {
throw new Error(`Could not find ${packageIndex}`);
}
const outputDirectory = upath.join(packagePath,
constants.PACKAGE_BUILD_DIRNAME);
const outputDirectory = upath.join(
packagePath,
constants.PACKAGE_BUILD_DIRNAME,
);
const esmFilename = `${packageName}.${buildType.slice(0, 4)}.mjs`;
const esmLegacyFilename = `${packageName}.${buildType.slice(0, 4)}.es5.mjs`;
@@ -36,8 +38,10 @@ async function buildWindowBundle(packagePath, buildType) {
const onwarn = (warning) => {
// This can occur when using rollup-plugin-replace.
if (buildType === constants.BUILD_TYPES.prod &&
warning.code === 'UNUSED_EXTERNAL_IMPORT') {
if (
buildType === constants.BUILD_TYPES.prod &&
warning.code === 'UNUSED_EXTERNAL_IMPORT'
) {
logHelper.warn(`[${warning.code}] ${warning.message}`);
return;
}
@@ -92,17 +96,27 @@ async function buildWindowBundle(packagePath, buildType) {
// This reads a little cleaner with a function to generate the sub-sequences.
function windowBundleSequence() {
const builds = Object.keys(constants.BUILD_TYPES).map((type) => packageRunner(
'build_window_packages_bundle', 'window', buildWindowBundle,
constants.BUILD_TYPES[type]));
const builds = Object.keys(constants.BUILD_TYPES).map((type) =>
packageRunner(
'build_window_packages_bundle',
'window',
buildWindowBundle,
constants.BUILD_TYPES[type],
),
);
return series(builds);
}
module.exports = {
build_window_packages: series(
parallel(packageRunner('build_window_packages_version_module', 'window',
versionModule)),
windowBundleSequence(),
parallel(
packageRunner(
'build_window_packages_version_module',
'window',
versionModule,
),
),
windowBundleSequence(),
),
};
+18 -10
View File
@@ -17,18 +17,26 @@ const {build_packages} = require('./build-packages');
// to add CDN details to workbox-sw.
// Make sure this runs **before** build_lerna_bootstrap.
async function build_update_cdn_details() {
const cdnDetails = await fse.readJSON(upath.join(
__dirname, '..', 'cdn-details.json',
));
const cdnDetails = await fse.readJSON(
upath.join(__dirname, '..', 'cdn-details.json'),
);
const workboxBuildPath = upath.join(
__dirname, '..', 'packages', 'workbox-build');
__dirname,
'..',
'packages',
'workbox-build',
);
const workboxBuildCdnDetailsPath = upath.join(
workboxBuildPath, 'src', 'cdn-details.json');
workboxBuildPath,
'src',
'cdn-details.json',
);
const workboxBuildPkg = await fse.readJSON(upath.join(
workboxBuildPath, 'package.json'));
const workboxBuildPkg = await fse.readJSON(
upath.join(workboxBuildPath, 'package.json'),
);
cdnDetails.latestVersion = workboxBuildPkg.version;
@@ -43,8 +51,8 @@ async function build_lerna_bootstrap() {
module.exports = {
build: series(
build_update_cdn_details,
build_lerna_bootstrap,
build_packages,
build_update_cdn_details,
build_lerna_bootstrap,
build_packages,
),
};
+15 -6
View File
@@ -25,8 +25,10 @@ async function docs_build() {
].join('&');
const params = [
'-c', upath.join(__dirname, '..', 'jsdoc.conf'),
'-d', DOCS_DIRECTORY,
'-c',
upath.join(__dirname, '..', 'jsdoc.conf'),
'-d',
DOCS_DIRECTORY,
];
if (!(global.cliOptions && global.cliOptions.pretty)) {
@@ -40,10 +42,17 @@ You can view a friendlier UI by running
'gulp docs --pretty'
`);
params.push(
'--template', upath.join(
__dirname, '..', 'infra', 'templates', 'reference-docs', 'jsdoc',
),
'--query', queryString,
'--template',
upath.join(
__dirname,
'..',
'infra',
'templates',
'reference-docs',
'jsdoc',
),
'--query',
queryString,
);
}
+22 -10
View File
@@ -10,19 +10,31 @@ const {parallel} = require('gulp');
const execa = require('execa');
async function lint_js() {
await execa('eslint', [
'**/*.{js,mjs}',
'--config', 'javascript.eslintrc.js',
'--ignore-path', '.gitignore',
], {preferLocal: true});
await execa(
'eslint',
[
'**/*.{js,mjs}',
'--config',
'javascript.eslintrc.js',
'--ignore-path',
'.gitignore',
],
{preferLocal: true},
);
}
async function lint_ts() {
await execa('eslint', [
'**/*.ts',
'--config', 'typescript.eslintrc.js',
'--ignore-path', '.gitignore',
], {preferLocal: true});
await execa(
'eslint',
[
'**/*.ts',
'--config',
'typescript.eslintrc.js',
'--ignore-path',
'.gitignore',
],
{preferLocal: true},
);
}
module.exports = {
+6 -4
View File
@@ -47,8 +47,7 @@ async function publish_github() {
// Get all of the tags in the repo.
const allTags = await githubHelper.getTags();
const taggedReleases = await githubHelper.getTaggedReleases();
const tagsToBuild = filterTagsWithReleaseBundles(allTags,
taggedReleases);
const tagsToBuild = filterTagsWithReleaseBundles(allTags, taggedReleases);
if (tagsToBuild.length === 0) {
logHelper.log(`No tags missing from GitHub.`);
@@ -56,8 +55,11 @@ async function publish_github() {
}
for (const tagToBuild of tagsToBuild) {
await handleGithubRelease(tagToBuild.name, tagToBuild.name,
taggedReleases[tagToBuild.name]);
await handleGithubRelease(
tagToBuild.name,
tagToBuild.name,
taggedReleases[tagToBuild.name],
);
}
}
+9 -3
View File
@@ -48,12 +48,18 @@ async function publish_glitch() {
await execa('git', ['commit', `-m'Autocommit on ${new Date()}'`], {
cwd: projectPath,
});
await execa('git', ['push', 'origin', 'glitch', '-f', '--set-upstream',
'--no-verify'], {cwd: projectPath});
await execa(
'git',
['push', 'origin', 'glitch', '-f', '--set-upstream', '--no-verify'],
{cwd: projectPath},
);
const deployURL = new URL(`https://${project}.glitch.me/deploy`);
deployURL.searchParams.set('secret', process.env.GLITCH_WORKBOX_SECRET);
deployURL.searchParams.set('repo', `https://api.glitch.com/git/${project}`);
deployURL.searchParams.set(
'repo',
`https://api.glitch.com/git/${project}`,
);
await execa('curl', ['-X', 'POST', deployURL.href]);
} catch (error) {
logHelper.error(`'${error}' occurred while processing ${project}.`);
+5 -2
View File
@@ -17,8 +17,11 @@ async function publish_lerna() {
// gulp publish --distTag=latest would be the most common.
if (global.cliOptions.distTag) {
logHelper.log(ol`Using ${logHelper.highlight(
'--dist-tag=' + global.cliOptions.distTag)}`);
logHelper.log(
ol`Using ${logHelper.highlight(
'--dist-tag=' + global.cliOptions.distTag,
)}`,
);
options.push('--dist-tag', global.cliOptions.distTag);
} else {
throw new Error(ol`Please set the --distTag command line option, normally
+10 -2
View File
@@ -34,6 +34,14 @@ async function dist_tag_check() {
}
module.exports = {
publish: series(dist_tag_check, publish_sign_in_check, build_packages_clean,
publish_clean, test, publish_lerna, publish_github, publish_cdn),
publish: series(
dist_tag_check,
publish_sign_in_check,
build_packages_clean,
publish_clean,
test,
publish_lerna,
publish_github,
publish_cdn,
),
};
+8 -6
View File
@@ -25,7 +25,7 @@ function runFiles(filePaths) {
return new Promise((resolve, reject) => {
const mocha = new Mocha({
retries: (process.env.TRAVIS || process.env.GITHUB_ACTIONS) ? 4 : 1,
retries: process.env.TRAVIS || process.env.GITHUB_ACTIONS ? 4 : 1,
timeout: 3 * 60 * 1000,
});
@@ -34,7 +34,7 @@ function runFiles(filePaths) {
}
// Run the tests.
mocha.run(function(failureCount) {
mocha.run(function (failureCount) {
if (failureCount > 0) {
return reject(new Error(`${failureCount} tests failed.`));
}
@@ -63,8 +63,9 @@ async function runTestSuite(testPath, nodeEnv, seleniumBrowser, webdriver) {
webdriver,
};
const testFiles = glob.sync(upath.join(__dirname, '..', testPath,
'test-*.js'));
const testFiles = glob.sync(
upath.join(__dirname, '..', testPath, 'test-*.js'),
);
await runFiles(testFiles);
} finally {
@@ -106,8 +107,9 @@ async function test_integration() {
// Install the latest Chrome and Firefox webdrivers without referencing
// package-lock.json, to ensure that they're up to date.
await execa('npm', ['install', '--no-save', 'chromedriver', 'geckodriver'],
{preferLocal: true});
await execa('npm', ['install', '--no-save', 'chromedriver', 'geckodriver'], {
preferLocal: true,
});
logHelper.log(`Downloading browsers...`);
const expiration = 24;
+28 -22
View File
@@ -28,14 +28,20 @@ async function runNodeTestSuite(testPath, nodeEnv) {
process.env.NODE_ENV = nodeEnv;
try {
const {stdout} = await execa('nyc', [
'--clean', 'false',
'--silent',
'mocha',
'--timeout', '60000',
`${testPath}/**/*.{js,mjs}`,
...options,
], {preferLocal: true});
const {stdout} = await execa(
'nyc',
[
'--clean',
'false',
'--silent',
'mocha',
'--timeout',
'60000',
`${testPath}/**/*.{js,mjs}`,
...options,
],
{preferLocal: true},
);
console.log(stdout);
} finally {
@@ -45,9 +51,7 @@ async function runNodeTestSuite(testPath, nodeEnv) {
async function runNodeTestsWithEnv(testGroup, nodeEnv) {
const globConfig = {
ignore: [
'**/all/**',
],
ignore: ['**/all/**'],
};
if (testGroup === 'all') {
@@ -87,17 +91,14 @@ async function test_node_coverage() {
const runOptions = [];
if (global.packageOrStar !== '*') {
runOptions.push('--include');
runOptions.push(
upath.join('packages', global.packageOrStar, '**', '*'),
);
runOptions.push(upath.join('packages', global.packageOrStar, '**', '*'));
}
const {stdout} = await execa('nyc', [
'report',
'--reporter', 'lcov',
'--reporter', 'text',
...runOptions,
], {preferLocal: true});
const {stdout} = await execa(
'nyc',
['report', '--reporter', 'lcov', '--reporter', 'text', ...runOptions],
{preferLocal: true},
);
console.log(stdout);
}
@@ -107,6 +108,11 @@ module.exports = {
test_node_coverage,
test_node_dev,
test_node_prod,
test_node: series(test_node_clean, test_node_dev, test_node_prod,
test_node_all, test_node_coverage),
test_node: series(
test_node_clean,
test_node_dev,
test_node_prod,
test_node_all,
test_node_coverage,
),
};
+9 -4
View File
@@ -8,8 +8,10 @@
const {series} = require('gulp');
const {transpile_typescript, transpile_typescript_watch} =
require('./transpile-typescript');
const {
transpile_typescript,
transpile_typescript_watch,
} = require('./transpile-typescript');
const constants = require('./utils/constants');
const testServer = require('../infra/testing/server/index');
@@ -36,6 +38,9 @@ function startServer() {
}
module.exports = {
test_server: series(transpile_typescript, startServer,
transpile_typescript_watch),
test_server: series(
transpile_typescript,
startServer,
transpile_typescript_watch,
),
};
+1 -4
View File
@@ -72,10 +72,7 @@ async function transpile_typescript() {
await execa('tsc', ['--build', 'tsconfig.json'], {preferLocal: true});
const jsFiles = await globby(`packages/*/**/*.js`, {
ignore: [
'**/build/**',
'**/src/**',
],
ignore: ['**/build/**', '**/src/**'],
});
for (const jsFile of jsFiles) {
+40 -29
View File
@@ -30,21 +30,30 @@ const logHelper = require('../../infra/utils/log-helper');
class AnalyseBuildForProperties {
run() {
const filePaths = this.getBuildFiles();
return Promise.all(filePaths.map((filePath) => {
const rawAnalysis = this.analyzeFile(filePath);
const analysis = this.tidyData(rawAnalysis);
return Promise.all(
filePaths.map((filePath) => {
const rawAnalysis = this.analyzeFile(filePath);
const analysis = this.tidyData(rawAnalysis);
return {
filePath,
analysis,
};
}));
return {
filePath,
analysis,
};
}),
);
}
getBuildFiles() {
// workbox-sw doesn't include .prod. in the build name.
const buildGlob = path.join(__dirname, '..', '..', 'packages',
'*', constants.PACKAGE_BUILD_DIRNAME, '{*.prod.js,workbox-sw.js}');
const buildGlob = path.join(
__dirname,
'..',
'..',
'packages',
'*',
constants.PACKAGE_BUILD_DIRNAME,
'{*.prod.js,workbox-sw.js}',
);
return glob.sync(buildGlob);
}
@@ -76,23 +85,24 @@ class AnalyseBuildForProperties {
}
tidyData(analysisEntries) {
return analysisEntries.filter((entry) => {
// If there is only one entry or it's a single character it's
// either not important or it's already been minified.
return entry.propertyCount > 1 && entry.propertyName.length > 1;
})
.filter((entry) => {
switch (entry.propertyName) {
case 'await':
case 'async':
return false;
default:
return true;
}
})
.sort((a, b) => {
return b.propertyCount - a.propertyCount;
});
return analysisEntries
.filter((entry) => {
// If there is only one entry or it's a single character it's
// either not important or it's already been minified.
return entry.propertyCount > 1 && entry.propertyName.length > 1;
})
.filter((entry) => {
switch (entry.propertyName) {
case 'await':
case 'async':
return false;
default:
return true;
}
})
.sort((a, b) => {
return b.propertyCount - a.propertyCount;
});
}
printDetails({filePath, analysis}) {
@@ -110,8 +120,9 @@ class AnalyseBuildForProperties {
analysis.forEach((entry) => {
const numberOfSpaces = longestPropertyName - entry.propertyName.length;
const extraSpace = ' '.repeat(numberOfSpaces);
logHelper.log(` ${entry.propertyName} ` +
`${extraSpace} ${entry.propertyCount}`);
logHelper.log(
` ${entry.propertyName} ` + `${extraSpace} ${entry.propertyCount}`,
);
});
logHelper.log();
}
+4 -3
View File
@@ -64,8 +64,9 @@ class CDNHelper {
const bucket = gcs.bucket(cdnDetails.bucketName);
for (const filePath of filePaths) {
const destination =
`${this._getReleaseTagPath(tagName)}/${path.basename(filePath)}`;
const destination = `${this._getReleaseTagPath(tagName)}/${path.basename(
filePath,
)}`;
try {
await bucket.upload(filePath, {
@@ -82,7 +83,7 @@ class CDNHelper {
throw err;
}
publicUrls.push(
`${cdnDetails.origin}/${cdnDetails.bucketName}/${destination}`,
`${cdnDetails.origin}/${cdnDetails.bucketName}/${destination}`,
);
}
+8 -6
View File
@@ -14,12 +14,14 @@ const DEFAULT_ROOT = path.join(__dirname, '..', '..');
const getPackages = ({type, root = DEFAULT_ROOT} = {}) => {
const pathToPkgJsons = glob.sync('packages/*/package.json', {cwd: root});
return pathToPkgJsons.map((pathToPkgJson) => {
const pkg = require(`${path.resolve(root)}/${pathToPkgJson}`);
return pkg;
}).filter((pkg) => {
return pkg.workbox && pkg.workbox.packageType === type;
});
return pathToPkgJsons
.map((pathToPkgJson) => {
const pkg = require(`${path.resolve(root)}/${pathToPkgJson}`);
return pkg;
})
.filter((pkg) => {
return pkg.workbox && pkg.workbox.packageType === type;
});
};
module.exports = {
+4 -2
View File
@@ -18,8 +18,10 @@ const github = new GitHubApi();
// See https://github.com/mikedeboer/node-github#authentication
const authenticate = () => {
if (!process.env.GITHUB_TOKEN) {
throw new Error('You must set a GITHUB_TOKEN in your environment to ' +
'publish a GitHub release.');
throw new Error(
'You must set a GITHUB_TOKEN in your environment to ' +
'publish a GitHub release.',
);
}
github.authenticate({
@@ -1,5 +1,3 @@
{
"presets": [
["@babel/preset-env", {"targets": {"node": "10.0"}}]
]
"presets": [["@babel/preset-env", {"targets": {"node": "10.0"}}]]
}
@@ -8,10 +8,8 @@
const {getPackages} = require('./get-packages');
const outputFilenameToPkgMap = {};
const windowAndSWPackages = [
...getPackages({type: 'sw'}),
...getPackages({type: 'window'}),
+12 -12
View File
@@ -18,20 +18,20 @@ const pkgPathToName = require('./pkg-path-to-name');
* @return Array<string> Paths to package.json files for the matching packages.
*/
function getPackages(typeFilter) {
return glob.sync(
`packages/${global.packageOrStar}/package.json`, {
absolute: true,
},
).filter((pathToPackageJson) => {
const pkgInfo = require(pathToPackageJson);
const packageType = pkgInfo.workbox.packageType;
if (!packageType) {
throw Error(oneLine`Unable to determine package type. Please add
return glob
.sync(`packages/${global.packageOrStar}/package.json`, {
absolute: true,
})
.filter((pathToPackageJson) => {
const pkgInfo = require(pathToPackageJson);
const packageType = pkgInfo.workbox.packageType;
if (!packageType) {
throw Error(oneLine`Unable to determine package type. Please add
workbox.packageType metadata to ${pathToPackageJson}`);
}
}
return typeFilter === 'all' || typeFilter === packageType;
});
return typeFilter === 'all' || typeFilter === packageType;
});
}
/*
+26 -12
View File
@@ -31,7 +31,11 @@ const doesDirectoryExist = async (directoryPath) => {
const getBuildPath = (tagName) => {
const tempReleasePath = upath.join(
__dirname, '..', '..', constants.GENERATED_RELEASE_FILES_DIRNAME);
__dirname,
'..',
'..',
constants.GENERATED_RELEASE_FILES_DIRNAME,
);
return upath.join(tempReleasePath, tagName);
};
@@ -54,8 +58,10 @@ const downloadGitCommit = async (tagName, gitBranch) => {
await execa('git', [
'clone',
'--branch', gitBranch,
'--depth', '1',
'--branch',
gitBranch,
'--depth',
'1',
`http://github.com/${constants.GITHUB_OWNER}/${constants.GITHUB_REPO}.git`,
sourceCodePath,
]);
@@ -89,8 +95,10 @@ const buildGitCommit = async (tagName) => {
* the folder structure will be the same.
*/
const groupBuildFiles = async (tagName, gitBranch) => {
const groupedBuildFiles = upath.join(getBuildPath(tagName),
GROUPED_BUILD_FILES);
const groupedBuildFiles = upath.join(
getBuildPath(tagName),
GROUPED_BUILD_FILES,
);
const dirExists = await doesDirectoryExist(groupedBuildFiles);
if (!dirExists) {
@@ -99,12 +107,17 @@ const groupBuildFiles = async (tagName, gitBranch) => {
const sourceCodePath = upath.join(getBuildPath(tagName), SOURCE_CODE_DIR);
const browserPackages = Object.values(outputFilenameToPkgMap)
.map((item) => item.name);
const browserPackages = Object.values(outputFilenameToPkgMap).map(
(item) => item.name,
);
const pattern = upath.join(sourceCodePath, 'packages',
`{${browserPackages.join(',')}}`, constants.PACKAGE_BUILD_DIRNAME,
'*.{js,mjs,map}');
const pattern = upath.join(
sourceCodePath,
'packages',
`{${browserPackages.join(',')}}`,
constants.PACKAGE_BUILD_DIRNAME,
'*.{js,mjs,map}',
);
logHelper.log(ol`
Grouping Build Files into
@@ -115,8 +128,9 @@ const groupBuildFiles = async (tagName, gitBranch) => {
// directory. In others, have a flat file structure of just the built files.
const filesToInclude = glob.sync(pattern);
for (const fileToInclude of filesToInclude) {
await fse.copy(fileToInclude, upath.join(groupedBuildFiles,
upath.basename(fileToInclude)),
await fse.copy(
fileToInclude,
upath.join(groupedBuildFiles, upath.basename(fileToInclude)),
);
}
} else {
+20 -15
View File
@@ -27,19 +27,24 @@ module.exports = {
const babelConfig = {
babelHelpers: 'bundled',
presets: [['@babel/preset-env', {
loose: true,
targets: {
browsers: es5 ?
// If es5 is true, target IE11
// https://github.com/browserslist/browserslist#queries
['ie 11'] :
// This corresponds to the version of Chromium used by
// Samsung Internet 6.x, which is the minimum non-evergreen
// browser we currently support.
['chrome >= 56'],
},
}]],
presets: [
[
'@babel/preset-env',
{
loose: true,
targets: {
browsers: es5
? // If es5 is true, target IE11
// https://github.com/browserslist/browserslist#queries
['ie 11']
: // This corresponds to the version of Chromium used by
// Samsung Internet 6.x, which is the minimum non-evergreen
// browser we currently support.
['chrome >= 56'],
},
},
],
],
};
if (es5) {
babelConfig.plugins = [asyncToPromises];
@@ -78,8 +83,8 @@ module.exports = {
// This is what the build should be
const replaceOptions = {
'preventAssignment': true,
'WORKBOX_CDN_ROOT_URL': getVersionsCDNUrl(),
preventAssignment: true,
WORKBOX_CDN_ROOT_URL: getVersionsCDNUrl(),
};
if (buildType) {
+6 -3
View File
@@ -20,13 +20,16 @@ const getDetails = (packagePath) => {
};
module.exports = async (packagePath) => {
const versionString =
`try{self['${getDetails(packagePath)}']&&_()}catch(e){}`;
const versionString = `try{self['${getDetails(
packagePath,
)}']&&_()}catch(e){}`;
if (await fs.pathExists(path.join(packagePath, 'src', 'index.ts'))) {
const tsVersionString = `// @ts-ignore\n${versionString}`;
await fs.writeFile(
path.join(packagePath, 'src', '_version.ts'), tsVersionString);
path.join(packagePath, 'src', '_version.ts'),
tsVersionString,
);
}
const mjsVersionString = `${versionString}// eslint-disable-line`;
+2 -2
View File
@@ -9,5 +9,5 @@
const cdn = require('../../packages/workbox-build/src/cdn-details.json');
const lernaPkg = require('../../lerna.json');
module.exports = () => `${cdn.origin}/${cdn.bucketName}/${cdn.releasesDir}` +
`/${lernaPkg.version}`;
module.exports = () =>
`${cdn.origin}/${cdn.bucketName}/${cdn.releasesDir}` + `/${lernaPkg.version}`;
+4 -2
View File
@@ -35,8 +35,10 @@ for (const taskFile of taskFiles) {
continue;
}
if (name in module.exports) {
throw new Error(`Duplicate task definition: ${name} defined in` +
` ${taskFile} conflicts with another task.`);
throw new Error(
`Duplicate task definition: ${name} defined in` +
` ${taskFile} conflicts with another task.`,
);
}
module.exports[name] = task;
}
+2 -1
View File
@@ -69,7 +69,8 @@ class AggregateSizePlugin extends PluginInterface {
const failPR = Boolean(percentValue > 100);
const prettyLog = `**${totalGzipString}** gzip'ed ` +
const prettyLog =
`**${totalGzipString}** gzip'ed ` +
`(**${percentString}%** of limit)\n` +
`**${totalSizeString}** uncompressed`;
@@ -6,46 +6,46 @@
# https://opensource.org/licenses/MIT.
constructor:
prefix: 'new '
prefix: 'new '
returnTypesSeparator: '&nbsp;returns&nbsp;'
tables:
body:
defaultValue: 'Defaults to {valueString}.'
defaultValueString: '<code>{value}</code>'
eachValueHasProperties: 'Values in <code>{name}</code> have the following properties:'
isOptional: 'Optional'
isRequired: '&nbsp;'
nonNullable:
long: 'Value must not be null.'
short: 'non-null'
nullable:
long: 'Value may be null.'
short: 'nullable'
repeatable:
long: 'Value may be repeated.'
short: 'repeatable'
unknownType: '?'
emptyCellPlaceholder: '&nbsp;'
header:
description: 'Description'
name: 'Name'
optional: 'Optional'
type: 'Type'
notApplicable: '&#8212;'
body:
defaultValue: 'Defaults to {valueString}.'
defaultValueString: '<code>{value}</code>'
eachValueHasProperties: 'Values in <code>{name}</code> have the following properties:'
isOptional: 'Optional'
isRequired: '&nbsp;'
nonNullable:
long: 'Value must not be null.'
short: 'non-null'
nullable:
long: 'Value may be null.'
short: 'nullable'
repeatable:
long: 'Value may be repeated.'
short: 'repeatable'
unknownType: '?'
emptyCellPlaceholder: '&nbsp;'
header:
description: 'Description'
name: 'Name'
optional: 'Optional'
type: 'Type'
notApplicable: '&#8212;'
params:
all: '({params})'
joiner: |
{items, plural,
=0 {{param}}
other {, {param}}}
optional: '{param}'
repeatable: '...{param}'
all: '({params})'
joiner: |
{items, plural,
=0 {{param}}
other {, {param}}}
optional: '{param}'
repeatable: '...{param}'
headings:
enums: |
{items, plural,
=1 {Enumeration}
other {Enumerations}}
values: |
{items, plural,
=1 {Value}
other {Values}}
enums: |
{items, plural,
=1 {Enumeration}
other {Enumerations}}
values: |
{items, plural,
=1 {Value}
other {Values}}
@@ -20,7 +20,7 @@ class PublishJob extends BaselinePublishJob {
}
generateTocYaml(symbols, basepath) {
symbols.sort(function(a, b) {
symbols.sort(function (a, b) {
let aName = a.kind === 'namespace' ? a.longname : a.name;
let bName = b.kind === 'namespace' ? b.longname : b.name;
@@ -40,8 +40,8 @@ class PublishJob extends BaselinePublishJob {
// check for duplicated names
symbols.forEach((symbol) => {
const symbolName = symbol.kind === 'namespace' ?
symbol.longname : symbol.name;
const symbolName =
symbol.kind === 'namespace' ? symbol.longname : symbol.name;
if ({}.hasOwnProperty.call(this._symbolNames, symbolName)) {
this._symbolNames[symbolName] = true;
} else {
@@ -54,8 +54,8 @@ class PublishJob extends BaselinePublishJob {
// disambiguated names are bar.Quxand baz.Qux.
symbols.forEach((symbol) => {
let mappedName = null;
const symbolName = symbol.kind === 'namespace' ?
symbol.longname : symbol.name;
const symbolName =
symbol.kind === 'namespace' ? symbol.longname : symbol.name;
if (this._symbolNames[symbolName] === true) {
if (symbol.kind !== 'namespace') {
@@ -69,8 +69,9 @@ class PublishJob extends BaselinePublishJob {
}
}
symbol.tocYamlName = mappedName || (symbol.kind === 'namespace' ?
symbol.longname : symbol.name);
symbol.tocYamlName =
mappedName ||
(symbol.kind === 'namespace' ? symbol.longname : symbol.name);
});
const data = {
@@ -98,8 +99,7 @@ class PublishJob extends BaselinePublishJob {
longnames.sort();
const data = {
longnames: longnames,
pageTitle: global.env.opts.query ?
global.env.opts.query.productName : '',
pageTitle: global.env.opts.query ? global.env.opts.query.productName : '',
};
this.generate('index-all', data, 'index-all.html');
+29 -22
View File
@@ -13,13 +13,14 @@ const fileFinder = require('jsdoc-baseline/lib/filefinder');
const helper = require('jsdoc/util/templateHelper');
const path = require('jsdoc/path');
exports.publish = function(data, opts, tutorials) {
exports.publish = function (data, opts, tutorials) {
baselineConfig.loadSync();
baselineConfig.set('l10n', path.join(__dirname, 'lang'))
.set('static', path.join(__dirname, 'static'))
.set('views.partials', path.join(__dirname, 'views'))
.set('views.layouts', path.join(__dirname, 'views'))
.set('modules', path.join(__dirname, 'lib'));
baselineConfig
.set('l10n', path.join(__dirname, 'lang'))
.set('static', path.join(__dirname, 'static'))
.set('views.partials', path.join(__dirname, 'views'))
.set('views.layouts', path.join(__dirname, 'views'))
.set('modules', path.join(__dirname, 'lib'));
const config = baselineConfig.get();
@@ -39,38 +40,44 @@ exports.publish = function(data, opts, tutorials) {
docletHelper.addDoclets(data);
job.setPackage(docletHelper.getPackage())
.setNavTree(docletHelper.navTree)
.setAllLongnamesTree(docletHelper.allLongnamesTree);
job
.setPackage(docletHelper.getPackage())
.setNavTree(docletHelper.navTree)
.setAllLongnamesTree(docletHelper.allLongnamesTree);
// create the output directory so we can start generating files
job.createOutputDirectory()
// then generate the source files so we can link to them
.generateSourceFiles(docletHelper.shortPaths);
job
.createOutputDirectory()
// then generate the source files so we can link to them
.generateSourceFiles(docletHelper.shortPaths);
// generate globals page if necessary
job.generateGlobals(docletHelper.globals);
// generate TOC data and index page
job.generateTocData({hasGlobals: docletHelper.hasGlobals()})
.generateIndex(opts.readme);
job
.generateTocData({hasGlobals: docletHelper.hasGlobals()})
.generateIndex(opts.readme);
// generate the rest of the output files (excluding tutorials)
docletHelper.getOutputLongnames().forEach(function(longname) {
job.generateByLongname(longname, docletHelper.getLongname(longname),
docletHelper.getMemberof(longname));
docletHelper.getOutputLongnames().forEach(function (longname) {
job.generateByLongname(
longname,
docletHelper.getLongname(longname),
docletHelper.getMemberof(longname),
);
});
// finally, generate the tutorials, and copy static files to the output
// directory
job.generateTutorials(tutorials)
.copyStaticFiles();
job.generateTutorials(tutorials).copyStaticFiles();
// custom Cast pages
job.generateTocYaml(
docletHelper.getCategory('classes')
.concat(docletHelper.getCategory('namespaces'))
.concat(docletHelper.getCategory('interfaces')),
docletHelper
.getCategory('classes')
.concat(docletHelper.getCategory('namespaces'))
.concat(docletHelper.getCategory('interfaces')),
global.env.opts.query ? global.env.opts.query.basepath : '',
);
job.generateIndexAll(Object.keys(docletHelper.longname));
@@ -1,15 +1,14 @@
.label {
font-style: italic;
text-transform: uppercase;
}
.dl-compact dt {
margin:8px 0px 0px 0px;
margin: 8px 0px 0px 0px;
}
h1.devsite-page-title {
display: none;
display: none;
}
h1 {
@@ -67,5 +66,5 @@ h2.symbol-header {
}
table.function.param tr {
background: #80A7B9;
background: #80a7b9;
}
+60 -41
View File
@@ -14,59 +14,78 @@ module.exports = async (swURL) => {
return activateSWSafari(swURL);
}
const error = await global.__workbox.webdriver.executeAsyncScript((swURL, cb) => {
function _onStateChangePromise(registration, desiredState) {
return new Promise((resolve, reject) => {
if (desiredState === 'activated' && registration.active) {
resolve();
return;
}
if (registration.installing === null) {
reject(new Error('No installing service worker found.'));
return;
}
const serviceWorker = registration.installing;
// We unregister all service workers after each test - this should
// always trigger an install state change
const stateChangeListener = (event) => {
if (event.target.state === desiredState) {
serviceWorker.removeEventListener('statechange', stateChangeListener);
const error = await global.__workbox.webdriver.executeAsyncScript(
(swURL, cb) => {
function _onStateChangePromise(registration, desiredState) {
return new Promise((resolve, reject) => {
if (desiredState === 'activated' && registration.active) {
resolve();
return;
}
if (event.target.state === 'redundant') {
serviceWorker.removeEventListener('statechange', stateChangeListener);
reject(new Error('Installing service worker became redundant.'));
if (registration.installing === null) {
reject(new Error('No installing service worker found.'));
return;
}
};
serviceWorker.addEventListener('statechange', stateChangeListener);
});
}
const serviceWorker = registration.installing;
navigator.serviceWorker.register(swURL).then((registration) => {
return _onStateChangePromise(registration, 'activated');
}).then(() => {
// Ensure the page is being controlled by the SW.
if (navigator.serviceWorker.controller &&
navigator.serviceWorker.controller.scriptURL === swURL) {
return;
} else {
return new Promise((resolve) => {
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (navigator.serviceWorker.controller.scriptURL === swURL) {
// We unregister all service workers after each test - this should
// always trigger an install state change
const stateChangeListener = (event) => {
if (event.target.state === desiredState) {
serviceWorker.removeEventListener(
'statechange',
stateChangeListener,
);
resolve();
return;
}
});
if (event.target.state === 'redundant') {
serviceWorker.removeEventListener(
'statechange',
stateChangeListener,
);
reject(new Error('Installing service worker became redundant.'));
return;
}
};
serviceWorker.addEventListener('statechange', stateChangeListener);
});
}
}).then(() => cb()).catch((error) => cb(error.message));
}, swURL);
navigator.serviceWorker
.register(swURL)
.then((registration) => {
return _onStateChangePromise(registration, 'activated');
})
.then(() => {
// Ensure the page is being controlled by the SW.
if (
navigator.serviceWorker.controller &&
navigator.serviceWorker.controller.scriptURL === swURL
) {
return;
} else {
return new Promise((resolve) => {
navigator.serviceWorker.addEventListener(
'controllerchange',
() => {
if (navigator.serviceWorker.controller.scriptURL === swURL) {
resolve();
}
},
);
});
}
})
.then(() => cb())
.catch((error) => cb(error.message));
},
swURL,
);
if (error) {
throw new Error(error);
+51 -33
View File
@@ -9,49 +9,63 @@
// TODO(philipwalton): remove this in favor of using workbox-window.
module.exports = async (swURL) => {
// First step: Wait for the page to activate
let error = await global.__workbox.webdriver.executeAsyncScript((swURL, cb) => {
const onStateChangePromise = (registration, desiredState) => {
return new Promise((resolve, reject) => {
if (desiredState === 'activated' &&
let error = await global.__workbox.webdriver.executeAsyncScript(
(swURL, cb) => {
const onStateChangePromise = (registration, desiredState) => {
return new Promise((resolve, reject) => {
if (
desiredState === 'activated' &&
registration.active &&
// Checking that the URLs match is needed to fix:
// https://github.com/GoogleChrome/workbox/issues/1633
registration.active.scriptURL === swURL) {
resolve();
return;
}
const serviceWorker = registration.installing || registration.waiting;
if (serviceWorker === null) {
throw new Error('There is no installing or waiting service worker.');
}
const stateChangeListener = function(evt) {
if (evt.target.state === desiredState) {
serviceWorker.removeEventListener('statechange', stateChangeListener);
registration.active.scriptURL === swURL
) {
resolve();
return;
}
if (evt.target.state === 'redundant') {
serviceWorker.removeEventListener('statechange', stateChangeListener);
// Must call reject rather than throw error here due to this
// being inside the scope of the callback function stateChangeListener
reject(new Error('The new service worker became redundant.'));
return;
const serviceWorker = registration.installing || registration.waiting;
if (serviceWorker === null) {
throw new Error(
'There is no installing or waiting service worker.',
);
}
};
serviceWorker.addEventListener('statechange', stateChangeListener);
});
};
const stateChangeListener = function (evt) {
if (evt.target.state === desiredState) {
serviceWorker.removeEventListener(
'statechange',
stateChangeListener,
);
resolve();
return;
}
navigator.serviceWorker.register(swURL)
if (evt.target.state === 'redundant') {
serviceWorker.removeEventListener(
'statechange',
stateChangeListener,
);
// Must call reject rather than throw error here due to this
// being inside the scope of the callback function stateChangeListener
reject(new Error('The new service worker became redundant.'));
return;
}
};
serviceWorker.addEventListener('statechange', stateChangeListener);
});
};
navigator.serviceWorker
.register(swURL)
.then((registration) => onStateChangePromise(registration, 'activated'))
.then(() => cb())
.catch((err) => cb(err.message));
}, swURL);
},
swURL,
);
if (error) {
throw error;
@@ -59,13 +73,17 @@ module.exports = async (swURL) => {
// To be 100% certain - ensure the SW is controlling the page.
error = await global.__workbox.webdriver.executeAsyncScript((swURL, cb) => {
if (navigator.serviceWorker.controller &&
navigator.serviceWorker.controller.scriptURL === swURL) {
if (
navigator.serviceWorker.controller &&
navigator.serviceWorker.controller.scriptURL === swURL
) {
cb();
} else if (!navigator.serviceWorker.controller) {
cb(`There's no service worker controlling the page.`);
} else {
cb(`There's an unexpected SW controlling the page: ${navigator.serviceWorker.controller.scriptURL}`);
cb(
`There's an unexpected SW controlling the page: ${navigator.serviceWorker.controller.scriptURL}`,
);
}
}, swURL);
+2 -2
View File
@@ -23,12 +23,12 @@ stubLogger();
// This is part of the "root" mocha suite - meaning it'll reset all the logger
// values before every test.
beforeEach(function() {
beforeEach(function () {
sandbox.restore();
stubLogger();
});
after(function() {
after(function () {
sandbox.restore();
});
+9 -5
View File
@@ -17,11 +17,15 @@ module.exports = async (webdriver, testingURL) => {
// can't call runInSW().
}
const error = await webdriver.executeAsyncScript((cb) => {
navigator.serviceWorker.getRegistration().then((reg) => {
if (reg) {
return reg.unregister();
}
}).then(() => cb()).catch((err) => cb(err.message));
navigator.serviceWorker
.getRegistration()
.then((reg) => {
if (reg) {
return reg.unregister();
}
})
.then(() => cb())
.catch((err) => cb(err.message));
});
if (error) {
throw new Error(error);

Some files were not shown because too many files have changed in this diff Show More