diff --git a/devsiteHelper.py b/devsiteHelper.py index 03fff188db8..9eb58c51b0d 100644 --- a/devsiteHelper.py +++ b/devsiteHelper.py @@ -152,7 +152,7 @@ def parseBookYaml(pathToBook, lang='en'): upperTabs.append(expandBook(upperTab)) return result except Exception as e: - logging.exception('Error in parseBookYaml') + logging.exception(e) return None @@ -199,9 +199,12 @@ def getLowerTabs(bookYaml): for lowerTab in tab['lower_tabs']['other']: lt = {} lt['name'] = lowerTab['name'] - if 'contents' in lowerTab and 'path' in lowerTab['contents'][0]: - lt['path'] = lowerTab['contents'][0]['path'] - result.append(lt) + if 'contents' in lowerTab: + for lowerTabContent in lowerTab['contents']: + if 'path' in lowerTabContent: + lt['path'] = lowerTabContent['path'] + result.append(lt) + break except Exception as e: logging.exception('Unable to read/parse the lower tabs') return result @@ -220,8 +223,16 @@ def getLeftNav(requestPath, bookYaml, lang='en'): for upperTab in bookYaml['upper_tabs']: if 'path' in upperTab and requestPath.startswith(upperTab['path']): for lowerTab in upperTab['lower_tabs']['other']: - if ('path' not in lowerTab['contents'][0] or - requestPath.startswith(lowerTab['contents'][0]['path'])): + firstPathInLowerTab = None + for lowerTabContent in lowerTab['contents']: + if 'path' in lowerTabContent: + firstPathInLowerTab = lowerTabContent['path'] + break + if (firstPathInLowerTab is None): + if 'path' in lowerTab: + firstPathInLowerTab = lowerTab['path'] + if (firstPathInLowerTab is None or + requestPath.startswith(firstPathInLowerTab)): result = '\n' @@ -229,6 +240,7 @@ def getLeftNav(requestPath, bookYaml, lang='en'): except Exception as e: msg = ' - Unable to read or parse primary book.yaml' logging.exception(msg) + logging.exception(e) whoops += '

Exception occured.

' return whoops @@ -243,6 +255,13 @@ def buildLeftNav(bookYaml, lang='en'): result += '' + cgi.escape(item['title']) + '\n' result += '\n' result += '\n' + elif 'heading' in item: + result += '
  • \n'; + result += '\n'; + result += '\n
  • \n'; elif 'section' in item: # Sub-section result += '
  • \n' diff --git a/devsiteParseYAML.py b/devsiteParseYAML.py index f0708208c13..860baaf2630 100644 --- a/devsiteParseYAML.py +++ b/devsiteParseYAML.py @@ -58,6 +58,8 @@ def parse(requestPath, fileLocation, rawYaml, lang='en'): if 'heading' in row: section += '

    ' section += row['heading'] + '

    ' + if 'description' in row: + section += row['description'] if 'items' in row: section += '
    ' section += parseIndexYamlItems(row['items']) diff --git a/gulp-tasks/build.js b/gulp-tasks/build.js index 429695233cf..cbcac4ba477 100644 --- a/gulp-tasks/build.js +++ b/gulp-tasks/build.js @@ -20,6 +20,10 @@ gulp.task('build:announcement', function() { const globOpts = { srcBase: 'src/content/en/', prefixBase: true, + ignore: [ + // Disable forced announcements on Workbox. + '**/workbox/**/_project.yaml', + ] }; const dumpYamlOpts = {lineWidth: 1000}; const projectYamlFiles = glob.find('**/_project.yaml', globOpts); diff --git a/gulp-tasks/workbox-v3-ref-docs.js b/gulp-tasks/workbox-v3-ref-docs.js new file mode 100644 index 00000000000..e5f3b9cd816 --- /dev/null +++ b/gulp-tasks/workbox-v3-ref-docs.js @@ -0,0 +1,194 @@ +const gulp = require('gulp'); +const remoteGitTags = require('remote-git-tags'); +const semver = require('semver'); +const fse = require('fs-extra'); +const path = require('path'); +const os = require('os'); +const spawn = require('child_process').spawn; +const glob = require('glob'); + +const PREVIOUS_RELEASES = 0; + +const buildJSDocs = (srcCodePath, docOutputPath, jsdocConfPath) => { + console.log(`\n\n Building JSDocs to '${path.relative(process.cwd(), docOutputPath)}'.`); + + try { + fse.accessSync(jsdocConfPath, fse.F_OK); + } catch (err) { + console.warn(`Unable to find jsdoc Config File @ '${jsdocConfPath}'`); + console.warn(err); + return; + } + + const contentPath = path.join(__dirname, '..', 'src', 'content', 'en'); + const templateBasePath = path.join( + path.posix.sep, + 'web', + path.relative(contentPath, docOutputPath) + ); + console.log(`\n\n Using JSDoc basepath=${templateBasePath}.`); + + const jsdocConfigContents = fse.readFileSync(jsdocConfPath); + const jsdocConfig = JSON.parse(jsdocConfigContents); + if (!jsdocConfig.webFundamentals) { + console.warn(`In your JSDoc config file you MUST provide a 'webFundamentals' property with:`); + console.warn(` projectRoot`); + console.warn(` productName`); + return; + } + + const queryString = [ + `projectRoot=${jsdocConfig.webFundamentals.projectRoot}`, + `basepath=${templateBasePath}`, + `productName=${jsdocConfig.webFundamentals.productName}`, + ].join('&'); + + const jsDocParams = [ + '--template', path.join( + __dirname, '..', 'src', 'templates', 'reference-docs', 'jsdoc' + ), + '-c', jsdocConfPath, + '-d', docOutputPath, + '--query', queryString, + ]; + + console.log(` JSDoc Params: `, jsDocParams); + + const jsdocPath = path.join(__dirname, '..', 'node_modules', 'jsdoc', 'jsdoc.js'); + + return new Promise((resolve, reject) => { + const jsdocProcess = spawn(jsdocPath, jsDocParams, { + cwd: srcCodePath, + stdio: 'inherit', + }); + + jsdocProcess.on('error', (err) => { + console.error('\n\nUnable to run jsdoc.'); + console.error(err); + }); + + jsdocProcess.on('close', (code) => { + if (code === 0) { + resolve(docOutputPath); + } else { + reject(`Error code: ${code}`); + } + }); + }) + .then((docOutputPath) => { + // jsdoc-baseline copies over these files for it's own template + // but we don't use them for devsite - so remove these files. + fse.removeSync(path.join(docOutputPath, 'css')); + fse.removeSync(path.join(docOutputPath, 'scripts')); + + return docOutputPath; + }) + .then((docOutputPath) => { + // Web Fundamentals linting errors on developers.google.com + const allFiles = glob.sync(path.join(docOutputPath, '**', '*'), { + absolute: true, + }); + allFiles.forEach((filePath) => { + const fileContents = fse.readFileSync(filePath).toString(); + const cleanContents = fileContents + .split('https://developers.google.com/').join('/'); + fse.writeFileSync(filePath, cleanContents); + }); + + return docOutputPath; + }) + .catch((err) => { + // If we error'd, make sure we didn't create a directory that will stop + // future doc builds. + fse.removeSync(docOutputPath); + + console.error(`\n\nUnable to build docs for: '${path.relative(process.cwd(), docOutputPath)}'`); + console.error(err); + + return null; + }); +}; + +const getSourceCode = (gitUrl, tag, tmpPath) => { + fse.ensureDirSync(tmpPath); + + return new Promise((resolve, reject) => { + const gitDownload = spawn('git', [ + 'clone', + '--branch', tag, + '--depth', '1', + '--config', 'advice.detachedHead=false', + gitUrl, + tmpPath, + ], { + stdio: 'inherit', + }); + + gitDownload.on('error', (err) => { + console.error(`\n\nUnable to retrieve tag '${tag}' from Git.`); + console.error(err); + reject(`Unable to retrieve tag '${tag}' from Git.`); + }); + + gitDownload.on('close', (code) => { + if (code === 0) { + resolve(tmpPath); + } else { + reject(`Error ${code} returned by command: 'git ${params.join(' ')}'`); + } + }); + }); +}; + +const generateRefDocs = (projectName, gitUrl, docPath, tag, jsdocConfPath, isLatest) => { + // 1. Check if current tag exists, if so return + const outputPath = path.join(docPath, tag); + if (fse.pathExistsSync(outputPath)) { + return; + } + + console.log(`\n\nNeed to build docs for '${projectName}: ${tag}'`); + + const tmpDirectory = path.join(os.tmpdir(), Date.now().toString()); + const tmpSrCodePath = path.join(tmpDirectory, tag); + return getSourceCode(gitUrl, tag, tmpSrCodePath) + .then(() => { + if (isLatest) { + const outputPath = path.join(docPath, 'latest'); + return buildJSDocs(tmpSrCodePath, outputPath, jsdocConfPath); + } + }) + .then(() => { + if (PREVIOUS_RELEASES > 0) { + return buildJSDocs(tmpSrCodePath, outputPath, jsdocConfPath); + } + }) + .then(() => { + fse.removeSync(tmpDirectory); + }, (err) => { + fse.removeSync(tmpDirectory); + throw err; + }); +}; + +const buildReferenceDocs = (projectName, gitUrl, localPath, jsdocConfPath) => { + fse.removeSync(path.join(localPath, 'latest')); + + return generateRefDocs( + projectName, + gitUrl, + localPath, + 'v3', + jsdocConfPath, + true, + ); +}; + +gulp.task('reference-docs:workbox-v3', () => { + return buildReferenceDocs( + 'Workbox', + 'https://github.com/GoogleChrome/workbox.git', + path.join(__dirname, '..', 'src/content/en/tools/workbox/v3/reference-docs/'), + path.join(__dirname, '..', 'src/content/en/tools/workbox/v3/_jsdoc.conf') + ); +}); diff --git a/gulp-tasks/workbox:generate-contributors.js b/gulp-tasks/workbox:generate-contributors.js new file mode 100644 index 00000000000..92d60f9ead0 --- /dev/null +++ b/gulp-tasks/workbox:generate-contributors.js @@ -0,0 +1,94 @@ +const GitHubApi = require('github'); +const fs = require('fs-extra'); +const path = require('path'); +const gulp = require('gulp'); + +const MAX_COLLABORATORS = 20; + +function getContributorHTML(contributorStats) { + const contributor = contributorStats.author; + let html = ` + +`; + return html; +} + +gulp.task(`workbox:generate-contributors`, function() { + if (!process.env.GITHUB_TOKEN) { + console.warn(`Unable to build Workbox contributors due to no ` + + `GITHUB_TOKEN existing on the current Path.`); + + // Return a promise so gulp is happy and thinks the task completed + return Promise.resolve(); + } + + const github = new GitHubApi(); + github.authenticate({ + type: 'token', + token: process.env.GITHUB_TOKEN + }); + + return github.repos.getStatsContributors({ + owner: 'googlechrome', + repo: 'workbox', + }) + .then((contributorStats) => { + contributorStats.sort((a, b) => b.total - a.total); + if (contributorStats.length > MAX_COLLABORATORS) { + contributorStats = contributorStats.splice(0, MAX_COLLABORATORS); + } + return contributorStats.map(getContributorHTML).join(''); + }) + .then((html) => { + const finalHtml = `{% framebox height="auto" %} + + +
    +${html} +
    +{% endframebox %}`; + const templatePath = path.join(__dirname, '..', 'src', 'content', + 'en', 'tools', 'workbox', 'templates', 'contributors.html'); + return fs.ensureDir(path.dirname(templatePath)) + .then(() => fs.writeFile(templatePath, finalHtml)) + .catch((err) => { + console.warn(`An error occured when generating the Workbox ` + + `collaborators.`); + console.warn(`This is not a vital error.`); + console.warn(err); + }); + }); +}); diff --git a/src/content/en/images/md-icons/ic_extension_black_24px.svg b/src/content/en/images/md-icons/ic_extension_black_24px.svg new file mode 100644 index 00000000000..91b12d5e446 --- /dev/null +++ b/src/content/en/images/md-icons/ic_extension_black_24px.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/src/content/en/tools/_book.yaml b/src/content/en/tools/_book.yaml index 0035874c28b..9494446f039 100644 --- a/src/content/en/tools/_book.yaml +++ b/src/content/en/tools/_book.yaml @@ -22,8 +22,8 @@ upper_tabs: - name: Workbox contents: - include: /web/tools/workbox/_toc.yaml - - name: Chrome User Experience Report - contents: - - include: /web/tools/chrome-user-experience-report/_toc.yaml +# - name: Chrome User Experience Report +# contents: +# - include: /web/tools/chrome-user-experience-report/_toc.yaml - include: /web/_upper_tabs-Updates.yaml - include: /web/_upper_tabs-Showcase.yaml diff --git a/src/content/en/tools/workbox/_toc.yaml b/src/content/en/tools/workbox/_toc.yaml index d7c9412a114..801961b3828 100644 --- a/src/content/en/tools/workbox/_toc.yaml +++ b/src/content/en/tools/workbox/_toc.yaml @@ -23,3 +23,5 @@ toc: - title: Github path: https://github.com/GoogleChrome/workbox status: external +# - title: Next Release (Alpha) +# path: /web/tools/workbox/v3 diff --git a/src/content/en/tools/workbox/templates/contributors.html b/src/content/en/tools/workbox/templates/contributors.html new file mode 100644 index 00000000000..522d1e17a6f --- /dev/null +++ b/src/content/en/tools/workbox/templates/contributors.html @@ -0,0 +1,192 @@ +{% framebox height="auto" %} + + + +{% endframebox %} \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/_book.yaml b/src/content/en/tools/workbox/v3/_book.yaml new file mode 100644 index 00000000000..bc3ca90f900 --- /dev/null +++ b/src/content/en/tools/workbox/v3/_book.yaml @@ -0,0 +1,22 @@ +upper_tabs: + - include: /web/_upper_tabs-Fundamentals.yaml + - name: Tools + heading: "Workbox" + path: /web/tools/ + lower_tabs: + other: + - name: Home + contents: + - title: Home + path: /web/tools/workbox/v3/ + - name: Guides + contents: + - include: /web/tools/workbox/v3/guides/_toc.yaml + - name: Modules + contents: + - include: /web/tools/workbox/v3/modules/_toc.yaml + - name: Reference Docs + contents: + - include: /web/tools/workbox/v3/reference-docs/_toc.yaml + - include: /web/_upper_tabs-Updates.yaml + - include: /web/_upper_tabs-Showcase.yaml diff --git a/src/content/en/tools/workbox/v3/_footer.yaml b/src/content/en/tools/workbox/v3/_footer.yaml new file mode 100644 index 00000000000..8f813827d0a --- /dev/null +++ b/src/content/en/tools/workbox/v3/_footer.yaml @@ -0,0 +1,27 @@ +footer: +- linkboxes: + - name: Key Topics + icon_name: star + contents: + - label: Guides + path: /web/tools/workbox/v3/guides/ + - label: Modules + path: /web/tools/workbox/v3/modules/ + - label: Reference Docs + path: /web/tools/workbox/v3/reference-docs/latest/ + + - name: Get in Touch + icon_name: star + contents: + - label: "@workboxjs on Twitter" + path: https://twitter.com/workboxjs + - label: Join the Slack Channel + path: /web/tools/workbox/v3/community + + - name: Contribute + icon_name: bug_report + contents: + - label: Ask a Question on StackOverflow + path: https://stackoverflow.com/questions/ask?tags=workbox + - label: File an Issue + path: https://github.com/googlechrome/workbox/issues diff --git a/src/content/en/tools/workbox/v3/_index.yaml b/src/content/en/tools/workbox/v3/_index.yaml new file mode 100644 index 00000000000..8965703c0e1 --- /dev/null +++ b/src/content/en/tools/workbox/v3/_index.yaml @@ -0,0 +1,73 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml + +landing_page: + header: + description: + + rows: + - heading: Welcome + description: > + Welcome to the home of Workbox! + + Workbox is a set of libraries and Node modules that make it easy to cache + assets of your sites offline and take full advantage of features used + to build progressive web apps. + + + items: + - heading: Get Started + description: > + Getting started with Workbox is easy, in a few minutes you'll be + caching assets for your web site and serving them up in your web app. + custom_image: + background: google-green + icon_name: history + buttons: + - label: Get started + path: /web/tools/workbox/v3/guides/get-started + + - heading: "Workbox @ Chrome Dev Summit" + background: grey + items: + - heading: "" + description: > + In this talk, Jeff Posnick gives an overview of Workbox's support for + caching strategies, precaching, and handling navigation requests. It's + filled throughout with real-world examples of how companies like + Pinterest and WIRED are using Workbox in production. + youtube_id: DtuJ55tmjps + + - heading: "Who's Using Workbox?" + description: > + +
    +
    Wired Logo
    +
    Pinterest Logo
    +
    Starbucks Logo
    + +
    Forbes Logo
    +
    iHeart Radio Logo
    +
    Tinder Logo
    +
    + + - heading: "Contributors" + background: grey + description: > +

    Workbox is built and maintained by friendly bunch of contributors + without whom none of this would be possible.

    + + {% include 'web/tools/workbox/templates/contributors.html' %} diff --git a/src/content/en/tools/workbox/v3/_jsdoc.conf b/src/content/en/tools/workbox/v3/_jsdoc.conf new file mode 100644 index 00000000000..7dd9e4a60eb --- /dev/null +++ b/src/content/en/tools/workbox/v3/_jsdoc.conf @@ -0,0 +1,16 @@ +{ + "source": { + "include": [ + "packages" + ], + "includePattern": ".+\\.(js(doc|x)?|mjs)$", + "excludePattern": "((^|\\/|\\\\)build(\\/|\\\\)|(^|\\/|\\\\)test(\\/|\\\\)|(^|\\/|\\\\)node_modules(\\/|\\\\)|(^|\\/|\\\\)demo(\\/|\\\\))" + }, + "opts": { + "recurse": true + }, + "webFundamentals": { + "projectRoot": "/web/tools/workbox/v3/", + "productName": "Workbox" + } +} diff --git a/src/content/en/tools/workbox/v3/_project.yaml b/src/content/en/tools/workbox/v3/_project.yaml new file mode 100644 index 00000000000..96d8eac9729 --- /dev/null +++ b/src/content/en/tools/workbox/v3/_project.yaml @@ -0,0 +1,11 @@ +name: Workbox +description: Workbox is a set of service worker libraries that making build progressive web apps easy. +home_url: /web/tools/workbox/v3/ +buganizer_id: 180451 +color: orange +content_license: cc3-apache2 +footer_path: /web/tools/workbox/v3/_footer.yaml +google_analytics_ids: + - UA-52746336-1 +icon: + path: /web/tools/workbox/v3/images/workbox-icon192x192.png diff --git a/src/content/en/tools/workbox/v3/community.md b/src/content/en/tools/workbox/v3/community.md new file mode 100644 index 00000000000..18f39ed4c8b --- /dev/null +++ b/src/content/en/tools/workbox/v3/community.md @@ -0,0 +1,45 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: Workbox Examples. + +{# wf_published_on: 2017-10-04 #} +{# wf_updated_on: 2017-10-04 #} + +# Community {: .page-title } + +There are a few ways you learn more about plans for Workbox, help others, +and get support. + +## Stack Overflow + +Stack Overflow is a great place to asking and answering +questions on how to use Workbox. + +If you do raise a question please use the +[workbox](https://stackoverflow.com/questions/ask?tags=workbox) +tag. This will help the community easily +[find](https://stackoverflow.com/questions/tagged/workbox) and answer your +questions. + +## Slack + +Once a week the Core Workbox team will be on Slack +for an hour or so to discuss upcoming changes as well +as future plans. + +If you are interested in taking part please feel free to join +the **#workbox** room on the +[ChromiumDev Slack Channel](https://chromiumdev.slack.com/). + +If you're not already a member of the channel, you can +[request access here](https://chromiumdev-slack.herokuapp.com/). + +Times of when we'll be meeting are on the calendar below. + +## Team Calendar + +To find out when the next release will be going out or +to learn when the team is scheduled to chat +on Slack, check out the calendar below: + + diff --git a/src/content/en/tools/workbox/v3/guides/_toc.yaml b/src/content/en/tools/workbox/v3/guides/_toc.yaml new file mode 100644 index 00000000000..25275bb6081 --- /dev/null +++ b/src/content/en/tools/workbox/v3/guides/_toc.yaml @@ -0,0 +1,29 @@ +toc: + +- title: Overview + path: /web/tools/workbox/v3/guides/ + +- title: "Get Started" + path: /web/tools/workbox/v3/guides/get-started +- title: "Precache Files" + path: /web/tools/workbox/v3/guides/precache-files +- title: "Route Requests" + path: /web/tools/workbox/v3/guides/route-requests +- title: "Configure Workbox" + path: /web/tools/workbox/v3/guides/configure-workbox +- title: "Handle Third-Party Requests" + path: /web/tools/workbox/v3/guides/handle-third-party-requests +# - title: "Build and Use Plugins" +# path: /web/tools/workbox/v3/guides/build-and-use-plugins +- title: "Common Recipes" + path: /web/tools/workbox/v3/guides/common-recipes +# - title: "Enable Offline Analytics" +# path: /web/tools/workbox/v3/guides/enable-offline-analytics +- title: "Troubleshoot and Debug" + path: /web/tools/workbox/v3/guides/troubleshoot-and-debug +# - title: "Generate a Complete Service Worker" +# path: /web/tools/workbox/v3/guides/generate-complete-sw +# - title: "Migrate from sw-" +# path: /web/tools/workbox/v3/guides/migrate +# - title: "Use as ES2015 Imports" +# path: /web/tools/workbox/v3/guides/use-es2015-imports diff --git a/src/content/en/tools/workbox/v3/guides/common-recipes.md b/src/content/en/tools/workbox/v3/guides/common-recipes.md new file mode 100644 index 00000000000..b7aeeed7190 --- /dev/null +++ b/src/content/en/tools/workbox/v3/guides/common-recipes.md @@ -0,0 +1,126 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: A common recipes to use with Workbox. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Common Recipes {: .page-title } + +This page contains a set of example caching strategies you can use with Workbox. + +## Google Fonts + +You can use a cache first strategy to cache the Google Fonts in your page. +Here we've limited the cache to 30 entries to ensure we don't balloon a users +device. + +```javascript +workbox.routing.registerRoute( + new RegExp('https://fonts.googleapis.com/(.*)'), + workbox.strategies.cacheFirst({ + cacheName: 'googleapis', + cacheExpiration: { + maxEntries: 30 + } + }) +); +``` + +## Caching Images + +You can capture and caching images with a cache first strategy based on +the extension. + +```javascript +workbox.routing.registerRoute( + /\.(?:png|gif|jpg|jpeg|svg)$/, + workbox.strategies.cacheFirst({ + cacheName: 'images', + cacheExpiration: { + maxEntries: 60, + maxAgeSeconds: 30 * 24 * 60 * 60 // 30 Days + } + }) +); +``` + +## Cache CSS and JavaScript Files + +You can use a stale while revalidate for CSS and JavaScript files that +aren't precached. + +```javascript +workbox.routing.registerRoute( + /\.(?:js|css)$/, + workbox.strategies.staleWhileRevalidate({ + cacheName: 'static-resources' + }) +); +``` + +## Caching Content from Multiple Origins + +You can create regular expressions to cache similar requests from multiple +origins in a single route. For example, you can cache assets from origins +like `googleapis.com` and `gstatic.com` with a single route. + +```javascript +workbox.routing.registerRoute( + /.*(?:googleapis|gstatic)\.com.*$/, + workbox.strategies.staleWhileRevalidate() +); +``` + +An alternative to the above example is to cache the origins separately to +store assets in cache for each origin. + +```javascript +workbox.routing.registerRoute( + /.*(?:googleapis)\.com.*$/, + workbox.strategies.staleWhileRevalidate({ + cacheName: 'googleapis' + }) +); + +workbox.routing.registerRoute( + /.*(?:gstatic)\.com.*$/, + workbox.strategies.staleWhileRevalidate({ + cacheName: 'gstatic' + }) +); +``` + +## Restrict Caches for a Specific Origin + +You can cache assets for a specific origin and apply expiration rules on +that cache. For example, the example below caches up to 50 requests for +up to 5 minutes. + +```javascript +workbox.routing.registerRoute( + 'https://hacker-news.firebaseio.com/v0/*', + workbox.strategies.cacheFirst({ + cacheName: 'stories', + cacheExpiration: { + maxEntries: 50, + maxAgeSeconds: 5 * 60 // 5 minutes + }, + cacheableResponse: {statuses: [0, 200]} + }) +); + +``` + +## Cache Resources from a Specific Subdirectory + +You can use a regular expression to easily route requests to files in a +specific directory. If we wanted to route requests to files in `/static/`, +we could use the regular expression `new RegExp('/static/.*/')`, like so: + +```javascript +workbox.routing.registerRoute( + new RegExp('/static/(.*)'), + workbox.strategies.staleWhileRevalidate() +); +``` diff --git a/src/content/en/tools/workbox/v3/guides/configure-workbox.md b/src/content/en/tools/workbox/v3/guides/configure-workbox.md new file mode 100644 index 00000000000..fb2acf7e955 --- /dev/null +++ b/src/content/en/tools/workbox/v3/guides/configure-workbox.md @@ -0,0 +1,137 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: A guide on how to configure Workbox. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Configure Workbox {: .page-title } + +Out of the box Workbox comes set up with some default values for cache names and log levels. This guide will cover how you can change these values and what will happen as a result. + +## Configure Cache Names + +As you start to use Workbox, you'll notice that caches are automatically created. + +![Workbox Default Caches](../images/guides/configure-workbox/default-caches.png) + +By default, Workbox will only create two caches, one for precaching and one for runtime caching. Using `workbox-core` you can get the current cache names like so: + +```javascript +const precacheCacheName = workbox.core.cacheNames.precache; +const runtimeCacheName = workbox.core.cacheNames.runtime; +``` + +Both the precache and runtime cache names are made of three pieces of information: + +`--` + +You can alter the cache names by altering all or some of these pieces of information: + +```javascript +workbox.core.setCacheNameDetails({ + prefix: 'my-app', + suffix: 'v1' +}); +``` + +The above would produce the cache names: + +**Precache:** my-app-precache-v1 + +**Runtime:** my-app-runtime-v1 + +You can customize the entire cache name by parsing in a `precache` and +/ or `runtime` parameter. + +```javascript +workbox.core.setCacheNameDetails({ + prefix: 'my-app', + suffix: 'v1', + precache: 'custom-precache-name', + runtime: 'custom-runtime-name' +}); +``` + +Note: We recommend changing the prefix for each of your projects. This +allows you to work on multiple projects using the same localhost port number +without mixing up the caches. + +### Custom Cache Names in Strategies + +Above discusses how to customise the **default cache names** used +for precaching and runtime caching, but it’s not uncommon to want +additional caches for specific uses, like a cache just for images. + +In other parts of the Workbox API’s there will in an option to supply a +`cacheName` property as an option. For example, the [runtime strategies](/web/tools/workbox/v3/modules/workbox-runtime-caching) accepts a `cacheName` +option. In these cases, the cache name will be used exactly as you define, +the prefix and suffix **will not be used**. + +If you wanted to use a cache for images, you might configure a route like this: + +```javascript +workbox.routing.registerRoute( + /.*\.(?:png|jpg|jpeg|svg|gif)/g, + new workbox.strategies.CacheFirst({ + cacheName: 'my-image-cache', + }) +); +``` + +This will result in images being stored in a cache called `my-image-cache`. + +![Using a Custom Cache Name in Workbox](../images/guides/configure-workbox/custom-cache-name.png) + +### Configure Debug Builds vs Production Builds + +For each of the Workbox service worker libraries, there are two builds, one for development and one for production. + +- **Debug Builds:** Come un-minified, have additional logging and performs rigorous assertion checking to make development as easy as possible. + +- **Production Builds:** Are minified with any optional logging and logic stripped from the build. + +If you are using `workbox-sw`, it’ll automatically use development builds whenever you are developing on a localhost origin, otherwise it’ll use production builds. + +![Debug vs Production Builds of Workbox](../images/guides/configure-workbox/debug-vs-prod.png) + +You can override this behavior with the `debug` option. Setting to true will force debug builds, setting to false will force production builds. + +```javascript +// Force development builds +workbox.setConfig({ debug: true }); + +// Force production builds +workbox.setConfig({ debug: false }); +``` + +If you are using the modules directly (via CDN of from NPM modules), you can switch between development and production builds by changing the file extension between `.dev.js` and `.prod.js`. + +## Configure Log Levels + +Workbox will print messages to the console to help during development. + +![Workbox Welcome Message](../images/guides/configure-workbox/welcome-message.png) + +You can determine the level of a log from the color code: + +![Color coded logs in Workbox](../images/guides/configure-workbox/workbox-core_logs.png) + +You can alter the log level to show more or less logs by setting the log level, like so: + +```javascript +// The most verbose - displays all logs. +workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug); + +// Shows logs, warnings and errors. +workbox.core.setLogLevel(workbox.core.LOG_LEVELS.log); + +// Show warnings and errors. +workbox.core.setLogLevel(workbox.core.LOG_LEVELS.warn); + +// Show *just* errors +workbox.core.setLogLevel(workbox.core.LOG_LEVELS.error); + +// Silence all of the Workbox logs. +workbox.core.setLogLevel(workbox.core.LOG_LEVELS.silent); +``` diff --git a/src/content/en/tools/workbox/v3/guides/get-started.md b/src/content/en/tools/workbox/v3/guides/get-started.md new file mode 100644 index 00000000000..da0635b5f49 --- /dev/null +++ b/src/content/en/tools/workbox/v3/guides/get-started.md @@ -0,0 +1,163 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description:Get Started with Workbox. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Get Started {: .page-title } + +This guide will show you how to get up and running with Workbox to route +common requests for a web page and demonstrate how to cache using a common +strategy. + +Since most websites contain CSS, JavaScript and images, let’s look at how we +can cache and serve these files using a service worker and Workbox. + +## Create and Register a Service Worker File + +Before we can use Workbox, we need to create a service worker file and +register it to our web site. + +Strart by creating a file called `sw.js` at the root of your site and add a +console message to the file (This is so we can see it load). + +```javascript +console.log('Hello from sw.js'); +``` + +In your web page register your new service worker file like so: + +```javascript + +``` + +This tell's the browser this is the service worker to use for site. + +If you refresh your page you'll see the log from your service worker file. + +![Console message from sw.js in DevTools](../images/guides/get-started/hello-console.png) + +Looking in the “Application” tab in Chrome DevTools you should see your service +worker registered. + +![Application Tab displaying a registered service worker.](../images/guides/get-started/application-tab.png) + +Note: Click the “Update on reload” checkbox to make it easier to develop with +your new service worker. + +Now that we have a service worker registered, let’s look at how we can use +Workbox. + +## Importing Workbox + +To start using Workbox you just need to import the `workbox-sw.js` file in your +service worker. + +Change your service worker so that it has the following `importScripts()` call. + +```javascript +importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0-alpha.24/workbox-sw.js'); + +if (workbox) { + console.log(`Yay! Workbox is loaded 🎉`); +} else { + console.log(`Boo! Workbox didn't load 😬`); +} +``` + +With this you should see the “Yay” message so we know that Workbox is +officially loaded in our service worker. + +![DevTools screenshot of Workbox loading in a service worker.](../images/guides/get-started/yay-loaded.png) + +Now we can start using Workbox. + +## Using Workbox + +One of Workbox’s primary features is it’s routing and and caching strategy +modules. It allows you to listen for requests from your web page and determine +if and how that request should be cached and responded to. + +Let’s add a cache fallback to our JavaScript files. The easiest way to do this +is to register a route with Workbox that will match any “.js” files that are +requested, which we can do with a regular expression: + +```javascript +workbox.routing.registerRoute(new RegExp('.*\.js'), … ); +``` + +This tells Workbox that when a request is made, it should see if the regular +expression matches part of the URL, and if it does, do something with that +request. For this guide, that “do something” is going to be passing the request +through one of Workbox’s caching strategies. + +If we want our JavaScript files to come from the network whenever possible, +but fallback to the cached version if the network fails, we can use the +“network first” strategy to achieve this. + +```javascript +workbox.routing.registerRoute(new RegExp('.*\.js'), workbox.strategies.networkFirst()); +``` + +Add this code to your service worker and refresh the page. If your web page +has JavaScript files in it, you should see some logs similar to this: + +![Example console logs from routing a JavaScript file.](../images/guides/get-started/routing-example.png) + +Workbox has routed the request for any “.js” files and used the network first +strategy to determine how to respond to the request. You can look in the +caches of DevTools to check that the request has actually been cached. + +![Example of a JavaScript file being cached.](../images/guides/get-started/cached-request.png) + +Workbox provides a few caching strategies that you can use. For example, your CSS could be served from the cache first and updated in the background or your images could be cached and used until it’s a week old, after which it’ll need updating. + +```javascript +workbox.routing.registerRoute( + // Cache CSS files + /.*\.css/, + // Use cache but update in the background ASAP + workbox.strategies.staleWhileRevalidate({ + // Use a custom cache name + cacheName: 'css-cache', + }) +); + +workbox.routing.registerRoute( + // Cache image files + /.*\.(?:png|jpg|jpeg|svg|gif)/, + // Use the cache if it's available + workbox.strategies.cacheFirst({ + // Use a custom cache name + cacheName: 'image-cache', + cacheExpiration: { + // Cache only 20 images + maxEntries: 20, + // Cache for a maximum of a week + maxAgeSeconds: 7 * 24 * 60 * 60, + } + }) +); +``` + +## What Else Can Workbox Do? + +Routing and caching strategies are performed by the `routing` and +`strategies` modules, but there are plenty of other modules, each offering +specific behaviours that you can use in your service worker. + +You'll find a number of guides that cover other features of Workbox as well +as more information on configuring Workbox. Find a full list on the left, but +the next natural step is to enable precaching, which is the process of adding +files to the cache when your service worker loads. + +Learn More About Precaching diff --git a/src/content/en/tools/workbox/v3/guides/handle-third-party-requests.md b/src/content/en/tools/workbox/v3/guides/handle-third-party-requests.md new file mode 100644 index 00000000000..bb9977a1605 --- /dev/null +++ b/src/content/en/tools/workbox/v3/guides/handle-third-party-requests.md @@ -0,0 +1,104 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: A guide on how to handle third party requests with Workbox. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Handle Third Party Requests {: .page-title } + +A lot of websites will use files from a different origin. For example, if you +use Google Fonts, you’ll be importing the styles and fonts from +`https://fonts.googleapis.com/`. Any request for a file from a different +origin is known as a cross-origin request and these requests require special +handling in Workbox. + +In this guide we are going to look at how a cross-origin request can be +different and what you can do in Workbox to support these requests. + +## Cross-Origin Requests and Opaque Responses + +One of the security mechanisms in browsers is that when a piece of JavaScript +requests a URL on a different origin, it’s not prevented from being able to +view the response. The reason for this is so websites can’t try and scan for +URLs on a user’s network. + +When you get a response like this, it’s known as an "opaque response". Some +requests can be read in JavaScript if the server returns +[CORS headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), but a +number of sites will not do this. + +In service workers you can make requests to third-parties and cache the +responses. For opaque responses the contents of the Response will still +be hidden. You can’t even check that status code of the response. Because +of this Workbox treats opaque responses differently. + +You can learn more from this +[Stackoverflow Q&A](https://stackoverflow.com/questions/39109789/what-limitations-apply-to-opaque-responses). + +## Workbox Caches Opaque Response Sometimes + +In general, Workbox will not cache opaque responses. + +The reason for this is that it’s very easy to get into a bad state. + +Let’s say a developer set up a route with a "cache first" strategy. + +```javascript +workbox.routing.registerRoute( + 'https://cdn.google.com/example-script.min.js', + workbox.strategies.cacheFirst(), +); +``` + +This response would cache the opaque response and serve it up from that point +onwards. The problem is that if that request fails for any reason, Workbox +won’t be able to detect this and will continue to serve up the broken response. +The user will be in a broken state. + +However, it’s not a bad thing to want to try and add some fault tolerance to +these requests so Workbox will allow opaque responses to be cached with the +`networkFirst` and `stalteWhileRevalidate` strategies. Since these strategies +regularly update the cached response it’s much safer to cache them as +hopefully a bad request will be short lived and used rarely. + +```javascript +workbox.routing.registerRoute( + 'https://cdn.google.com/example-script.min.js', + workbox.strategies.networkFirst(), +); + +// OR + +workbox.routing.registerRoute( + 'https://cdn.google.com/example-script.min.js', + workbox.strategies.staleWhileRevalidate(), +); + +``` + +If you use another caching strategy and an opaque response is returned, +Workbox will log a warning letting you know that the response wasn’t cached. + +![Example warning when an opaque response isn't cached.](../images/guides/third-party-requests/opaque-response-log.png) + +## Force Caching of Opaque Responses + +If you are certain that you want to cache an opquae response, you can do +so using the `CachaeablResponsePlugin`, like so: + +```javascript +workbox.routing.registerRoute( + 'https://cdn.google.com/example-script.min.js', + workbox.strategies.cacheFirst({ + cacheableResponse: { + statuses: [0, 200] + } + }), +); +``` + + diff --git a/src/content/en/tools/workbox/v3/guides/index.md b/src/content/en/tools/workbox/v3/guides/index.md new file mode 100644 index 00000000000..be7dfea2758 --- /dev/null +++ b/src/content/en/tools/workbox/v3/guides/index.md @@ -0,0 +1,17 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: TODO: Description of Guides. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Guides {: .page-title} + +Workbox offers a range of functionality and features that developers can +take advantage of. + +These guides will introduce you to the Workbox API and step through +how to use each piece of Workbox and best practices to make the most +of the libraries. + +Get Started diff --git a/src/content/en/tools/workbox/v3/guides/precache-files.md b/src/content/en/tools/workbox/v3/guides/precache-files.md new file mode 100644 index 00000000000..cd4097f2f1e --- /dev/null +++ b/src/content/en/tools/workbox/v3/guides/precache-files.md @@ -0,0 +1,8 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: A guide on how to precache files with Workbox. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Precache Files {: .page-title } diff --git a/src/content/en/tools/workbox/v3/guides/route-requests.md b/src/content/en/tools/workbox/v3/guides/route-requests.md new file mode 100644 index 00000000000..76b06f3fd3f --- /dev/null +++ b/src/content/en/tools/workbox/v3/guides/route-requests.md @@ -0,0 +1,237 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: A guide on how to route requests with Workbox. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Route Requests {: .page-title } + +Routing in Workbox is the process of a Router *matching* a request to a +route and the route then *handling* that request (i.e. providing a response). + +There are three ways developers can match a request with `workbox-routing`. + +1. A string. +1. A regular expression. +1. A callback function. + +We’ll first look at how you can matching using this three approaches and +then we’ll go on to cover the handling of a request, which is where the +`handler` variable will serve as a placeholder. + +## Matching a Route with a String + +Matching a route with a string is the easiest to understand, but also the least flexible option. + +The requests URL is compared to the routes string and if they are equal the request will use that routes handler. + +So we could define a route for '/logo.png' like so: + +```javascript +workbox.routing.registerRoute( + '/logo.png', + handler +); +``` + +The only thing to be weary of is that this would only match for requests +on your origin. If there was a seperate site what had the URL +"https://some-other-origin.com/logo.png", this route wouldn’t match, because +in most cases, that’s not what was intended. Instead you’d need to define +the entire URL to match. + +```javascript +workbox.routing.registerRoute( + 'https://some-other-origin.com/logo.png', + handler +); +``` + +## Matching a Route with a Regular Expression + +When you have a set of URLs that you want to route as a group, Regular Expressions are the best way to go. + +The regular expression needs to match part of the URL to be treated as a match for that route. This provides a lot of flexibility as to how you use it. +If we wanted to route specific file extensions we could write routes such as: + +```javascript +workbox.routing.registerRoute( + new RegExp('.*\.js'), + jsHandler +); + +workbox.routing.registerRoute( + new RegExp('.*\.css'), + cssHandler +); +``` + +Or you can write regular expressions that test for a specifc URL format, for example a blog that follows the format `/blog///`. + +```javascript +workbox.routing.registerRoute( + /\/blog\/\d\d\d\d\/\d\d\/.+/, + handler +); +``` + +Just like the string matching, requests for different origins are treated differently. Instead of needing match a part of the URL, it must match from the beginning of the URL. For example, +`https://some-other-origin.com/blog///` would +need to match against "https://some-other-origin.com" as well as the path +name. So we’d have to change our regular expression to something like the +following if we wanted to capture both same origin and third party origin +requests: + +```javascript +workbox.routing.registerRoute( + /(?:https:\/\/.*)?\/blog\/\d\d\d\d\/\d\d\/.+/, + handler +); +``` + +## Matching a Route with a Callback Function + +To allow developers to do anything they want to match a request, you can also +provide a function that can determine with a request should match a route on +any criteria it wishes. + +The callback will receive an object with the requests URL and the `FetchEvent` +received in the service worker. + +```javascript +const matchFunction = ({url, event}) => { + // Return true if the route should match + return false; +}; + +workbox.routing.registerRoute( + matchFunction, + handler +); +``` + +Now that a request can be matched with a route, it’s time to handle the request (i.e. provide a Response for the request). + +There are two ways you can handle a request: + +1. Use one of Workbox’s strategies provided by `workbox.strategies`. +1. Provide a callback function that returns a Promise that resolves to a +`Response`. + +## Handling a Route with a Workbox Strategy + +Most routes can be handled with one of the built in caching strategies. + +- Stale While Revalidate + - This strategy will use a cached response for a request if it is + available and update the cache in the background with a response form + the network. (If it’s not cached it will wait for the network response + and use that). This is a fairly safe strategy as it means users are + regularly updating their cache. The downside of this strategy is that + it’s always requesting an asset from the network, using up the user’s + bandwidth. +- Network First + - This will try and get a request from the network first. If it receives + a response, it’ll pass that to the browser and also save it to a cache. + If the network request fails, the last cached response will be used. +- Cache First + - This strategy will check the cache for a response first and use that + if one is available. If the request isn’t in the cache, the network will + be used and any valid response will be added to the cache before being + passed to the browser. +- Network Only + - Force the response to come from the network. +- Cache Only + - Force the response to come from the cache. + +Using these as your `handler` can be done like so: + +```javascript +workbox.routing.registerRoute( + match, + workbox.strategies.staleWhileRevalidate() +); + +workbox.routing.registerRoute( + match, + workbox.strategies.networkFirst() +); + +workbox.routing.registerRoute( + match, + workbox.strategies.cacheFirst() +); + +workbox.routing.registerRoute( + match, + workbox.strategies.networkOnly() +); + +workbox.routing.registerRoute( + match, + workbox.strategies.cacheOnly() +); +``` + +There are some options you can set on each strategy to customise the behavior +of a route. + +```javascript +workbox.strategies.staleWhileRevalidate({ + // Use a custom cache for this route + cacheName: 'my-cache-name', + // Force the cache to clear out the cached requests + cacheExpiration: { + // Limit the cache to storing 10 requests + maxEntries: 10, + // Don’t let a request to be cached longer than 1 hour + maxAgeSeconds: 60 * 60, + }, + // Add some plugins to provide extra behaviors + plugins: [...] +}); +``` + +These options are often needed to make it safer when caching requests +(i.e. limiting how long they are cached or making sure the data used on a +device is limited). + +## Handling a Route with a Custom Callback + +There may be scenarios where you’d like to respond to a request with a +different strategy of your own or simply generating the request in the +service worker with templating. For this you can provide a function and +it’ll be called with an object containing the request url and `FetchEvent`. + +```javascript +const handler = ({url, event}) => { + return new Response(`Custom handler response.`); +}; + +workbox.routing.registerRoute(match, handler); +``` + +One thing to note is that if you return a value in the `match` callback, +it’ll be passed into the `handler` callback as a `params` argument. + +```javascript +const match = ({url, event}) => { + return { + name: 'Workbox', + type: 'guide', + }; +}; + +const handler = ({url, event, params}) => { + // Response will be “A guide on Workbox” + return new Response( + `A ${params.type} on ${params.name}` + ); +}; + +workbox.routing.registerRoute(match, handler); +``` + +This may be helpful if there are pieces of information in the URL that can +be parsed once in the *match* callback and used in your *handler*. diff --git a/src/content/en/tools/workbox/v3/guides/troubleshoot-and-debug.md b/src/content/en/tools/workbox/v3/guides/troubleshoot-and-debug.md new file mode 100644 index 00000000000..c91ab30e1e8 --- /dev/null +++ b/src/content/en/tools/workbox/v3/guides/troubleshoot-and-debug.md @@ -0,0 +1,120 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: A guide on how to troubleshoot and debugging issues with Workbox. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Troubleshoot and Debug {: .page-title } + +Working with service workers can be challenging, especially when +starting out. This page will cover a few useful tips to help working +with service workers and help with Workbox. + +## Get to Know Your Developer Tools + +Chrome's developer tools have a number of tools to make it easier to +work with service workers. + +The most common features use are the following. + +### Update on Reload + +The "update on reload" toggle will force Chrome to check for a new service +worker every time you refresh the page. This means that any new changes will +be found on each page load. + +![image alt text](image_0.png) + +### Clear Storage + +There will come a point where you'll want to start from a claim state. +No service workers, not caching, nothing. You can clear everything with +the "Clear site data" button. + +![image alt text](image_1.png) + +## Bypass for Network + +When you aren't working with service workers at all, you can make the browser +go straight to the network (i.e. not use the service worker) with the "Bypass +for Network" toggle. + +![image alt text](image_2.png) + +You'll know what this is working because the network panel will stop showing +"(from ServiceWorker)". + +![image alt text](image_3.png) + +There are plenty more features, the above list should help as you start +working on your service worker files. +[Learn what other features exist in DevTools here](https://developers.google.com/web/tools/chrome-devtools/progressive-web-apps#service-workers). + +## Common Problems + +There are a set of problems that are common for developers to hit when +working with developers. + +**_Q:_** Why isn't my new service worker loading? + +**_A:_** The reason that you might find that your service worker isn't +loading is because it's stuck in a pending state. This is normally caused +by having multiple tabs or windows open that are using the service worker. + +You can determine if this is the case by looking under your service worker +in Application > Service Workers. + +![image alt text](image_4.png) + +You can fix this by clicking the "skipWaiting" link or by closing the extra +tabs so you only have one tab using the website (this enables the service +worker to update on a refresh). + +**_Q:_** My service worker isn't pending, but it's still no loading new changes. + +**_A:_** Browsers will actually use a cached version of a service worker if +the service worker file is served with a cache expiration header. The cached +version will only be used for up to 24 hours, but it can still be difficult +to reason with. +**The best practice is to set the cache expiration header to 0 for your service worker file**. +This forces the browser to update the service worker whenever your page loads. + +## Debugging Workbox + +If you are finding it difficult to debug what Workbox is doing there are a few +things you can do to get some extra information. + +### Use a Debug Build + +The debug builds of Workbox perform extra checks on the inputs and outputs +arguments, provide extra logging and come unminified. This should help with +debug a range of issues. + +If you are using `workbox-sw`, you just need to set the config to `debug: true` +to force Workbox to use debug builds. + +```javascript +workbox.setConfig({ + debug: true +}); +``` + +If you are using the module files directly, just swap `.prod.js` for `.dev.js`. + +### Enable 'debug' Logs + +To avoid clogging up the console with Workbox logs it has a log level feature +that by default will be set to `log` for debug builds. Changing the log level +to `debug` will result in more logs being printed to the console. + +```javascript +workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug); +``` + +## Stackoverflow + +If you are still struggling to figure out your problem try posting a question +to [Stackoverflow with the `workbox` tag](https://stackoverflow.com/questions/ask?tags=workbox). +This enables a wide audience of people to view, answer and learn from your +question. diff --git a/src/content/en/tools/workbox/v3/home.md b/src/content/en/tools/workbox/v3/home.md new file mode 100644 index 00000000000..d47f9ce8b6a --- /dev/null +++ b/src/content/en/tools/workbox/v3/home.md @@ -0,0 +1,212 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: Service Worker Libraries. + +{# wf_published_on: 2017-10-04 #} +{# wf_updated_on: 2017-10-31 #} + + + +# Workbox {: .page-title } + + + +Workbox is a collection of libraries and build tools that make it easy to +store your website’s files locally, on your users’ devices. Consider Workbox +if you want to: + +- Make your site work offline. +- Improve load performance on repeat-visits. Even if you don’t want to go +fully-offline, you can use Workbox to store and serve common files locally, +rather than from the network. + +

    Learn more

    + +
    + +## Get Started +### Choose your build tool to get started: + + + +### Not using a build tool? + +Install our command-line interface: + +``` +$ npm install workbox-cli --global + +# Generate a service worker with some smart defaults +$ workbox generate:sw +``` + +### Want to work directly in your service worker? + +We support that too with workbox-sw. + +``` +$ npm install --save workbox-sw +``` + +Then reference the file from your service worker: + +``` +importScripts('/node_modules/workbox-sw/build/workbox-sw.vX.X.X.prod.js'); +``` + +## Features + +### Easy precaching + +```javascript +importScripts('/node_modules/workbox-sw/build/workbox-sw.vX.X.X.prod.js'); + +const workboxSW = new WorkboxSW(); +workboxSW.precache([ + { + url: '/index.html', + revision: 'bb121c', + }, { + url: '/styles/main.css', + revision: 'acd123', + }, { + url: '/scripts/main.js', + revision: 'a32caa', + } +]); +``` + +### Comprehensive caching strategies + +```javascript +const workboxSW = new WorkboxSW(); +const networkFirst = workboxSW.strategies.networkFirst(); +workboxSW.router.registerRoute('/schedule', networkFirst); +``` + +- Cache only +- Cache first, falling back to network +- Cache, with network update +- Network only +- Network first, falling back to cache + +### Powerful debugging support + +Example of Workbox Logging. + +### The next version of sw-precache & sw-toolbox + +Workbox is a rethink of our previous service worker libraries with a focus on +modularity. It aims to reduce friction with a unified interface, while keeping +the overall library size small. Same great features, easier to use and +cross-browser compatible. + +## Workbox: Flexible PWA Libraries @ Chrome Dev Summit 2017 + +
    +

    In this talk, Jeff Posnick gives an overview of Workbox's support for caching +strategies, precaching, and handling navigation requests. It's filled throughout +with real-world examples of how companies like Pinterest and WIRED are using +Workbox in production.

    +
    + +
    + +
    + +
    + +## Contributors + +
    + {% include "web/tools/workbox/templates/contributors.html" %} +
    diff --git a/src/content/en/tools/workbox/v3/images/guides/configure-workbox/custom-cache-name.png b/src/content/en/tools/workbox/v3/images/guides/configure-workbox/custom-cache-name.png new file mode 100644 index 00000000000..84bf15ba29e Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/guides/configure-workbox/custom-cache-name.png differ diff --git a/src/content/en/tools/workbox/v3/images/guides/configure-workbox/debug-vs-prod.png b/src/content/en/tools/workbox/v3/images/guides/configure-workbox/debug-vs-prod.png new file mode 100644 index 00000000000..abcf93688e6 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/guides/configure-workbox/debug-vs-prod.png differ diff --git a/src/content/en/tools/workbox/v3/images/guides/configure-workbox/default-caches.png b/src/content/en/tools/workbox/v3/images/guides/configure-workbox/default-caches.png new file mode 100644 index 00000000000..f398683598b Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/guides/configure-workbox/default-caches.png differ diff --git a/src/content/en/tools/workbox/v3/images/guides/configure-workbox/welcome-message.png b/src/content/en/tools/workbox/v3/images/guides/configure-workbox/welcome-message.png new file mode 100644 index 00000000000..9a9037cb1e1 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/guides/configure-workbox/welcome-message.png differ diff --git a/src/content/en/tools/workbox/v3/images/guides/configure-workbox/workbox-core_logs.png b/src/content/en/tools/workbox/v3/images/guides/configure-workbox/workbox-core_logs.png new file mode 100644 index 00000000000..51eb041b7b9 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/guides/configure-workbox/workbox-core_logs.png differ diff --git a/src/content/en/tools/workbox/v3/images/guides/get-started/application-tab.png b/src/content/en/tools/workbox/v3/images/guides/get-started/application-tab.png new file mode 100644 index 00000000000..2cfaf2d3b0f Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/guides/get-started/application-tab.png differ diff --git a/src/content/en/tools/workbox/v3/images/guides/get-started/cached-request.png b/src/content/en/tools/workbox/v3/images/guides/get-started/cached-request.png new file mode 100644 index 00000000000..c57aea83940 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/guides/get-started/cached-request.png differ diff --git a/src/content/en/tools/workbox/v3/images/guides/get-started/hello-console.png b/src/content/en/tools/workbox/v3/images/guides/get-started/hello-console.png new file mode 100644 index 00000000000..0dc027dbcef Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/guides/get-started/hello-console.png differ diff --git a/src/content/en/tools/workbox/v3/images/guides/get-started/routing-example.png b/src/content/en/tools/workbox/v3/images/guides/get-started/routing-example.png new file mode 100644 index 00000000000..27e39d76328 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/guides/get-started/routing-example.png differ diff --git a/src/content/en/tools/workbox/v3/images/guides/get-started/yay-loaded.png b/src/content/en/tools/workbox/v3/images/guides/get-started/yay-loaded.png new file mode 100644 index 00000000000..d0113c1f4be Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/guides/get-started/yay-loaded.png differ diff --git a/src/content/en/tools/workbox/v3/images/guides/third-party-requests/opaque-response-log.png b/src/content/en/tools/workbox/v3/images/guides/third-party-requests/opaque-response-log.png new file mode 100644 index 00000000000..2da5ac1fbb2 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/guides/third-party-requests/opaque-response-log.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-core/workbox-core_logs.png b/src/content/en/tools/workbox/v3/images/modules/workbox-core/workbox-core_logs.png new file mode 100644 index 00000000000..51eb041b7b9 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-core/workbox-core_logs.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-precaching/precaching-step-1.png b/src/content/en/tools/workbox/v3/images/modules/workbox-precaching/precaching-step-1.png new file mode 100644 index 00000000000..afa37bab9fd Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-precaching/precaching-step-1.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-precaching/precaching-step-2.png b/src/content/en/tools/workbox/v3/images/modules/workbox-precaching/precaching-step-2.png new file mode 100644 index 00000000000..fefa10119b0 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-precaching/precaching-step-2.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-precaching/precaching-step-3.png b/src/content/en/tools/workbox/v3/images/modules/workbox-precaching/precaching-step-3.png new file mode 100644 index 00000000000..f3594745da2 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-precaching/precaching-step-3.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-routing/workbox-routing-diagram.png b/src/content/en/tools/workbox/v3/images/modules/workbox-routing/workbox-routing-diagram.png new file mode 100644 index 00000000000..6dd71f11a67 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-routing/workbox-routing-diagram.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-routing/workbox-routing-logs.png b/src/content/en/tools/workbox/v3/images/modules/workbox-routing/workbox-routing-logs.png new file mode 100644 index 00000000000..cd3a7e794df Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-routing/workbox-routing-logs.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-routing/workbox-routing-standard-logs.png b/src/content/en/tools/workbox/v3/images/modules/workbox-routing/workbox-routing-standard-logs.png new file mode 100644 index 00000000000..bfc111c7d1c Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-routing/workbox-routing-standard-logs.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/cache-first.png b/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/cache-first.png new file mode 100644 index 00000000000..dc85d29767c Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/cache-first.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/cache-only.png b/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/cache-only.png new file mode 100644 index 00000000000..6fedc2d8098 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/cache-only.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/network-first.png b/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/network-first.png new file mode 100644 index 00000000000..a53c5a17878 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/network-first.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/network-only.png b/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/network-only.png new file mode 100644 index 00000000000..3cd8f3318e4 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/network-only.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/stale-while-revalidate.png b/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/stale-while-revalidate.png new file mode 100644 index 00000000000..dbaaff59654 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-strategies/stale-while-revalidate.png differ diff --git a/src/content/en/tools/workbox/v3/images/modules/workbox-sw/workbox-sw-loading.png b/src/content/en/tools/workbox/v3/images/modules/workbox-sw/workbox-sw-loading.png new file mode 100644 index 00000000000..2a64d8f8b0e Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/modules/workbox-sw/workbox-sw-loading.png differ diff --git a/src/content/en/tools/workbox/v3/images/third_party/gulp-logo.svg b/src/content/en/tools/workbox/v3/images/third_party/gulp-logo.svg new file mode 100644 index 00000000000..981db61972a --- /dev/null +++ b/src/content/en/tools/workbox/v3/images/third_party/gulp-logo.svg @@ -0,0 +1,2189 @@ + + + + + + image/svg+xml + + logo-on-dark-bg + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + logo-on-dark-bg + + + + + + + + + + + + + + + + + + + + diff --git a/src/content/en/tools/workbox/v3/images/third_party/logos/forbes.png b/src/content/en/tools/workbox/v3/images/third_party/logos/forbes.png new file mode 100644 index 00000000000..97a2df0e92b Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/third_party/logos/forbes.png differ diff --git a/src/content/en/tools/workbox/v3/images/third_party/logos/iheartradio.png b/src/content/en/tools/workbox/v3/images/third_party/logos/iheartradio.png new file mode 100644 index 00000000000..316f1563c99 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/third_party/logos/iheartradio.png differ diff --git a/src/content/en/tools/workbox/v3/images/third_party/logos/pinterest.png b/src/content/en/tools/workbox/v3/images/third_party/logos/pinterest.png new file mode 100644 index 00000000000..da32b973e26 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/third_party/logos/pinterest.png differ diff --git a/src/content/en/tools/workbox/v3/images/third_party/logos/starbucks.png b/src/content/en/tools/workbox/v3/images/third_party/logos/starbucks.png new file mode 100644 index 00000000000..abd8f81852b Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/third_party/logos/starbucks.png differ diff --git a/src/content/en/tools/workbox/v3/images/third_party/logos/tinder.png b/src/content/en/tools/workbox/v3/images/third_party/logos/tinder.png new file mode 100644 index 00000000000..cb614d063ac Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/third_party/logos/tinder.png differ diff --git a/src/content/en/tools/workbox/v3/images/third_party/logos/wired.png b/src/content/en/tools/workbox/v3/images/third_party/logos/wired.png new file mode 100644 index 00000000000..87a7881e761 Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/third_party/logos/wired.png differ diff --git a/src/content/en/tools/workbox/v3/images/third_party/npm-logo.svg b/src/content/en/tools/workbox/v3/images/third_party/npm-logo.svg new file mode 100644 index 00000000000..423b074f374 --- /dev/null +++ b/src/content/en/tools/workbox/v3/images/third_party/npm-logo.svg @@ -0,0 +1,2229 @@ + + + + + + image/svg+xml + + logo-on-dark-bg + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + logo-on-dark-bg + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/content/en/tools/workbox/v3/images/third_party/webpack-logo.svg b/src/content/en/tools/workbox/v3/images/third_party/webpack-logo.svg new file mode 100644 index 00000000000..3d418fe1808 --- /dev/null +++ b/src/content/en/tools/workbox/v3/images/third_party/webpack-logo.svg @@ -0,0 +1,2182 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + logo-on-dark-bg + + + + + + + + + + + + + + + + diff --git a/src/content/en/tools/workbox/v3/images/workbox-icon192x192.png b/src/content/en/tools/workbox/v3/images/workbox-icon192x192.png new file mode 100644 index 00000000000..efbe5a447ba Binary files /dev/null and b/src/content/en/tools/workbox/v3/images/workbox-icon192x192.png differ diff --git a/src/content/en/tools/workbox/v3/modules/_toc.yaml b/src/content/en/tools/workbox/v3/modules/_toc.yaml new file mode 100644 index 00000000000..da91d0b2134 --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/_toc.yaml @@ -0,0 +1,30 @@ +toc: + +- title: Overview + path: /web/tools/workbox/v3/modules/ + +- heading: Service Worker Libraries +- title: workbox + path: /web/tools/workbox/v3/modules/workbox-sw +- title: workbox.core + path: /web/tools/workbox/v3/modules/workbox-core +- title: workbox.precaching + path: /web/tools/workbox/v3/modules/workbox-precaching +- title: workbox.routing + path: /web/tools/workbox/v3/modules/workbox-routing +- title: workbox.strategies + path: /web/tools/workbox/v3/modules/workbox-strategies +- title: workbox.expiration + path: /web/tools/workbox/v3/modules/workbox-cache-expiration +- title: workbox.backgroundSync + path: /web/tools/workbox/v3/modules/workbox-background-sync +- title: workbox.googleAnalytics + path: /web/tools/workbox/v3/modules/workbox-google-analytics + +- heading: Node Modules +- title: workbox-cli + path: /web/tools/workbox/v3/modules/workbox-cli +- title: workbox-build + path: /web/tools/workbox/v3/modules/workbox-build +- title: workbox-webpack-plugin + path: /web/tools/workbox/v3/modules/workbox-webpack-plugin diff --git a/src/content/en/tools/workbox/v3/modules/index.md b/src/content/en/tools/workbox/v3/modules/index.md new file mode 100644 index 00000000000..9b1740bb6a0 --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/index.md @@ -0,0 +1,17 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The troubleshooting and debugging guide for Workbox. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox Modules {: .page-title} + +Workbox is a set of service worker libraries and Node modules. + +The service worker libraries can be loaded and used within a service worker to +make it easy to handle network requests and take full advantage of the service +worker API's and events. + +The Node modules make it easy to precache files efficiently for +your users, a vital step to making your site work offline. diff --git a/src/content/en/tools/workbox/v3/modules/workbox-background-sync.md b/src/content/en/tools/workbox/v3/modules/workbox-background-sync.md new file mode 100644 index 00000000000..45b334f6658 --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/workbox-background-sync.md @@ -0,0 +1,12 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The module guide for workbox-background-sync. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox Background Sync {: .page-title } + +No Demo | [Reference Docs](http://localhost:8080/web/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync) + +Sorry. This module's documentation hasn't been written yet. diff --git a/src/content/en/tools/workbox/v3/modules/workbox-build.md b/src/content/en/tools/workbox/v3/modules/workbox-build.md new file mode 100644 index 00000000000..7026a080c73 --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/workbox-build.md @@ -0,0 +1,10 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The module guide for workbox-build. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox Build {: .page-title} + +Sorry. This module's documentation hasn't been written yet. diff --git a/src/content/en/tools/workbox/v3/modules/workbox-cache-expiration.md b/src/content/en/tools/workbox/v3/modules/workbox-cache-expiration.md new file mode 100644 index 00000000000..2ead84a36b7 --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/workbox-cache-expiration.md @@ -0,0 +1,112 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The module guide for workbox-cache-expiration. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox Cache Expiration {: .page-title } + +[Demo](https://workbox-demos.firebaseapp.com/demo/workbox-cache-expiration/) | [Reference Docs](http://localhost:8080/web/tools/workbox/v3/reference-docs/latest/workbox.expiration) + +## What is Cache Expiration? + +It’s fairly common to want to put restrictions on a cache in terms of how long if should allow items to be stored in a cache or how many items should be kept in a cache. Workbox provides this functionality through the `workbox-cache-expiration` plugin that allows you to limit the number of entries in a cache and / or remove entries that have been cached for a long period of time. + +## Restrict the Number of Cache Entries + +To restrict the number of entries stored in a cache you can use the `cacheExpiration` option like so: + +```javascript +workbox.routing.registerRoute( + new RegExp('/images/'), + workbox.strategies.cacheFirst({ + cacheName: 'image-cache', + cacheExpiration: { + maxEntries: 20, + }, + }) +); +``` + +With this, the [CacheExpirationPlugin](../reference-docs/latest/workbox.expiration.CacheExpirationPlugin) will be added to this route. After a cached response is used or a new request is added to the cache the plugin will look at the configured cache and ensure that the number of cached entries doesn’t exceed the limit. If it does, **the oldest entries will be removed**. + +## Restrict the Age of Cached Entries + +To restrict how long a request is cached for you can define a max age in seconds like so; + +```javascript +workbox.routing.registerRoute( + /\/images\//, + workbox.strategies.cacheFirst({ + cacheName: 'image-cache', + cacheExpiration: { + maxAgeSeconds: 20, + }, + }) +); +``` + +The plugin will check and remove entries after each request or cache update. + +One thing to note: + +- Because it’s slow to open IndexedDB, expiration won’t occur until *after* the request is used. This means that an expired request may be used once, but will be expired after that. +- To alleviate this, the plugin will check the "Date" header of the cached response, if one exists and the date can be parsed, it’ll expire based on this as it doesn’t require an IndexedDB lookup.. + +## Advanced Usage + +Above discusses the common usage of `workbox-cache-expiration` which is largely abstracted behind configuration, but you can use the underlying classes to use as a normal Workbox plugin or use the logic seperate from any other Workbox modules. + +### Using the Plugin Directly + +The plugin can be instantiated and used like so: + +```javascript +workbox.routing.registerRoute( + new RegExp('/images/'), + workbox.strategies.cacheFirst({ + cacheName: 'image-cache', + plugins: [ + new workbox.expiration.CacheExpirationPlugin({ + maxAgeSeconds: 60 * 60, + maxEntries 20, + }), + ], + }) +); +``` + +### Using Just the Cache Expiration Logic + +If you’d like to use the expiration logic separate from any other Workbox modules you can do so with the [CacheExpiration](../reference-docs/latest/workbox.expiration.CacheExpiration) class. + +To apply restrictions to a cache, you’d create an instance of CacheExpiration for the cache you want to control like so: + +```javascript +const cacheName = 'my-cache'; +const expirationManager = new workbox.expiration.CacheExpiration( + cacheName, + { + maxAgeSeconds: 60 * 60, + maxEntries 20, + } +); +``` + +Whenever you update a cached entry, you need to call the `updateTimestamp()` method so that it’s age is updated. + +```javascript +openCache.put( + request, + response +); + +expirationManager.updateTimestamp(request.url); +``` + +Then whenever you want to expire a set of entries you can call the `expireEntries()` method which will enforce the `maxAgeSeconds` and `maxEntries` configuration. + +```javascript +expirationManager.expireEntries(); +``` diff --git a/src/content/en/tools/workbox/v3/modules/workbox-cli.md b/src/content/en/tools/workbox/v3/modules/workbox-cli.md new file mode 100644 index 00000000000..e92771eb98b --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/workbox-cli.md @@ -0,0 +1,10 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The module guide for workbox-cli. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox CLI {: .page-title} + +Sorry. This module's documentation hasn't been written yet. diff --git a/src/content/en/tools/workbox/v3/modules/workbox-core.md b/src/content/en/tools/workbox/v3/modules/workbox-core.md new file mode 100644 index 00000000000..afa6a15bc96 --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/workbox-core.md @@ -0,0 +1,90 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The module guide for workbox-core. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox Core {: .page-title } + +[Demo](https://workbox-demos.firebaseapp.com/demo/workbox-core/) | [Reference Docs](http://localhost:8080/web/tools/workbox/v3/reference-docs/latest/workbox.core) + +## What is Workbox Core? + +Workbox has been built to be modular, allowing developers to select the pieces they want to use without forcing them to download everything in a single file. + +There is however overlap between modules, for example, each module will like need to interact with the console, throw meaningful errors and make use of the network or cache. To avoid each module implementing the same logic, `workbox-core` contains this common code which each module relies on. + +This module does provide some functionality to developers, but beyond log levels and caching, `workbox-core` offers internal logic to each module, rather than the end developer. + +## Change the Log Level + +Workbox uses a very thin wrapper over `console.log` so that you can filter out the Workbox messages separate from your own logic. + +![workbox-core Log Demo](../images/modules/workbox-core/workbox-core_logs.png) + +To adjust the log level, all you need to do is call `setLogLevel()` and pass in a value from `LOG_LEVELS`. + +```javascript +// The most verbose - displays all logs. +workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug); + +// Shows logs, warnings and errors. +workbox.core.setLogLevel(workbox.core.LOG_LEVELS.log); + +// Show warnings and errors. +workbox.core.setLogLevel(workbox.core.LOG_LEVELS.warn); + +// Show *just* errors +workbox.core.setLogLevel(workbox.core.LOG_LEVELS.error); + +// Silence all of the Workbox logs. +workbox.core.setLogLevel(workbox.core.LOG_LEVELS.silent); +``` + +You can see what the current log level is like so: + +```javascript +console.log(workbox.core.logLevel); +``` + +The default log level changes depending on the build type. If you use the debug build, `workbox-core.dev.js`, the log level will be set to `LOG_LEVELS.log` (i.e. it will log everything except debug messages). For production builds, `workbox-core.prod.js`, the log level will be set to `LOG_LEVELS.warn`, meaning you’ll only see warnings and errors. + +## View and Change the Default Cache Names + +Workbox defines it's caches via `workbox.core.cacheNames`: + +```javascript +console.log(workbox.core.cacheNames.precache); + +console.log(workbox.core.cacheNames.runtime); + +console.log(workbox.core.cacheNames.googleAnalytics); +``` + +These cache names are constructed in the format of a prefix, a name and suffix, where the name changes based on the use of the cache. + +`--` + +You can change these default names by altering all or some of the values passed into `setCacheNameDetails()`. + +```javascript +workbox.core.setCacheNameDetails({ + prefix: 'my-app', + suffix: 'v1', + precache: 'install-time', + runtime: 'run-time', + googleAnalytics: 'ga', +}); + +// Will print 'my-app-install-time-v1' +console.log(workbox.core.cacheNames.precache); + +// Will print 'my-app-run-time-v1' +console.log(workbox.core.cacheNames.runtime); + +// Will print 'my-app-ga-v1' +console.log(workbox.core.cacheNames.googleAnalytics); +``` + +The main use case for the prefix and suffix is that if you use Workbox for multiple projects and use the same localhost for each project, setting a custom prefix for each module will prevent the caches from conflicting with each other. diff --git a/src/content/en/tools/workbox/v3/modules/workbox-google-analytics.md b/src/content/en/tools/workbox/v3/modules/workbox-google-analytics.md new file mode 100644 index 00000000000..763aee48d76 --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/workbox-google-analytics.md @@ -0,0 +1,12 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The module guide for workbox-google-analytics. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox Google Analytics {: .page-title } +No Demo | [Reference Docs](http://localhost:8080/web/tools/workbox/v3/reference-docs/latest/workbox.googleAnalytics) + + +Sorry. This module's documentation hasn't been written yet. diff --git a/src/content/en/tools/workbox/v3/modules/workbox-precaching.md b/src/content/en/tools/workbox/v3/modules/workbox-precaching.md new file mode 100644 index 00000000000..b2d2d2d06c9 --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/workbox-precaching.md @@ -0,0 +1,164 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The module guide for workbox-core. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox Precaching {: .page-title } + +[Demo](https://workbox-demos.firebaseapp.com/demo/workbox-precaching/) | [Reference Docs](http://localhost:8080/web/tools/workbox/v3/reference-docs/latest/workbox.precaching) + +## What is Precaching? + +One feature of service workers is the ability to save a set of files to the +cache when the service worker is installing. This is often referred to as +"precaching", since you are caching content ahead of the service worker being +used. + +The main reasons for doing this is that it gives developers control over the +cache, meaning they can determine when and how long a file is cached as well +as serve it to the browser without going to the network, meaning it can be +used to create web apps that work offline. + +Workbox takes a lot of the heavy lifting out of precaching by simplifying +the API and ensuring assets are downloaded efficiently. + +## How workbox-precaching Works + +When a web app is loaded for the first time workbox-precaching will + +look at all the assets you want to download, remove any duplicates and hook +up the relevant service worker events to download and store the assets, +saving information about the revision of the asset in indexedDB. + +![Workbox precaching list to precached assets](../images/modules/workbox-precaching/precaching-step-1.png) + + workbox-precaching does all of this during the service worker's + [install event](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Install_and_activate_populating_your_cache). + +When a user later re-visits your web app and you have a new service worker with +different precached assets, workbox-precaching will look at the new list +and determine which assets are completely new and which of the existing assets +need updating, based of their revisioning. These assets will be updated in the +cache and their revision details will be updated or added to indexedDB during +this new service workers install event. + +![Workbox precaching update example](../images/modules/workbox-precaching/precaching-step-2.png) + +This new service worker won't be used until it's activated and it’s activate +event has been triggered. It’s in the activate event that workbox-precaching +will check for any old cached assets and remove them from the cache and +indexedDB. + +![Workbox precaching cleanup step](../images/modules/workbox-precaching/precaching-step-3.png) + +Precache will perform these steps each time your service worker is install +and activated, ensuring the user has the latest assets, only downloading the +files that have changed. + +## Explanation of the Precache List + +workbox-precaching expects an Array of strings or an Array of objects like so: + +```javascript +workbox.precaching.precacheAndRoute([ + '/styles/example.ac29.css', + { + url: '/index.html', + revision: 'as46', + } +]); +``` + +This list references a set of URLs, each with their own piece of "revisioning" +information. For the first item in the example above, +'/styles/example.ac29.css', the revisioning information +**is in the URL itself**. This is a best practice for web as it allows +browsers to safely cache these URLs for a long time. For assets with +revisioning like this, you can add them to the precache list as is. + +For assets where you don't have revisioning information in the URL, +**you need to add a revision property which should be a hash of the file contents**. +This allows workbox-precaching to know when the file has changed and update it. + +Workbox comes with tools to help with generating this list: + +- workbox-build + - This is an NPM module that can be used in a gulp task or as an npm + run script. +- workbox-webpack-plugin + - Webpack users can use the Workbox webpack plugin. +- workbox-cli + - Our CLI can also be used to generate the list of assets and add them + to your service worker. + +These tools make it easy to generate and use the list of assets for your site +but you can generate the list yourself, just make sure you include unique +revision properties that change whenever the file is updated. + +```javascript +// Revisioned files added via a glob +workbox.precaching.precache([ + '/styles/example-1.abcd.css', + '/styles/example-2.1234.css', + '/scripts/example-1.abcd.js', + '/scripts/example-2.1234.js', +]); + +// Precache entries from workbox-build or somewhere else +workbox.precaching.precache([ + { + url: '/index.html', + revision: 'abcd', + }, { + url: '/about.html', + revision: '1234', + } +]); + +// Add Precache Route +workbox.precaching.addRoute(); +``` + +## Advanced Usage + +By default, workbox-precaching will set up the install and activate listeners +for you. For developers familiar with service workers, this may not be +desirable and you may want finer grained control. + +Instead of using the default export, you can use the +[PrecacheController](/web/tools/workbox/v3/reference-docs/latest/workbox.precaching.PrecacheController) +to add items to the precache, determine when these assets are installed and +when cleanup should occur. + +```javascript +const precacheController = new workbox.precaching.PrecacheController(); +precacheController.addToCacheList([ + '/styles/example-1.abcd.css', + '/styles/example-2.1234.css', + '/scripts/example-1.abcd.js', + '/scripts/example-2.1234.js', +]); + +precacheController.addToCacheList([ + { + url: '/index.html', + revision: 'abcd', + }, { + url: '/about.html', + revision: '1234', + } +]); + + +self.addEventListener('install', (event) => { + event.waitUntil(precacheController.install()); +}); +self.addEventListener('activate', (event) => { + event.waitUntil(precacheController.cleanup()); +}); +self.addEventListener('fetch', (event) => { + event.respondWith(caches.match(event.request).then(...)); +}); +``` diff --git a/src/content/en/tools/workbox/v3/modules/workbox-routing.md b/src/content/en/tools/workbox/v3/modules/workbox-routing.md new file mode 100644 index 00000000000..4fd29d50e3f --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/workbox-routing.md @@ -0,0 +1,210 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The module guide for workbox-routing. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox Routing {: .page-title } + +[Demo](https://workbox-demos.firebaseapp.com/demo/workbox-routing/) | [Reference Docs](http://localhost:8080/web/tools/workbox/v3/reference-docs/latest/workbox.routing) + +## What is Workbox Routing? + +A service worker can intercept network requests for a page. It may respond to the browser with cached content,content from the network or content generated in the service worker. + +`workbox-routing` is a module which makes is easy to "route" these requests to different functions that provide responses. + +## How Routing is Performed + +When a network request causes a service worker fetch event, `workbox-routing` will attempt to respond to the request using the supplied routes and handlers. + +![Workbox Routing Diagram](../images/modules/workbox-routing/workbox-routing-diagram.png) + +The main things to note from the above is: + +- The type of request is important. + - By default, Routes are registered for 'GET' requests. If you wish to intercept other types of requests, you’ll need to specify the method. +- The order of the Route registration is important. + - If multiple Routes are registered that could handle a request, the Route that is registered first will be used to respond to the Request. + +There are a few ways to register a route, you can use callbacks, regular expressions or Route instances each of which we’ll look at next. + +## Matching and Handling in Routes + +A "route" in workbox is nothing more than two functions a “matching” function to determine if the route should match a request and a “handling” function, which should handle the request and respond with a Response. + +Workbox comes with some helpers that’ll perform the matching and handling for you, but if you ever find yourself wanting different behaviour, writing a custom match and handler function is the best option. + +A match function will be given a FetchEvent and a URL object and you can match against a request by returning a truthy value. For a simple example, you could match against a specific URL like so: + +```javascript +const matchCb = ({url, event}) => { + return (url.pathname === '/special/url'); +}; +``` + +Most use cases can be covered by examining / testing either the `url` or the `event.request` to match against a Request. + +A "handler" will be given the url and event as well and you can determine how to respond, whether it’s from the network, from the cache or generated in the service worker. + +```javascript +const handlerCb = ({url, event, params}) => { + return fetch(event.request) + .then((response) => { + return response.text(); + }) + .then((responseBody) => { + return new Response(`${responseBody} `); + }); +}; + +``` + +Your handler must return a Promise that resolves to a Response. The `params` value is is the value of any value returned by the "match" function. This may be useful is you parsed the URL or request and want to pass that values into the “handler” for a matching request. + +You can register these callbacks via like so: + +```javascript +workbox.routing.registerRoute(matchCb, handlerCb); +``` + +The only limitation is that "match" **must synchronously** return a truthy value, you can’t perform any asynchronous work. The reason for this is that the Router must synchronously respond to the fetch event or allow falling through to other fetch events. + +The "handler" callback should return a Promise that resolves to a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). Where that Response comes from is up to you, the network, a cache or generated in the service worker. + +Normally the "handler" callback would use one of the strategies provided by `workbox-runtime-caching` like so: + +```javascript +workbox.routing.registerRoute(matchCb, workbox.stratgies.staleWhileRevalidate()); +``` + +In this page we’ll focus on `workbox-routing` but you can [learn more about these strategies on workbox.strategies](./workbox-strategies). + +## How to Register a Regular Expression Route + +A common practice is to skip avoid using the "match" callback and instead use a Regular Expression to match requests. + +```javascript +workbox.routing.registerRoute(new RegExp('/styles/.*\.css'), handlerCb); +``` + +For requests from the [same origin](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy), this route will be used as long as part of the request’s URL matches the regular expression. + +- https://example.com/styles/main.css +- https://example.com/styles/nested/file.css +- https://example.com/nested/styles/directory.css + +However, for cross-origin requests, regular expressions **must match the beginning of the URL**. The reason for this is that it’s unlikely that with a regular expression `new RegExp('/styles/.*\.css')` you intended to match a third-parties CSS files. + +- https://cdn.third-party-site.com/styles/main.css +- https://cdn.third-party-site.com/styles/nested/file.css +- https://cdn.third-party-site.com/nested/styles/directory.css + +If you *did* want this behaviour, you just need to ensure that regular expression matches the beginning of the URL. If we wanted to match the requests for `https://cdn.third-party-site.com` we could use the regular expression `new RegExp('https://cdn.third-party-site.com.*/styles/.*\.css')`. + +- https://cdn.third-party-site.com/styles/main.css +- https://cdn.third-party-site.com/styles/nested/file.css +- https://cdn.third-party-site.com/nested/styles/directory.css + +If you wanted to match both local and third parties you can use a wildcard at the start of your regular expression, but this should be done with caution to ensure it doesn’t cause unexpected behaviors in you web app. + +## How to Register a Navigation Route + +If your site is a single page app, you can use a [NavigationRoute](../reference-docs/latest/workbox.routing.NavigationRoute) to return a specific response for all [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests). + +```javascript +workbox.routing.registerNavigationRoute('/single-page-app.html'); +``` + +Whenever a user goes to your site in the browser, the request for the page will be a navigation request and will be served the cached page '/single-page-app.html'. (Note: should have the page cached via `workbox-precaching` or through your own installation step). + +By default this will respond to *all* navigation requests, if you want to restrict it to respond to a subset of URL’s you can use the `whitelist` and `blacklist` options to restrict which pages will match this route. + +```javascript +workbox.routing.registerNavigationRoute('/single-page-app.html', { + whitelist: [ + new RegExp('/blog/') + ], + blacklist: [ + new RegExp('/blog/restricted/'), + ] +}); +``` + +The only thing to note is that the `blacklist` will win if a URL is in both the `whitelist` and `blacklist`. + +## Set a Default Handler + +If you want to supply a "handler" for requests that don’t match a route, you can set a default handler. + +```javascript +workbox.routing.setDefaultHandler(({url, event, params}) => { + ... +}); +``` + +## Set a Catch Handler + +In the case of any of your routes throwing an error, you can capture and degrade gracefully by setting a catch handler. + +```javascript +workbox.routing.setCatchHandler(({url, event, params}) => { + ... +}); +``` + +## Defining a Route for Non-GET Requests + +All routes by default are assumed to be for 'GET' requests. + +If you would like to route other requests, like a 'POST' request, you need to define the method when register the request, like so: + +```javascript +workbox.routing.registerRoute( + matchCb, + handlerCb, + 'POST' +); +workbox.routing.registerRoute( + new RegExp('/api/.*\.json'), + handlerCb, + 'POST' +); +``` + +## Router Logging + +You should be able to determine the flow of a request using the logs from `workbox-routing` which will highlight which URLs are being processed through Workbox. + +![Routing Logs](../images/modules/workbox-routing/workbox-routing-standard-logs.png) + +If you need more verbose information you can set the log level to `debug` to view logs on requests not handled by the Router. See our [debugging guide](../guides/how-to-troubleshoot-and-debug) for more info on setting the log level. + +![Debug and Log Routing Messages](../images/modules/workbox-routing/workbox-routing-logs.png) + +## Advanced Usage + +If you want to have more control over when the Workbox Router is given requests you can create your own [Router](../reference-docs/latest/workbox.routing.Router) instance and call it’s [handleRequest()](../reference-docs/latest/workbox.routing.Router#handleRequest) method whenever you want to use the router to respond to a request. + +```javascript +const router = new DefaultRouter(); +self.addEventListener('fetch', (event) => { + const responsePromise = router.handleRequest(event); + if (responsePromise) { + // Router found a route to handle the request + event.respondWith(responsePromise); + } else { + // No route found to handle the request + } +}); +``` + +When using the `Router` directly you will also need to use the `Route` class, or any of the extending classes to register routes. + +```javascript +const router = new DefaultRouter(); +router.registerRoute(new Route(matchCb, handlerCb)); +router.registerRoute(new RegExpRoute(new RegExp(...), handlerCb)); +router.registerRoute(new NavigationRoute(handlerCb)); +``` diff --git a/src/content/en/tools/workbox/v3/modules/workbox-strategies.md b/src/content/en/tools/workbox/v3/modules/workbox-strategies.md new file mode 100644 index 00000000000..450cd3a21e8 --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/workbox-strategies.md @@ -0,0 +1,206 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The module guide for workbox-routing. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox Strategies {: .page-title } + +[Demo](https://workbox-demos.firebaseapp.com/demo/workbox-runtime-caching/) | [Reference Docs](http://localhost:8080/web/tools/workbox/v3/reference-docs/latest/workbox.strategies) + +## What is a Workbox Runtime Caching Strategy? + +When service workers were first introduced, a set of common caching strategies +emerged. A caching strategy is a pattern that determines how a service worker +generates a response after receiving a fetch event. + +`workbox-runtime-caching` provides these caching strategies so it’s easy to +apply them in your service worker. + +We won’t go into much detail outside of the strategies supported by Workbox, +but you can [learn more in the Offline Cookbook](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/). + +## Using Strategies +In the following examples we’ll show you how to use the Workbox caching +strategies with `workbox-routing`. There are some options you can define with +each strategy that is covered in the +[Configuring Strategies section of this doc](#configuring_strategies). + +In the [Advanced Usage section](#advanced_usage) we’ll cover how you can use +the caching strategies directly without `workbox-routing`. + +### Stale-While-Revalidate + +![Stale While Revalidate Diagram](../images/modules/workbox-strategies/stale-while-revalidate.png) + +The [stale-while-revalidate ](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#stale-while-revalidate) +pattern allows you to respond the request as quickly as possible with a +cached response if available, falling back to the network request if it’s +not cached. The network request is then used to update the cache. + +This is a fairly common strategy where having the most up-to-date resource +is not vital to the application. + +```javascript +workbox.routing( + new RegExp('/images/avatars/'), + workbox.strategies.staleWhileRevaliate() +); +``` + +### Cache First (Cache Falling Back to Network) + +![Cache First Diagram](../images/modules/workbox-strategies/cache-first.png) + +Offline webapps will rely heavily on the cache, but for assets that are +non-critical and can be gradually cached, a +[cache first](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network) +is the best option. + +Requests will be fulfilled from the cache if possible, otherwise it’ll fall +back to the Network. (Note: Workbox will cache this response for the next +request). + +```javascript +workbox.routing( + new RegExp('/styles/'), + workbox.strategies.cacheFirst() +); +``` + +### Network First (Network Falling Back to Cache) + +![Network First Diagram](../images/modules/workbox-strategies/network-first.png) + +For requests that are updating frequently, the +[network first]( +https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-falling-back-to-cache) +strategy is the ideal solution. By default it will try and fetch the latest +request from the network. If the request is successful, it’ll put the response +in the cache. If the network fails to return a response, the caches response +will be used. + +```javascript +workbox.routing( + new RegExp('/social-timeline/'), + workbox.strategies.networkFirst() +); +``` + +### Network Only + +![Network Only Diagram](../images/modules/workbox-strategies/network-only.png) + +If you require specific requests to be fulfilled from the network, the +[network first](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-only) +is the strategy to use. + +```javascript +workbox.routing( + new RegExp('/admin/'), + workbox.strategies.networkOnly() +); +``` + +### Cache Only + +![Cache Only Diagram](../images/modules/workbox-strategies/cache-only.png) + +The [cache only](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-only) +strategy ensures that requests are obtained from a cache. This is less common +in workbox, but can be useful if you have your own precaching step. + +```javascript +workbox.routing( + new RegExp('/app/v2/'), + workbox.strategies.cacheOnly() +); +``` + +## Configuring Strategies + +All of the strategies allow you to configure: + +- The name of the cache to use in the strategy. +- Cache expiration restrictions to use in the strategy. +- An array of plugins that will have their life cycle methods called when + fetching and caching a request. + +### Changing the Cache Used by a Strategy +You can change the cache a strategy used by supplying a cache name. This is +useful if you want to separate out your assets to help with debugging. + +```javascript +workbox.routing.registerRoute( + new RegExp('/images/'), + workbox.strategies.cacheFirst({ + cacheName: 'image-cache' + } +); +``` + +### Setting a Cache Expiration +There may be scenarios where you want to enforce a limit of how long an +asset is cached and / or restrict the number of entries that are cached. + +To do this, you can define some `cacheExpiration` options and Workbox will +create and add a +[CacheExpirationPlugin](../reference-docs/latest/workbox.expiration.CacheExpirationPlugin) +to the strategy. + +```javascript +workbox.registerRoute( + new RegExp('/images/'), + workbox.strategies.cacheFirst({ + cacheName: 'image-cache', + cacheExpiration: { + // Only cache requests for a week + maxAgeSeconds: 7 * 24 * 60 * 60, + // Only cache 10 requests. + maxEntries: 10, + } + } +); +``` + +### Add Custom Plugins +Each strategy can have additional plugins used during fetching and caching +requests, allowing extra functionality (like the `CacheExpirationPlugin` +mentioned above. + +```javascript +const myCustomPlugin = { + cachedResponseWillBeUsed: ({cacheName,request,cachedResponse}) => {...}, + ... +}; + +workbox.registerRoute( + new RegExp('/images/'), + workbox.strategies.cacheFirst({ + plugins: [ + myCustomPlugin, + ] + } +); +``` + +## Advanced Usage + +If you want to use the strategies in your own fetch event logic you can use +use the strategy classes to run a request through a specific strategy. + +For example, to implement the stale-while-revalidate class you can do the +following: + +```javascript +self.addEventListener('fetch', (event) => { + if (event.request.url === '/') { + const staleWhileRevalidate = new workbox.strategies.StaleWhileRevalidate(); + event.respondWith(staleWhileRevalidate.handle({event})); + } +}); +``` + +You can find the list of available classes in the +[workbox-strategies reference docs](../reference-docs/latest/workbox.strategies). diff --git a/src/content/en/tools/workbox/v3/modules/workbox-sw.md b/src/content/en/tools/workbox/v3/modules/workbox-sw.md new file mode 100644 index 00000000000..8c6e9ad2275 --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/workbox-sw.md @@ -0,0 +1,83 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The module guide for workbox-sw. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox {: .page-title } + +[Demo](https://workbox-demos.firebaseapp.com/demo/workbox-sw/) | [Reference Docs](http://localhost:8080/web/tools/workbox/v3/reference-docs/latest/workbox) + +## What is Workbox SW? + +The `workbox-sw` module provide an extremely easy way to get up and running with the Workbox modules and simplifies the loading of the Workbox modules and offers some simply helper methods. + +You can use `workbox-sw` via our CDN or you use it with a set of workbox files on your own server. + +## Using Workbox SW via CDN + +The easiest way to start using this module is via the CDN. You just need to add the following to your service worker: + +```javascript +importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0-alpha.28/workbox-sw.prod.js'); +``` + +With this you’ll have the `workbox` namespace in your service worker that will provide access to all of the Workbox modules. + +```javascript +workbox.precaching.* +workbox.routing.* +etc +``` + +There is some magic that happens as you start to use the additional modules. + +When you reference a module for the first time, `workbox-sw` will detect this and load the module before making it available. You can see this happening in the network tab in DevTools. + +![Workbox Libraries Loading in DevTools](../images/modules/workbox-sw/workbox-sw-loading.png) + +These files will be cached by your browser making them available for future offline use. + +## Using Local Workbox Files Instead of CDN + +If you don’t want to use the CDN, it’s easy enough to switch to Workbox files hosted on your own domain. + +The simplest approach is to get the files via [workbox-build#getFiles()]() or from a [Github Release](https://github.com/GoogleChrome/workbox/releases) and then tell `workbox-sw` where to find these files via the `modulePathPrefix` config option. + +Let’s say you put the files under `/third_party/workbox/`, you would use them like so: + +```javascript +importScripts('/third_party/workbox/workbox-sw.js'); + +workbox.setConfig({ + modulePathPrefix: '/third_party/workbox/' +}); +``` + +With this, you’ll use only the local workbox files. + +## Force Use of Debug or Production Builds + +All of the Workbox modules come with two builds, a debug build which is contains logging and additional type checking and a production build which strips the logging and type checking. + +By default, `workbox-sw` will use the debug build for sites on localhost, but for any other origin it’ll use the production build. + +If you want to force debug or production builds you set the `debug` config option. + +```javascript +workbox.setConfig({ + debug: +}); +``` + +## Skip Waiting and Clients Claim + +Some developers want to be able to publish a new service worker and have it update and control a web page as soon as possible, skipping the default service worker lifecycle. + +If you find yourself wanting this behavior, `workbox-sw` provides some helper methods to make this easy: + +```javascript +workbox.skipWaiting(); +workbox.clientsClaim(); +``` diff --git a/src/content/en/tools/workbox/v3/modules/workbox-webpack-plugin.md b/src/content/en/tools/workbox/v3/modules/workbox-webpack-plugin.md new file mode 100644 index 00000000000..00ac8ab064c --- /dev/null +++ b/src/content/en/tools/workbox/v3/modules/workbox-webpack-plugin.md @@ -0,0 +1,10 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: The module guide for workbox-build. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Workbox Webpack Plugin {: .page-title} + +Sorry. This module's documentation hasn't been written yet. diff --git a/src/content/en/tools/workbox/v3/overview.md b/src/content/en/tools/workbox/v3/overview.md new file mode 100644 index 00000000000..4331197241f --- /dev/null +++ b/src/content/en/tools/workbox/v3/overview.md @@ -0,0 +1,146 @@ +project_path: /web/tools/_project.yaml +book_path: /web/tools/_book.yaml +description: Workbox Examples. + +{# wf_published_on: 2017-10-04 #} +{# wf_updated_on: 2017-10-04 #} + +# Overview {: .page-title } + +Workbox is a collection of libraries and build tools that make it easy to +store your website's resources locally, on your users' devices. Consider +Workbox if you want to: + +* Make your site work offline. +* Improve load performance on repeat-visits. You can use Workbox to store + and serve common resources locally, rather than from the network. + +## The technology behind Workbox + +Modern offline web apps are possible thanks to [**service workers**][sw]. +Service workers are background workers, written in JavaScript, that can +locally store all of the resources needed to run your site offline. + +[sw]: https://developers.google.com/web/fundamentals/getting-started/primers/service-workers + +You can think of a service worker as a [proxy server][proxy] that's running in +the background of your users' devices. Your site makes a request for a +resource, the service worker intercepts the request, and then decides +whether to serve a local version of the resource or to fetch a fresh version +from the network. + +[proxy]: https://en.wikipedia.org/wiki/Proxy_server + +The place where Workbox stores resources locally is called the **cache**. +The act of storing locally is called **caching**. This is because the +underlying technology that Workbox relies on is called the [Cache API][cache]. +This is completely different than [HTTP caching][http]. The main benefit +that Workbox provides over HTTP caching is that it can cache resources *before* +they're requested, whereas HTTP caching can only do so after the user goes to +a page where the resource is required. Storing resources before they're +actually required is called **precaching**. Precaching HTML documents is +one of the main ways that Workbox can improve your load performance. Rather +than going to the network for the document, Workbox just serves it from the +cache. + +[cache]: https://developer.mozilla.org/en-US/docs/Web/API/Cache +[http]: https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching + +The logic for determining whether to serve a resource from the cache or to +fetch a fresh version is called the **caching strategy** for that resource. +It's common to use different caching strategies for different types of +resources. For example: + +* For a logo that doesn't change often, you can probably serve it from the + cache. +* For a JSON file containing a user's social media feed, you probably want + to display the cached content only while you fetch the latest content. + +## What problems Workbox solves + +In short, Workbox makes it easy to create optimal service worker code. + +Manually maintaining caches is tedious and full of pitfalls. +The "core" Workbox libraries and tools make it easy to automatically +generate a service worker that correctly caches resources. + +If you need to use different caching strategies for different types of +resources, Workbox also simplifies this process. Much of the logic can be +reduced to declarative build-time configurations. The rest of it can be +abstracted away by calling the core `workbox-sw` runtime library from your +custom service worker code. + +Workbox also intelligently manages updates to precached resources. In other +words, when a resource is changed, Workbox only downloads the changed +resource and leaves the rest of the cache untouched. This is a subtle but +important optimization. Other solutions invalidate the entire cache when a +single resource is updated, causing the service worker to re-download every +resource. + +## How you use Workbox + +The general workflow for integrating Workbox into your project is: + +1. Create a configuration file telling Workbox which resources to cache. +1. Run one of the Workbox tools in your project directory before each deploy. + Workbox generates the service worker code needed for caching and updating + the resources. + +There are a few Workbox tools, each one built for a different workflow: + +* `workbox-webpack-plugin` is for webpack. +* `workbox-build` for Node-based tools like Gulp and Grunt. +* `workbox-cli` for npm scripts or for manually generating the code from + the command line. + +If you've got a simple site, it may suffice to let Workbox generate the +entire service worker for you. See [`generateSW()`][generateSW] for an +example. + +[generateSW]: /reference-docs/latest/module-workbox-build.html#.generateSW + +If you've got a complex site, chances are that you're going to need to set +up some custom routing logic. In that case, you can write a custom service +worker that injects the Workbox code into your service worker. For example, +the code that you write may look something like this: + +```javascript +importScripts('/path/to/workbox-sw.js'); // not the actual filename +const workbox = new WorkboxSW(); + +// your custom service worker logic here + +workbox.precache([]); +``` + +After running the code through a Workbox tool, the final, generated code looks +like this: + +```javascript +importScripts('/path/to/workbox-sw.js'); // not the actual filename +const workbox = new WorkboxSW(); + +// your custom service worker logic here + +workbox.precache([ + { + "url": "/index.html", + "revision": "b3e78d93b20c49d0c927050682c99df3" + }, + { + "url": "/images/hamburger.svg", + "revision": "d2cb0dda3e8313b990e8dcf5e25d2d0f" + }, +]); +``` + +See [`injectManifest()`][injectManifest] for an example. + +[injectManifest]: /reference-docs/latest/module-workbox-build.html#.injectManifest + +## Feedback + +Still not clear on what Workbox is all about? We'd love to hear your +thoughts. [Please open an issue on our docs repo][feedback] and tell us more. + +[feedback]: https://github.com/GoogleChrome/workbox-microsite/issues/new?title=[Overview] diff --git a/src/content/en/tools/workbox/v3/reference-docs/_toc.yaml b/src/content/en/tools/workbox/v3/reference-docs/_toc.yaml new file mode 100644 index 00000000000..043167ac471 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/_toc.yaml @@ -0,0 +1,32 @@ +toc: + +- title: "Overview" + path: /web/tools/workbox/v3/reference-docs/ + +- heading: Service Worker Libraries +- title: "workbox" + path: /web/tools/workbox/v3/reference-docs/latest/workbox +- title: "workbox.core" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.core +- title: "workbox.precaching" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.precaching +- title: "workbox.routing" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.routing +- title: "workbox.strategies" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.strategies +- title: "workbox.expiration" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.expiration +- title: "workbox.backgroundSync" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync +- title: "workbox.googleAnalytics" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.googleAnalytics + +- heading: Node Modules +- title: workbox-build + path: /web/tools/workbox/v3/reference-docs/latest/module-workbox-build +- title: workbox-webpack-plugin + path: /web/tools/workbox/v3/reference-docs/latest/module-workbox-webpack-plugin + +- heading: Reference +- title: "View Full API" + path: /web/tools/workbox/v3/reference-docs/latest/index-all diff --git a/src/content/en/tools/workbox/v3/reference-docs/index.md b/src/content/en/tools/workbox/v3/reference-docs/index.md new file mode 100644 index 00000000000..12fa5e51180 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/index.md @@ -0,0 +1,16 @@ +project_path: /web/tools/workbox/v3/_project.yaml +book_path: /web/tools/workbox/v3/_book.yaml +description: Reference docs for Workbox. + +{# wf_updated_on: 2017-11-06 #} +{# wf_published_on: 2017-11-06 #} + +# Reference Docs {: .page-title} + +You can view the available API's for the Workbox service worker libraries and +node modules by selecting the appropriate link on the left. + +
    diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/_toc.yaml b/src/content/en/tools/workbox/v3/reference-docs/latest/_toc.yaml new file mode 100644 index 00000000000..328e18df382 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/_toc.yaml @@ -0,0 +1,49 @@ +toc: +- title: "CacheExpiration" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.expiration.CacheExpiration +- title: "CacheExpirationPlugin" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.expiration.CacheExpirationPlugin +- title: "CacheFirst" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.strategies.CacheFirst +- title: "CacheOnly" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.strategies.CacheOnly +- title: "NavigationRoute" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.routing.NavigationRoute +- title: "NetworkFirst" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.strategies.NetworkFirst +- title: "NetworkOnly" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.strategies.NetworkOnly +- title: "PrecacheController" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.precaching.PrecacheController +- title: "Queue" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync.Queue +- title: "QueuePlugin" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync.QueuePlugin +- title: "RegExpRoute" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.routing.RegExpRoute +- title: "Route" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.routing.Route +- title: "Router" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.routing.Router +- title: "StaleWhileRevalidate" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.strategies.StaleWhileRevalidate +- title: "workbox" + path: /web/tools/workbox/v3/reference-docs/latest/workbox +- title: "workbox.backgroundSync" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync +- title: "workbox.core" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.core +- title: "workbox.expiration" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.expiration +- title: "workbox.googleAnalytics" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.googleAnalytics +- title: "workbox.precaching" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.precaching +- title: "workbox.routing" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.routing +- title: "workbox.strategies" + path: /web/tools/workbox/v3/reference-docs/latest/workbox.strategies +- title: "WorkboxWebpackPlugin" + path: /web/tools/workbox/v3/reference-docs/latest/module-workbox-webpack-plugin-WorkboxWebpackPlugin +- title: "Index of all" + path: /web/tools/workbox/v3/reference-docs/latest/index-all diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/global.html b/src/content/en/tools/workbox/v3/reference-docs/latest/global.html new file mode 100644 index 00000000000..c869e1b4c69 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/global.html @@ -0,0 +1,287 @@ + + + + + + + + Globals + + + + +
    +
    +
    +
    +

    Globals

    +
    +

    Properties

    +
    +

    askConfigLocation

    +
    constant
    +

    +

    Copyright 2017 Google Inc.

    +

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    +
    http://www.apache.org/licenses/LICENSE-2.0
    +

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for + the specific language governing permissions and limitations under the License.

    +
    +
    +

    assert

    +
    constant
    +

    +

    Copyright 2017 Google Inc.

    +

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    +
    http://www.apache.org/licenses/LICENSE-2.0
    +

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for + the specific language governing permissions and limitations under the License.

    +
    +
    +

    assert

    +
    constant
    +

    +

    Copyright 2017 Google Inc.

    +

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    +
    http://www.apache.org/licenses/LICENSE-2.0
    +

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for + the specific language governing permissions and limitations under the License.

    +
    +
    +

    assert

    +
    constant
    +

    +

    Copyright 2017 Google Inc.

    +

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    +
    http://www.apache.org/licenses/LICENSE-2.0
    +

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for + the specific language governing permissions and limitations under the License.

    +
    +
    +

    assert

    +
    constant
    +

    +

    Copyright 2017 Google Inc.

    +

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    +
    http://www.apache.org/licenses/LICENSE-2.0
    +

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for + the specific language governing permissions and limitations under the License.

    +
    +
    +

    assert

    +
    constant
    +

    +

    Copyright 2017 Google Inc.

    +

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    +
    http://www.apache.org/licenses/LICENSE-2.0
    +

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for + the specific language governing permissions and limitations under the License.

    +
    +
    +

    chalk

    +
    constant
    +

    +

    Copyright 2017 Google Inc.

    +

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    +
    http://www.apache.org/licenses/LICENSE-2.0
    +

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for + the specific language governing permissions and limitations under the License.

    +
    +
    +

    fse

    +
    constant
    +

    +

    Copyright 2017 Google Inc.

    +

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    +
    http://www.apache.org/licenses/LICENSE-2.0
    +

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for + the specific language governing permissions and limitations under the License.

    +
    +
    +

    meow

    +
    constant
    +

    +

    Copyright 2017 Google Inc.

    +

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    +
    http://www.apache.org/licenses/LICENSE-2.0
    +

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for + the specific language governing permissions and limitations under the License.

    +
    +
    +

    ol

    +
    constant
    +

    +

    Copyright 2017 Google Inc.

    +

    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

    +
    http://www.apache.org/licenses/LICENSE-2.0
    +

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for + the specific language governing permissions and limitations under the License.

    +
    +
    +

    readFileFn

    +

    +

    Use the compiler.inputFileSystem._readFile method instead of fs.readFile, + readFile is configured to use compiler.inputFileSystem._readFile during the run phase of the webpack compilation lifecycle by passing the function to the setReadFile function.

    +
    +
    +

    timestamp

    +

    +

    Gets the private _timestamp property.

    +
    +
    Returns
    +
    +

    number 

    +
    +
    +
    +

    Methods

    +
    +

    askQuestion

    +
    async
    +

    askQuestion() returns Promise containing Object

    +
    +
    Returns
    +
    +

    Promise containing Object The answers from inquirer.

    +
    +
    +

    askQuestion

    +

    askQuestion() returns Promise containing Object

    +
    +
    Returns
    +
    +

    Promise containing Object The answers from inquirer.

    +
    +
    +

    askQuestion

    +

    askQuestion() returns Promise containing Object

    +
    +
    Returns
    +
    +

    Promise containing Object The answers from inquirer.

    +
    +
    +

    askQuestion

    +
    async
    +

    askQuestion(globDirectory) returns Promise containing Object

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    globDirectory

    +
    +

    string

    +

    The directory used for the root of globbing.

    +
    +
    +
    +
    Returns
    +
    +

    Promise containing Object The answers from inquirer.

    +
    +
    +

    fromRequest

    +
    async
    +

    fromRequest(request) returns Promise containing StorableRequest

    +

    Converts a Request object to a plain object that can be structured cloned or JSON-stringified.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    request

    +
    +

    Request

    +
    +
    +
    +
    Returns
    +
    +

    Promise containing StorableRequest 

    +
    +
    +

    getAllFileExtensions

    +
    async
    +

    getAllFileExtensions(globDirectory) returns Promise containing Array of string

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    globDirectory

    +
    +

    string

    +

    The directory used for the root of globbing.

    +
    +
    +
    +
    Returns
    +
    +

    Promise containing Array of string The unique file extensions corresponding to all of the files under globDirectory.

    +
    +
    +

    getSubdirectories

    +
    async
    +

    getSubdirectories() returns Promise containing Array of string

    +
    +
    Returns
    +
    +

    Promise containing Array of string The subdirectories of the current working directory, with hidden and ignored ones filtered out.

    +
    +
    +

    toObject

    +

    toObject() returns Object

    +

    Coverts this instance to a plain Object.

    +
    +
    Returns
    +
    +

    Object 

    +
    +
    +

    toRequest

    +

    toRequest() returns Request

    +

    Converts this instance to a Request.

    +
    +
    Returns
    +
    +

    Request 

    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/index-all.html b/src/content/en/tools/workbox/v3/reference-docs/latest/index-all.html new file mode 100644 index 00000000000..935eca4c525 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/index-all.html @@ -0,0 +1,112 @@ + + + + + + + + Index All + + + + +
    +
    +
    + +
    + +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/index.html b/src/content/en/tools/workbox/v3/reference-docs/latest/index.html new file mode 100644 index 00000000000..b53f8c09133 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/index.html @@ -0,0 +1,618 @@ + + + + + + + + Overview + + + + +
    +
    +
    + +
    +
    +
    +
    +

    module

    +
    +
    +

    + module.exports +

    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +

    workbox-webpack-plugin

    +
    + +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    workbox-webpack-plugin~WorkboxWebpackPlugin

    + +
    +
    +
    + +
    +
    +
    +

    workbox.backgroundSync

    +
    + +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +

    workbox.backgroundSync.QueuePlugin

    + +
    +
    +
    + +
    +
    +
    +

    workbox.expiration

    +
    + +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    +

    workbox.expiration.CacheExpirationPlugin

    + +
    +
    +
    +
    +

    workbox.googleAnalytics

    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +

    workbox.routing.NavigationRoute

    + +
    +
    +
    +
    +

    workbox.routing.RegExpRoute

    + +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +

    workbox.strategies.CacheFirst

    + +
    +
    +
    +
    +

    workbox.strategies.CacheOnly

    + +
    +
    +
    +
    +

    workbox.strategies.NetworkFirst

    + +
    +
    +
    +
    +

    workbox.strategies.NetworkOnly

    + +
    +
    +
    +
    +

    workbox.strategies.StaleWhileRevalidate

    + +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/jsdoc.css b/src/content/en/tools/workbox/v3/reference-docs/latest/jsdoc.css new file mode 100644 index 00000000000..1deb9cd5994 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/jsdoc.css @@ -0,0 +1,71 @@ + +.label { + font-style: italic; + text-transform: uppercase; +} + +.dl-compact dt { + margin:8px 0px 0px 0px; +} + +h1.devsite-page-title { + display: none; +} + +h1 { + margin-bottom: 8px; +} + +h2 { + margin: 48px 0px 0px 0px; +} + +h3.symbol-name { + margin: 32px 0px 8px 0px; +} + +h3.class-list:first-child { + display: block; + margin: 16px 0px 0px 0px; +} + +h3.class-list { + display: block; + margin: 12px 0px 0px 0px; + font-size: 16px; +} + +h3.class-list + p { + margin: 0px 0px 0px 0px; +} + +h4 { + margin: 8px 0px 0px 0px; +} + +td p { + margin: 6px 0px 0px 0px; +} + +p.type-signature { + font-family: 'Roboto Mono', monospace; + font-size: 80%; + font-style: normal; + font-variant: normal; + font-weight: 500; + font-stretch: normal; + line-height: normal; + margin-top: 0px; +} + +p.symbol-index-name { + margin: 8px 0px 0px 0px; +} + +h2.symbol-header { + margin: 36px 0px 0px 0px; +} + +table.function.param tr { + background: #80A7B9; +} diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/module-workbox-build.html b/src/content/en/tools/workbox/v3/reference-docs/latest/module-workbox-build.html new file mode 100644 index 00000000000..eeebdb44829 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/module-workbox-build.html @@ -0,0 +1,687 @@ + + + + + + + + Module: workbox-build + + + + +
    +
    +
    +
    + +
    +

    Methods

    +
    +

    copyWorkboxLibraries

    +
    static
    +

    copyWorkboxLibraries(destDirectory) returns Promise containing string

    +

    This copies over a set of runtime libraries used by Workbox into a local directory, which should be deployed alongside your service worker file.

    +

    As an alternative to deploying these local copies, you could instead use Workbox from its official CDN URL.

    +

    This method is exposed for the benefit of developers using + injectManifest() who would prefer not to use the CDN copies of Workbox. Developers using + generateSW() don't need to explicitly call this method, as it's called automatically when + importWorkboxFromCDN is set to false.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    destDirectory

    +
    +

    string

    +

    The path to the parent directory under which the new directory of libraries will be created.

    +
    +
    +
    +
    Returns
    +
    +

    Promise containing string The name of the newly created directory.

    +
    +
    +

    generateSW

    +
    async   static
    +

    generateSW(input) returns Promise containing {count: Number, size: Number}

    +

    This method creates a list of URLs to precache, referred to as a "precache manifest", based on the options you provide.

    +

    It also takes in additional options that configures the service worker's behavior, like any runtimeCaching rules it should use.

    +

    Based on the precache manifest and the additional configuration, it writes a ready-to-use service worker file to disk at swDest.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    input

    +
    +

    Object

    +
    +
    +
    +
    Returns
    +
    +

    Promise containing {count: Number, size: Number} A promise that resolves once the service worker file has been written to swDest. The size property contains the aggregate size of all the precached + entries, in bytes, and the + count property contains the total number of precached entries.

    +
    +
    +

    generateSWString

    +
    async   static
    +

    generateSWString(input) returns Promise containing String

    +

    This method generates a service worker based on the configuration options provided. +

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    input

    +
    +

    Object

    +
    +
    +
    +
    Returns
    +
    +

    Promise containing String A populated service worker template, based on the other configuration options provided.

    +
    +
    +

    getManifest

    +
    async   static
    +

    getManifest(input) returns Promise containing {manifestEntries: Array of ManifestEntry, count: Number, size: Number}

    +

    This method returns a list of URLs to precache, referred to as a "precache manifest", along with details about the number of entries and their size, based on the options you provide.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    input

    +
    +

    Object

    +
    +
    +
    +
    Returns
    +
    +

    Promise containing {manifestEntries: Array of ManifestEntry, count: Number, size: Number} A promise that resolves once the precache manifest is determined. The size property contains the aggregate size + of all the precached entries, in bytes, the count property contains the total number of precached entries, and the manifestEntries property contains all the ManifestEntry items.

    +
    +
    +

    injectManifest

    +
    async   static
    +

    injectManifest(input) returns Promise containing {count: Number, size: Number}

    +

    This method creates a list of URLs to precache, referred to as a "precache manifest", based on the options you provide.

    +

    The manifest is injected into the swSrc file, and the regular expression + injectionPointRegexp determines where in the file the manifest should go.

    +

    The final service worker file, with the manifest injected, is written to disk at swDest.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    input

    +
    +

    Object

    +
    +
    +
    +
    Returns
    +
    +

    Promise containing {count: Number, size: Number} A promise that resolves once the service worker file has been written to swDest. The size property contains the aggregate size of all the precached + entries, in bytes, and the + count property contains the total number of precached entries.

    +
    +
    +
    +

    Abstract types

    +
    +

    Configuration

    +
    static
    +

    Object

    +

    These are the full set of options that could potentially be used to configure one of the build tools. Each of the build tools has a slightly different way of providing this configuration:

    +
      +
    • +

      When using the workbox-build module directly, pass the configuration object to appropriate method. For example, + workboxBuild.injectManifest(configuration) or + workboxBuild.generateSW(configuration).

      +
    • +
    • +

      When using the workbox-cli command line interface, use the + --config-file flag to point to a + CommonJS module file that assigns the configuration object to module.exports.

      +
    • +
    • +

      When using workbox-webpack-plugin within a + Webpack build, pass the configuration object to the plugin's constructor, like + new WorkboxBuildWebpackPlugin(configuration).

      +
    • +
    +

    Some specific options might not make sense with certain combinations of interfaces. In those cases, the limitations are called out in the documentation, and may lead to build-time warnings or errors.

    +

    Each option documented here includes an example, which, for the sake of illustration, assumes the following local filesystem setup. Please adjust the example values to match your actual setup.

    +
    ./
    +├── dev/
    +│   ├── app.js
    +│   ├── ignored.html
    +│   ├── image.png
    +│   ├── index.html
    +│   ├── main.css
    +│   ├── sw.js
    +│   └── templates/
    +│       └── app_shell.hbs
    +└── dist/
    +    ├── app.js
    +    ├── image.png
    +    ├── index.html
    +    ├── main.css
    +    └── sw.js
    +
    +

    Properties

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    swDest

    +
    +

    String

    +

    The path to the final service worker file that will be created by the build process, relative to the current working directory.

    +

    E.g.: './dist/sw.js'

    +

    Note: This option is only valid when used with + generateSW() or + injectManifest().

    +
    +

    swSrc

    +
    +

    String

    +

    The path to the source service worker containing a precache([]) placeholder, which will be replaced with the precache manifest generated by the build.

    +

    E.g.: './dev/sw.js'

    +

    Note: This option is only valid when used with + injectManifest().

    +
    +

    swTemplate

    +
    +

    String

    +

    A service worker template that should be populated based on the configuration provided. The template should be in a format that lodash.template understands. +

    +

    Note: This option is only valid when used with generateSWNoFS(). +

    +
    +

    importWorkboxFromCDN

    +
    +

    Optional

    +

    boolean

    +

    If true, the WorkboxSW runtime will be automatically imported into the generated service worker from the official CDN URL. If false, the WorkboxSW runtime will be copied locally into your swDest directory when using + generateSW(). If process.env.NODE_ENV is set to a string starting with dev then the + dev bundle of WorkboxSW, with additional assertions and debugging info, will be used; otherwise, the prod bundle will be used.

    +

    Note: This option is only valid when used with + generateSW() or generateSWNoFS(). +

    +
    +

    importScripts

    +
    +

    Optional

    +

    Array of String

    +

    An optional list of JavaScript files that should be passed to + importScripts() inside the generated service worker file.

    +

    Note: This option is only valid when used with + generateSW() or generateSWNoFS(). +

    +
    +

    globPatterns

    +
    +

    Optional

    +

    Array of String

    +

    Files matching against any of these + glob patterns will be included in the precache manifest.

    +

    E.g.: '**\/*.{js,css,html,png}'

    +
    +

    globDirectory

    +
    +

    String

    +

    The base directory you wish to match globPatterns against, related to the current working directory.

    +

    E.g.: './dev'

    +
    +

    globIgnores

    +
    +

    Optional

    +

    (String or Array of String)

    +

    Files matching against any of these glob patterns will be excluded from the file manifest, overriding any matches from globPatterns.

    +

    E.g. ['**\/ignored.html']

    +
    +

    templatedUrls

    +
    +

    Optional

    +

    Object with (Array or string) properties

    +

    If a URL is rendered generated based on some server-side logic, its contents may depend on multiple files or on some other unique string value.

    +

    If used with an array of strings, they will be interpreted as + glob patterns, and the contents of any files matching the patterns will be used to uniquely version the URL.

    +

    If used with a single string, it will be interpreted as unique versioning information that you've generated out of band for a given URL.

    +

    E.g.

    +
    {
    +  '/app-shell': [
    +    'dev/templates/app-shell.hbs',
    +    'dev/**\/*.css',
    +   ],
    +  '/other-page': 'my-version-info',
    +}
    +
    +

    maximumFileSizeToCacheInBytes

    +
    +

    Optional

    +

    number

    +

    This value can be used to determine the maximum size of files that will be precached. This prevents you from inadvertantly precaching very large files that might have been accidentally match your globPatterns values.

    +
    +

    manifestTransforms

    +
    +

    Optional

    +

    Array of ManifestTransform

    +

    An array of manifest transformations, which will be applied sequentially against the generated manifest. If modifyUrlPrefix or dontCacheBustUrlsMatching are also specified, their corresponding transformations + will be applied first.

    +

    See ManifestTransform.

    +
    +

    modifyUrlPrefix

    +
    +

    Optional

    +

    Object with String properties

    +

    A mapping of prefixes that, if present in an entry in the precache manifest, will be replaced with the corresponding value.

    +

    This can be used to, for example, remove or add a path prefix from a manifest entry if your web hosting setup doesn't match your local filesystem setup.

    +

    As an alternative with more flexibility, you can use the manifestTransforms option and provide a function that modifies the entries in the manifest using whatever logic you provide.

    +

    E.g.

    +
    {
    +  '/prefix-to-remove': '',
    +}
    +
    +

    dontCacheBustUrlsMatching

    +
    +

    Optional

    +

    RegExp

    +

    Assets that match this regex will be assumed to be uniquely versioned via their URL, an exempted from the normal HTTP cache-busting that's done when populating the precache.

    +

    While not required, it's recommended that if your existing build process already inserts a [hash] value into each filename, you provide a RegExp that will detect those values, as it will reduce the amount of bandwidth + consumed when precaching.

    +

    E.g. /\.\w{8}\./

    +
    +

    navigateFallback

    +
    +

    Optional

    +

    String

    +

    This will be used to create a + NavigationRoute that will respond to navigation requests for URLs that that aren't precached.

    +

    This is meant to be used in a + Single Page App scenario, in which you want all navigations to result in common App Shell HTML being reused.

    +

    It's not intended for use as a fallback that's displayed when the browser is offline.

    +

    Note: This option is only valid when used with generateSW(). When using + injectManifest(), you can explicitly add in a call to registerNavigationRoute() in your swSrc file.

    +

    E.g. '/app-shell'

    +
    +

    navigateFallbackWhitelist

    +
    +

    Optional

    +

    Array of RegExp

    +

    An optional array of regular expressions that restrict which URLs the navigation route applies to.

    +

    Note: This option is only valid when used with generateSW(). When using + injectManifest(), you can explicitly add in the whitelist when calling registerNavigationRoute() in your swSrc file.

    +

    E.g. [/pages/, /articles/]

    +
    +

    cacheId

    +
    +

    Optional

    +

    String

    +

    An optional ID to be prepended to caches used by workbox-sw. This is primarily useful for local development where multiple sites may be served from the same http://localhost origin.

    +

    Note: This option is only valid when used with generateSW(). When using + injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file. +

    +

    E.g. 'my-app-name'

    +
    +

    skipWaiting

    +
    +

    Optional

    +

    Boolean

    +

    Whether or not the service worker should skip over the waiting lifecycle stage.

    +

    Note: This option is only valid when used with generateSW(). When using + injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file. +

    +
    +

    clientsClaim

    +
    +

    Optional

    +

    Boolean

    +

    Whether or not the service worker should start controlling any existing clients as soon as it activates.

    +

    Note: This option is only valid when used with generateSW(). When using + injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file. +

    +
    +

    directoryIndex

    +
    +

    Optional

    +

    string

    +

    If a request for a URL ending in '/' fails, this value will be appended to the URL and a second request will be made.

    +

    This should be configured to whatever your web server is using, if anything, for its directory index.

    +

    Note: This option is only valid when used with generateSW(). When using + injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file. +

    +
    +

    runtimeCaching

    +
    +

    Optional

    +

    Array of Object

    +

    Passing in an array of objects containing urlPatterns, handlers, and potentially options that will add the appropriate code to the generated service worker to handle runtime caching. +

    +

    Requests for precached URLs that are picked up via globPatterns are handled by default, and don't need to be accomodated in runtimeCaching.

    +

    The handler values correspond the names of the strategies supported by workbox-sw.

    +

    Note: This option is only valid when used with generateSW(). When using + injectManifest(), you can explicitly add in the corresponding runtime caching behavior via registerRoute() in your + swSrc file.

    +

    E.g.

    +
    [{
    +  // You can use a RegExp as the pattern:
    +  urlPattern: /.jpg$/,
    +  handler: 'cacheFirst',
    +  // Any options provided will be used when
    +  // creating the caching strategy.
    +  options: {
    +    cacheName: 'image-cache',
    +    cacheExpiration: {
    +      maxEntries: 10,
    +    },
    +  },
    +}, {
    +  // You can also use Express-style strings:
    +  urlPattern: 'https://example.com/path/to/:file',
    +  handler: 'staleWhileRevalidate',
    +  options: {
    +    cacheableResponse: {
    +         statuses: [0],
    +    },
    +  },
    +}]
    +
    +

    ignoreUrlParametersMatching

    +
    +

    Optional

    +

    Array of RegExp

    +

    Any search parameter names that match against one of the regex's in this array will be removed before looking for a precache match.

    +

    This is useful if your users might request URLs that contain, for example, URL parameters used to track the source of the traffic. Those URL parameters would normally cause the cache lookup to fail, since the URL strings used as + cache keys would not be expected to include them.

    +

    You can use [/./] to ignore all URL parameters.

    +

    Note: This option is only valid when used with generateSW(). When using + injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file. +

    +

    E.g. [/homescreen/]

    +
    +

    handleFetch

    +
    +

    Optional

    +

    Boolean

    +

    Whether or not workbox-sw should create a fetch event handler that responds to network requests. This is useful during development if you don't want the service worker serving stale content. +

    +

    Note: This option is only valid when used with generateSW(). When using + injectManifest(), you can explicitly pass the desired value in to the WorkboxSW() constructor in your swSrc file. +

    +
    +
    +
    +
    +

    ManifestEntry

    +
    static
    +

    Object

    +
    +

    Properties

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    url

    +
    +

    String

    +

    The URL to the asset in the manifest.

    +
    +

    revision

    +
    +

    String

    +

    The revision details for the file. This is a hash generated by node based on the file contents.

    +
    +
    +
    +
    +

    ManifestTransform

    +
    static
    +

    ManifestTransform(manifestEntries) returns Array of ManifestEntry

    +

    A ManifestTransform function can be used to modify the modify the url or + revision properties of some or all of the ManifestEntries in the manifest.

    +

    Deleting the revision property of an entry will cause the corresponding url to be precached without cache-busting parameters applied, which is to say, it implies that the URL itself contains proper versioning info. + If the revision property is present, it must be set to a string.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    manifestEntries

    +
    +

    Array of ManifestEntry

    +

    The full array of entries, prior to the current transformation.

    +
    +
    +
    +
    Returns
    +
    +

    Array of ManifestEntry The array of entries with the transformation applied. +

    +
    +
    +
    +

    + Examples +

    +
    +
    <caption>A transformation that prepended the origin of a CDN for any
    +URL starting with '/assets/' could be implemented as:</caption>
    +
    +const cdnTransform = (manifestEntries) => manifestEntries.map(entry => {
    +  const cdnOrigin = 'https://example.com';
    +  if (entry.url.startsWith('/assets/')) {
    +    entry.url = cdnOrigin + entry.url;
    +  }
    +  return entry;
    +});
    +
    +
    +
    <caption>A transformation that removes the revision field when the
    +URL contains an 8-character hash surrounded by '.', indicating that it
    +already contains revision information:</caption>
    +
    +const removeRevisionTransform = (manifestEntries) => {
    +  return manifestEntries.map(entry => {
    +    const hashRegExp = /\.\w{8}\./;
    +    if (entry.url.match(hashRegExp)) {
    +      delete entry.revision;
    +    }
    +    return entry;
    +  });
    +};
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/module-workbox-webpack-plugin-WorkboxWebpackPlugin.html b/src/content/en/tools/workbox/v3/reference-docs/latest/module-workbox-webpack-plugin-WorkboxWebpackPlugin.html new file mode 100644 index 00000000000..86211542477 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/module-workbox-webpack-plugin-WorkboxWebpackPlugin.html @@ -0,0 +1,122 @@ + + + + + + + + Class: WorkboxWebpackPlugin + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    WorkboxWebpackPlugin

    +

    new WorkboxWebpackPlugin(config) +

    +

    Creates an instance of WorkboxWebpackPlugin.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    config

    +
    +

    Optional

    +

    module:workbox-build.Configuration

    +

    All the options as passed to module:workbox-build.generateSWString.

    +

    Values in config have the following properties:

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    chunks

    +
    +

    Optional

    +

    Array of String

    +

    Array of chunk names to use for generating the asset manifest. All assets belonging to the provided chunk names will be included in the asset manifest. Any chunks that are not listed or do not have a name will be removed.

    +
    +

    excludeChunks

    +
    +

    Optional

    +

    Array of String

    +

    Array of chunk names to exclude from the asset manifest. Any asset beloning to the provided chunk names will not be included in the asset manifest. This does not affect chunks with no chunk name.

    +
    +

    filename

    +
    +

    Optional

    +

    string

    +

    Name of the service worker file

    +
    +

    manifestFilename

    +
    +

    Optional

    +

    string

    +

    Name of the manifest file that will be written to the build directory

    +
    +

    swSrc

    +
    +

    Optional

    +

    string

    +

    Path to an existing service worker file. Will be added to the webpack compilation and prepended with importScripts('workbox-sw.js', 'file-manifest.js')

    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/module-workbox-webpack-plugin.html b/src/content/en/tools/workbox/v3/reference-docs/latest/module-workbox-webpack-plugin.html new file mode 100644 index 00000000000..d1226ccf1f5 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/module-workbox-webpack-plugin.html @@ -0,0 +1,38 @@ + + + + + + + + Module: workbox-webpack-plugin + + + + +
    +
    +
    +
    + +
    +

    Class

    + +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_Queue.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_Queue.mjs.html new file mode 100644 index 00000000000..892967cc82f --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_Queue.mjs.html @@ -0,0 +1,240 @@ + + + + + + + + Source: workbox-background-sync/Queue.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2017 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
    +import {QueueStore} from './models/QueueStore.mjs';
    +import StorableRequest from './models/StorableRequest.mjs';
    +import {TAG_PREFIX, MAX_RETENTION_TIME} from './utils/constants.mjs';
    +import './_version.mjs';
    +
    +const queueNames = new Set();
    +
    +
    +/**
    + * A class to manage storing failed requests in IndexedDB and retrying them
    + * later. All parts of the storing and replaying process are observable via
    + * callbacks.
    + *
    + * @memberof workbox.backgroundSync
    + */
    +class Queue {
    +  /**
    +   * Creates an instance of Queue with the given options
    +   *
    +   * @param {string} name The unique name for this queue. This name must be
    +   *     unique as it's used to register sync events and store requests
    +   *     in IndexedDB specific to this instance. An error will be thrown if
    +   *     a duplicate name is detected.
    +   * @param {Object} [options]
    +   * @param {Object} [options.callbacks] Callbacks to observe the lifecycle of
    +   *     queued requests. Use these to respond to or modify the requests
    +   *     during the replay process.
    +   * @param {function(StorableRequest):undefined}
    +   *     [options.callbacks.requestWillEnqueue]
    +   *     Invoked immediately before the request is stored to IndexedDB. Use
    +   *     this callback to modify request data at store time.
    +   * @param {function(StorableRequest):undefined}
    +   *     [options.callbacks.requestWillReplay]
    +   *     Invoked immediately before the request is re-fetched. Use this
    +   *     callback to modify request data at fetch time.
    +   * @param {function(Array&lt;StorableRequest>):undefined}
    +   *     [options.callbacks.queueDidReplay]
    +   *     Invoked after all requests in the queue have successfully replayed.
    +   * @param {number} [options.maxRetentionTime = 7 days] The amount of time (in
    +   *     ms) a request may be retried. After this amount of time has passed,
    +   *     the request will be deleted from the queue.
    +   */
    +  constructor(name, {
    +    callbacks = {},
    +    maxRetentionTime = MAX_RETENTION_TIME,
    +  } = {}) {
    +    // Ensure the store name is not already being used
    +    if (queueNames.has(name)) {
    +      throw new WorkboxError('duplicate-queue-name', {name});
    +    } else {
    +      queueNames.add(name);
    +    }
    +
    +    this._name = name;
    +    this._callbacks = callbacks;
    +    this._maxRetentionTime = maxRetentionTime;
    +    this._queueStore = new QueueStore(this);
    +
    +    this._addSyncListener();
    +  }
    +
    +  /**
    +   * @return {string}
    +   */
    +  get name() {
    +    return this._name;
    +  }
    +
    +  /**
    +   * Stores the passed request into IndexedDB. The database used is
    +   * `workbox-background-sync` and the object store name is the same as
    +   * the name this instance was created with (to guarantee it's unique).
    +   *
    +   * @param {Request} request The request object to store.
    +   */
    +  async addRequest(request) {
    +    const storableRequest = await StorableRequest.fromRequest(request.clone());
    +
    +    await this._runCallback('requestWillEnqueue', storableRequest);
    +
    +    await this._queueStore.addEntry(storableRequest);
    +    await this._registerSync();
    +  }
    +
    +  /**
    +   * Retrieves all stored requests in IndexedDB and retries them. If the
    +   * queue contained requests that were successfully replayed, the
    +   * `queueDidReplay` callback is invoked (which implies the queue is
    +   * now empty). If any of the requests fail, a new sync registration is
    +   * created to retry again later.
    +   */
    +  async replayRequests() {
    +    const now = Date.now();
    +    const replayedRequests = [];
    +    const failedRequests = [];
    +
    +    let storableRequest;
    +    while (storableRequest = await this._queueStore.getAndRemoveOldestEntry()) {
    +      // Ignore requests older than maxRetentionTime.
    +      if (now - storableRequest.timestamp > this._maxRetentionTime) {
    +        continue;
    +      }
    +
    +      await this._runCallback('requestWillReplay', storableRequest);
    +
    +      const replay = {request: storableRequest.toRequest()};
    +
    +      try {
    +        // Clone the request before fetching so callbacks get an unused one.
    +        replay.response = await fetch(replay.request.clone());
    +      } catch (err) {
    +        replay.error = err;
    +        failedRequests.push(storableRequest);
    +      }
    +
    +      replayedRequests.push(replay);
    +    }
    +
    +    // If any requests failed, put the failed requests back in the queue
    +    // and register for another sync.
    +    if (failedRequests.length) {
    +      await Promise.all(failedRequests.map((storableRequest) => {
    +        return this._queueStore.addEntry(storableRequest);
    +      }));
    +
    +      await this._registerSync();
    +    }
    +
    +    await this._runCallback('queueDidReplay', replayedRequests);
    +  }
    +
    +  /**
    +   * Runs the passed callback if it exists.
    +   *
    +   * @private
    +   * @param {string} name The name of the callback on this._callbacks.
    +   * @param {...*} args The arguments to invoke the callback with.
    +   */
    +  async _runCallback(name, ...args) {
    +    if (typeof this._callbacks[name] === 'function') {
    +      await this._callbacks[name].apply(null, args);
    +    }
    +  }
    +
    +  /**
    +   * In sync-supporting browsers, this adds a listener for the sync event.
    +   * In non-sync-supporting browsers, this will retry the queue on service
    +   * worker startup.
    +   *
    +   * @private
    +   */
    +  _addSyncListener() {
    +    if ('sync' in registration) {
    +      self.addEventListener('sync', (event) => {
    +        event.waitUntil(this.replayRequests());
    +      });
    +    } else {
    +      // If the browser doesn't support background sync, retry
    +      // every time the service worker starts up as a fallback.
    +      this.replayRequests();
    +    }
    +  }
    +
    +  /**
    +   * Registers a sync event with a tag unique to this instance.
    +   *
    +   * @private
    +   */
    +  async _registerSync() {
    +    try {
    +      await registration.sync.register(`${TAG_PREFIX}:${this._name}`);
    +    } catch (err) {
    +      // This means the registration failed for some reason, either because
    +      // the browser doesn't supported it or because the user has disabled it.
    +      // In either case, do nothing.
    +    }
    +  }
    +
    +  /**
    +   * Returns the set of queue names. This is primarily used to reset the list
    +   * of queue names in tests.
    +   *
    +   * @return {Set}
    +   *
    +   * @private
    +   */
    +  static get _queueNames() {
    +    return queueNames;
    +  }
    +}
    +
    +export {Queue};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_QueuePlugin.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_QueuePlugin.mjs.html new file mode 100644 index 00000000000..401fc73a670 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_QueuePlugin.mjs.html @@ -0,0 +1,75 @@ + + + + + + + + Source: workbox-background-sync/QueuePlugin.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2017 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import './_version.mjs';
    +
    +/**
    + * A class implementing the `fetchDidFail` lifecycle callback. This makes it
    + * easier to add failed requests to a background sync Queue.
    + *
    + * @memberof workbox.backgroundSync
    + */
    +class QueuePlugin {
    +  /**
    +   * @param {Queue} queue The Queue instance to add failed requests to.
    +   */
    +  constructor(queue) {
    +    this._queue = queue;
    +    this.fetchDidFail = this.fetchDidFail.bind(this);
    +  }
    +
    +  /**
    +   * @param {Object} options
    +   * @param {Request} options.request
    +   * @private
    +   */
    +  async fetchDidFail({request}) {
    +    await this._queue.addRequest(request);
    +  }
    +}
    +
    +export {QueuePlugin};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_index.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_index.mjs.html new file mode 100644 index 00000000000..0e186532764 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_index.mjs.html @@ -0,0 +1,54 @@ + + + + + + + + Source: workbox-background-sync/index.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2017 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import './_version.mjs';
    +
    +/**
    + * @namespace workbox.backgroundSync
    + */
    +
    +export * from './_public.mjs';
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_models_StorableRequest.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_models_StorableRequest.mjs.html new file mode 100644 index 00000000000..d12106b0c45 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-background-sync_models_StorableRequest.mjs.html @@ -0,0 +1,153 @@ + + + + + + + + Source: workbox-background-sync/models/StorableRequest.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2017 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import '../_version.mjs';
    +
    +const serializableProperties = [
    +  'method',
    +  'referrer',
    +  'referrerPolicy',
    +  'mode',
    +  'credentials',
    +  'cache',
    +  'redirect',
    +  'integrity',
    +  'keepalive',
    +  'signal',
    +];
    +
    +
    +/**
    + * A class to make it easier to serialize and de-serialize requests so they
    + * can be stored in IndexedDB.
    + *
    + * @private
    + */
    +export default class StorableRequest {
    +  /**
    +   * Converts a Request object to a plain object that can be structured
    +   * cloned or JSON-stringified.
    +   *
    +   * @param {Request} request
    +   * @return {Promise&lt;StorableRequest>}
    +   */
    +  static async fromRequest(request) {
    +    const requestInit = {headers: {}};
    +
    +    // Set the body if present.
    +    if (request.method !== 'GET') {
    +      // Use blob to support non-text request bodies,
    +      // and clone first in case the caller still needs the request.
    +      requestInit.body = await request.clone().blob();
    +    }
    +
    +    // Convert the headers from an iterable to an object.
    +    for (const [key, value] of request.headers.entries()) {
    +      requestInit.headers[key] = value;
    +    }
    +
    +    // Add all other serializable request properties
    +    for (const prop of serializableProperties) {
    +      if (request[prop] !== undefined) {
    +        requestInit[prop] = request[prop];
    +      }
    +    }
    +
    +    return new StorableRequest({url: request.url, requestInit});
    +  }
    +
    +  /**
    +   * Accepts a URL and RequestInit dictionary that can be used to create a
    +   * new Request object. A timestamp is also generated so consumers can
    +   * reference when the object was created.
    +   *
    +   * @param {Object} param1
    +   * @param {string} param1.url
    +   * @param {Object} param1.requestInit
    +   *     See: https://fetch.spec.whatwg.org/#requestinit
    +   * @param {number} param1.timestamp The time the request was created,
    +   *     defaulting to the current time if not specified.
    +   */
    +  constructor({url, requestInit, timestamp = Date.now()}) {
    +    this.url = url;
    +    this.requestInit = requestInit;
    +
    +    // "Private"
    +    this._timestamp = timestamp;
    +  }
    +
    +  /**
    +   * Gets the private _timestamp property.
    +   *
    +   * @return {number}
    +   */
    +  get timestamp() {
    +    return this._timestamp;
    +  }
    +
    +  /**
    +   * Coverts this instance to a plain Object.
    +   *
    +   * @return {Object}
    +   */
    +  toObject() {
    +    return {
    +      url: this.url,
    +      timestamp: this.timestamp,
    +      requestInit: this.requestInit,
    +    };
    +  }
    +
    +  /**
    +   * Converts this instance to a Request.
    +   *
    +   * @return {Request}
    +   */
    +  toRequest() {
    +    return new Request(this.url, this.requestInit);
    +  }
    +}
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_generate-sw-string.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_generate-sw-string.js.html new file mode 100644 index 00000000000..8721c02168d --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_generate-sw-string.js.html @@ -0,0 +1,74 @@ + + + + + + + + Source: workbox-build/src/entry-points/generate-sw-string.js + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +const generateSWStringSchema = require('./options/generate-sw-string-schema');
    +const getFileManifestEntries = require('../lib/get-file-manifest-entries');
    +const populateSWTemplate = require('../lib/populate-sw-template');
    +const validate = require('./options/validate');
    +
    +/**
    + * This method generates a service worker based on the configuration options
    + * provided.
    + *
    + * @param {Object} input
    + * @return {Promise&lt;String>} A populated service worker template, based on the
    + * other configuration options provided.
    + *
    + * @memberof module:workbox-build
    + */
    +async function generateSWString(input) {
    +  const options = validate(input, generateSWStringSchema);
    +
    +  const {manifestEntries} = await getFileManifestEntries(options);
    +
    +  return populateSWTemplate(Object.assign({
    +    manifestEntries,
    +  }, options));
    +}
    +
    +module.exports = generateSWString;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_generate-sw.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_generate-sw.js.html new file mode 100644 index 00000000000..cc25841a72a --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_generate-sw.js.html @@ -0,0 +1,119 @@ + + + + + + + + Source: workbox-build/src/entry-points/generate-sw.js + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +const path = require('path');
    +
    +const cdnUtils = require('../lib/cdn-utils');
    +const copyWorkboxLibraries = require('../lib/copy-workbox-libraries');
    +const generateSWSchema = require('./options/generate-sw-schema');
    +const getFileManifestEntries = require('../lib/get-file-manifest-entries');
    +const validate = require('./options/validate');
    +const writeServiceWorkerUsingDefaultTemplate =
    +  require('../lib/write-sw-using-default-template');
    +
    +/**
    + * This method creates a list of URLs to precache, referred to as a "precache
    + * manifest", based on the options you provide.
    + *
    + * It also takes in additional options that configures the service worker's
    + * behavior, like any `runtimeCaching` rules it should use.
    + *
    + * Based on the precache manifest and the additional configuration, it writes
    + * a ready-to-use service worker file to disk at `swDest`.
    + *
    + * @param {Object} input
    + * @return {Promise&lt;{count: Number, size: Number}>} A promise that resolves once
    + * the service worker file has been written to `swDest`. The `size` property
    + * contains the aggregate size of all the precached entries, in bytes, and the
    + * `count` property contains the total number of precached entries.
    + *
    + * @memberof module:workbox-build
    + */
    +async function generateSW(input) {
    +  const options = validate(input, generateSWSchema);
    +
    +  const destDirectory = path.dirname(options.swDest);
    +
    +  if (options.importWorkboxFromCDN) {
    +    const cdnUrl = cdnUtils.getModuleUrl('workbox-sw');
    +    // importScripts may or may not already be an array containing other URLs.
    +    // Either way, list cdnUrl first.
    +    options.importScripts = [cdnUrl].concat(options.importScripts || []);
    +  } else {
    +    // If we're not importing the Workbox scripts from the CDN, then copy
    +    // over the dev + prod version of all of the core libraries.
    +    const workboxDirectoryName = await copyWorkboxLibraries(destDirectory);
    +
    +    // The Workbox library files should not be precached, since they're cached
    +    // automatically by virtue of being used with importScripts().
    +    options.globIgnores = [
    +      `**/${workboxDirectoryName}/*.js*`,
    +    ].concat(options.globIgnores || []);
    +
    +    const workboxSWPkg = require(`workbox-sw/package.json`);
    +    const workboxSWFilename = path.basename(workboxSWPkg.main);
    +
    +    // importScripts may or may not already be an array containing other URLs.
    +    // Either way, list workboxSWFilename first.
    +    options.importScripts = [
    +      `${workboxDirectoryName}/${workboxSWFilename}`,
    +    ].concat(options.importScripts || []);
    +
    +    options.modulePathPrefix = workboxDirectoryName;
    +  }
    +
    +  const {count, size, manifestEntries} = await getFileManifestEntries(options);
    +
    +  await writeServiceWorkerUsingDefaultTemplate(Object.assign({
    +    manifestEntries,
    +  }, options));
    +
    +  return {count, size};
    +}
    +
    +module.exports = generateSW;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_get-manifest.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_get-manifest.js.html new file mode 100644 index 00000000000..2550fbf205d --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_get-manifest.js.html @@ -0,0 +1,75 @@ + + + + + + + + Source: workbox-build/src/entry-points/get-manifest.js + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +const getFileManifestEntries = require('../lib/get-file-manifest-entries');
    +const getManifestSchema = require('./options/get-manifest-schema');
    +const validate = require('./options/validate');
    +
    +/**
    + * This method returns a list of URLs to precache, referred to as a "precache
    + * manifest", along with details about the number of entries and their size,
    + * based on the options you provide.
    + *
    + * @param {Object} input
    + * @return {Promise&lt;{manifestEntries: Array&lt;ManifestEntry>,
    + * count: Number, size: Number}>} A promise that resolves once the precache
    + * manifest is determined. The `size` property contains the aggregate size of
    + * all the precached entries, in bytes, the `count` property contains the total
    + * number of precached entries, and the `manifestEntries` property contains all
    + * the `ManifestEntry` items.
    + *
    + * @memberof module:workbox-build
    + */
    +async function getManifest(input) {
    +  const options = validate(input, getManifestSchema);
    +
    +  const {manifestEntries, count, size} = await getFileManifestEntries(options);
    +  return {manifestEntries, count, size};
    +}
    +
    +module.exports = getManifest;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_inject-manifest.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_inject-manifest.js.html new file mode 100644 index 00000000000..38c851d22a8 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_entry-points_inject-manifest.js.html @@ -0,0 +1,114 @@ + + + + + + + + Source: workbox-build/src/entry-points/inject-manifest.js + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +const assert = require('assert');
    +const fse = require('fs-extra');
    +const path = require('path');
    +
    +const errors = require('../lib/errors');
    +const getFileManifestEntries = require('../lib/get-file-manifest-entries');
    +const injectManifestSchema = require('./options/inject-manifest-schema');
    +const validate = require('./options/validate');
    +
    +/**
    + * This method creates a list of URLs to precache, referred to as a "precache
    + * manifest", based on the options you provide.
    + *
    + * The manifest is injected into the `swSrc` file, and the regular expression
    + * `injectionPointRegexp` determines where in the file the manifest should go.
    + *
    + * The final service worker file, with the manifest injected, is written to
    + * disk at `swDest`.
    + *
    + * @param {Object} input
    + * @return {Promise&lt;{count: Number, size: Number}>} A promise that resolves once
    + * the service worker file has been written to `swDest`. The `size` property
    + * contains the aggregate size of all the precached entries, in bytes, and the
    + * `count` property contains the total number of precached entries.
    + *
    + * @memberof module:workbox-build
    + */
    +async function injectManifest(input) {
    +  const options = validate(input, injectManifestSchema);
    +
    +  if (path.normalize(input.swSrc) === path.normalize(input.swDest)) {
    +    throw new Error(errors['same-src-and-dest']);
    +  }
    +
    +  const globalRegexp = new RegExp(options.injectionPointRegexp, 'g');
    +
    +  const {count, size, manifestEntries} = await getFileManifestEntries(options);
    +  let swFileContents;
    +  try {
    +    swFileContents = await fse.readFile(input.swSrc, 'utf8');
    +  } catch (error) {
    +    throw new Error(`${errors['invalid-sw-src']} ${error.message}`);
    +  }
    +
    +  const injectionResults = swFileContents.match(globalRegexp);
    +  assert(injectionResults, errors['injection-point-not-found'] +
    +    ` ${options.injectionPointRegexp}`);
    +  assert(injectionResults.length === 1, errors['multiple-injection-points'] +
    +    ` ${options.injectionPointRegexp}`);
    +
    +  const entriesString = JSON.stringify(manifestEntries, null, 2);
    +  swFileContents = swFileContents.replace(globalRegexp, `$1${entriesString}$2`);
    +
    +  try {
    +    await fse.mkdirp(path.dirname(options.swDest));
    +  } catch (error) {
    +    throw new Error(errors['unable-to-make-injection-directory'] +
    +      ` '${error.message}'`);
    +  }
    +
    +  await fse.writeFile(input.swDest, swFileContents);
    +
    +  return {count, size};
    +}
    +
    +module.exports = injectManifest;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_index.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_index.js.html new file mode 100644 index 00000000000..b2672aa2ce5 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_index.js.html @@ -0,0 +1,431 @@ + + + + + + + + Source: workbox-build/src/index.js + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +const copyWorkboxLibraries = require('./lib/copy-workbox-libraries');
    +const generateSW = require('./entry-points/generate-sw');
    +const generateSWString = require('./entry-points/generate-sw-string');
    +const getManifest = require('./entry-points/get-manifest');
    +const injectManifest = require('./entry-points/inject-manifest');
    +
    +/**
    + * This Node module can be used to generate a list of assets that should be
    + * precached in a service worker, generating a hash that can be used to
    + * intelligently update a cache when the service worker is updated.
    + *
    + * This module will use glob patterns to find assets in a given directory
    + * and use the resulting URL and revision data for one of the follow uses:
    + *
    + * 1. Generate a complete service worker with precaching and some basic
    + * configurable options, writing the resulting service worker file to disk. See
    + * [generateSW()]{@link module:workbox-build.generateSW}.
    + * 1. Generate a complete service worker with precaching and some basic
    + * configurable options, without writing the results to disk. See
    + * [generateSWString()]{@link module:workbox-build.generateSWString}.
    + * 1. Inject a manifest into an existing service worker. This allows you
    + * to control your own service worker while still taking advantage of
    + * [workboxSW.precache()]{@link module:workbox-sw.WorkboxSW#precache} logic.
    + * See [injectManifest()]{@link module:workbox-build.injectManifest}.
    + * 1. Just generate a manifest, not a full service worker file.
    + * This is useful if you want to make use of the manifest from your own existing
    + * service worker file and are okay with including the manifest yourself.
    + * See [getManifest()]{@link module:workbox-build.getManifest}.
    + *
    + * @module workbox-build
    + */
    +
    +/**
    + * These are the full set of options that could potentially be used to configure
    + * one of the build tools. Each of the build tools has a slightly different way
    + * of providing this configuration:
    + *
    + * - When using the `workbox-build` module directly, pass the
    + * configuration object to appropriate method. For example,
    + * `workboxBuild.injectManifest(configuration)` or
    + * `workboxBuild.generateSW(configuration)`.
    + *
    + * - When using the `workbox-cli` command line interface, use the
    + * `--config-file` flag to point to a
    + * [CommonJS module file](https://nodejs.org/docs/latest/api/modules.html) that
    + * assigns the configuration object to `module.exports`.
    + *
    + * - When using `workbox-webpack-plugin` within a
    + * [Webpack](https://webpack.js.org/) build, pass the configuration object to
    + * the plugin's constructor, like
    + * `new WorkboxBuildWebpackPlugin(configuration)`.
    + *
    + * Some specific options might not make sense with certain combinations of
    + * interfaces. In those cases, the limitations are called out in the
    + * documentation, and may lead to build-time warnings or errors.
    + *
    + * Each option documented here includes an example, which, for the sake of
    + * illustration, assumes the following local filesystem setup. Please adjust
    + * the example values to match your actual setup.
    + *
    + * ```sh
    + * ./
    + * ├── dev/
    + * │   ├── app.js
    + * │   ├── ignored.html
    + * │   ├── image.png
    + * │   ├── index.html
    + * │   ├── main.css
    + * │   ├── sw.js
    + * │   └── templates/
    + * │       └── app_shell.hbs
    + * └── dist/
    + *     ├── app.js
    + *     ├── image.png
    + *     ├── index.html
    + *     ├── main.css
    + *     └── sw.js
    + * ```
    + *
    + * @typedef {Object} Configuration
    + *
    + * @property {String} swDest The path to the final service worker
    + * file that will be created by the build process, relative to the current
    + * working directory.
    + *
    + * E.g.: `'./dist/sw.js'`
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build.generateSW|generateSW()} or
    + * {@link module:workbox-build.injectManifest|injectManifest()}.
    + *
    + * @property {String} swSrc The path to the source service worker
    + * containing a `precache([])` placeholder, which will be replaced with the
    + * precache manifest generated by the build.
    + *
    + * E.g.: `'./dev/sw.js'`
    + *
    + *  Note: This option is only valid when used with
    + *  {@link module:workbox-build.injectManifest|injectManifest()}.
    + *
    + * @property {String} swTemplate A service worker template that should be
    + * populated based on the configuration provided. The template should be in a
    + * format that [`lodash.template`](https://lodash.com/docs/4.17.4#template)
    + * understands.
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build.generateSWNoFS|generateSWNoFS()}.
    + *
    + * @property {boolean} [importWorkboxFromCDN=true] If `true`, the WorkboxSW
    + * runtime will be automatically imported into the generated service worker from
    + * the official CDN URL. If `false`, the WorkboxSW runtime will be copied
    + * locally into your `swDest` directory when using
    + * {@link module:workbox-build.generateSW|generateSW()}.
    + * If `process.env.NODE_ENV` is set to a string starting with `dev` then the
    + * `dev` bundle of WorkboxSW, with additional assertions and debugging info,
    + * will be used; otherwise, the `prod` bundle will be used.
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build.generateSW|generateSW()} or
    + * {@link module:workbox-build.generateSWNoFS|generateSWNoFS()}.
    + *
    + * @property {Array&lt;String>} [importScripts] An optional list of JavaScript
    + * files that should be passed to
    + * [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)
    + * inside the generated service worker file.
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build.generateSW|generateSW()} or
    + * {@link module:workbox-build.generateSWNoFS|generateSWNoFS()}.
    + *
    + * @property {Array&lt;String>} [globPatterns=['**\/*.{js,css,html}']]
    + * Files matching against any of these
    + * [glob patterns](https://github.com/isaacs/node-glob) will be included in the
    + * precache manifest.
    + *
    + * E.g.: `'**\/*.{js,css,html,png}'`
    + *
    + * @property {String} globDirectory The base directory you wish to
    + * match `globPatterns` against, related to the current working directory.
    + *
    + * E.g.: `'./dev'`
    + *
    + * @property {String|Array&lt;String>} [globIgnores='node_modules']
    + * Files matching against any of these glob patterns will be excluded from the
    + * file manifest, overriding any matches from `globPatterns`.
    + *
    + * E.g. `['**\/ignored.html']`
    + *
    + * @property {Object&lt;String,Array|string>} [templatedUrls]
    + * If a URL is rendered generated based on some server-side logic, its contents
    + * may depend on multiple files or on some other unique string value.
    + *
    + * If used with an array of strings, they will be interpreted as
    + * [glob patterns](https://github.com/isaacs/node-glob), and the contents of
    + * any files matching the patterns will be used to uniquely version the URL.
    + *
    + * If used with a single string, it will be interpreted as unique versioning
    + * information that you've generated out of band for a given URL.
    + *
    + * E.g.
    + * ```js
    + * {
    + *   '/app-shell': [
    + *     'dev/templates/app-shell.hbs',
    + *     'dev/**\/*.css',
    +*    ],
    + *   '/other-page': 'my-version-info',
    + * }
    + * ```
    + *
    + * @property {number} [maximumFileSizeToCacheInBytes=2097152]
    + * This value can be used to determine the maximum size of files that will be
    + * precached. This prevents you from inadvertantly precaching very large files
    + * that might have been accidentally match your `globPatterns` values.
    + *
    + * @property {Array&lt;ManifestTransform>} [manifestTransforms] An array of
    + * manifest transformations, which will be applied sequentially against the
    + * generated manifest. If `modifyUrlPrefix` or `dontCacheBustUrlsMatching` are
    + * also specified, their corresponding transformations will be applied first.
    + *
    + * See {@link module:workbox-build.ManifestTransform|ManifestTransform}.
    + *
    + * @property {Object&lt;String,String>} [modifyUrlPrefix] A mapping of
    + * prefixes that, if present in an entry in the precache manifest, will be
    + * replaced with the corresponding value.
    + *
    + * This can be used to, for example, remove or add a path prefix from a manifest
    + * entry if your web hosting setup doesn't match your local filesystem setup.
    + *
    + * As an alternative with more flexibility, you can use the `manifestTransforms`
    + * option and provide a function that modifies the entries in the manifest using
    + * whatever logic you provide.
    + *
    + * E.g.
    + * ```js
    + * {
    + *   '/prefix-to-remove': '',
    + * }
    + * ```
    + *
    + * @property {RegExp} [dontCacheBustUrlsMatching] Assets that match this
    + * regex will be assumed to be uniquely versioned via their URL, an exempted
    + * from the normal HTTP cache-busting that's done when populating the precache.
    + *
    + * While not required, it's recommended that if your existing build process
    + * already inserts a `[hash]` value into each filename, you provide a RegExp
    + * that will detect those values, as it will reduce the amount of bandwidth
    + * consumed when precaching.
    + *
    + * E.g. `/\.\w{8}\./`
    + *
    + * @property {String} [navigateFallback] This will be used to create a
    + * {@link workbox.routing.NavigationRoute|NavigationRoute} that will
    + * respond to navigation requests for URLs that that aren't precached.
    + *
    + * This is meant to be used in a
    + * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application)
    + * scenario, in which you want all navigations to result in common App Shell
    + * HTML being reused.
    + *
    + * It's *not* intended for use as a fallback that's displayed when the browser
    + * is offline.
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build#generateSW|generateSW()}. When using
    + * {@link module:workbox-build.injectManifest|injectManifest()}, you can
    + * explicitly add in a call to
    + * {@link module:workbox-sw.Router#registerNavigationRoute|
    + * registerNavigationRoute()}
    + * in your `swSrc` file.
    + *
    + * E.g. `'/app-shell'`
    + *
    + * @property {Array&lt;RegExp>} [navigateFallbackWhitelist=/./] An optional
    + * array of regular expressions that restrict which URLs the navigation route
    + * applies to.
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build#generateSW|generateSW()}. When using
    + * {@link module:workbox-build.injectManifest|injectManifest()}, you can
    + * explicitly add in the whitelist when calling
    + * {@link module:workbox-sw.Router#registerNavigationRoute|
    + * registerNavigationRoute()}
    + * in your `swSrc` file.
    + *
    + * E.g. `[/pages/, /articles/]`
    + *
    + * @property {String} [cacheId] An optional ID to be prepended to caches
    + * used by `workbox-sw`. This is primarily useful for local development where
    + * multiple sites may be served from the same `http://localhost` origin.
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build#generateSW|generateSW()}. When using
    + * {@link module:workbox-build.injectManifest|injectManifest()}, you can
    + * explicitly pass the desired value in to the
    + * {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc`
    + * file.
    + *
    + * E.g. `'my-app-name'`
    + *
    + * @property {Boolean} [skipWaiting=false] Whether or not the service worker
    + * should skip over the [waiting](/web/fundamentals/instant-and-offline/service-worker/lifecycle#waiting)
    + * lifecycle stage.
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build#generateSW|generateSW()}. When using
    + * {@link module:workbox-build.injectManifest|injectManifest()}, you can
    + * explicitly pass the desired value in to the
    + * {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc`
    + * file.
    + *
    + * @property {Boolean} [clientsClaim=false] Whether or not the service worker
    + * should [start controlling](/web/fundamentals/instant-and-offline/service-worker/lifecycle#clientsclaim)
    + * any existing clients as soon as it activates.
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build#generateSW|generateSW()}. When using
    + * {@link module:workbox-build.injectManifest|injectManifest()}, you can
    + * explicitly pass the desired value in to the
    + * {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc`
    + * file.
    + *
    + * @property {string} [directoryIndex='index.html'] If a request for a URL
    + * ending in '/' fails, this value will be appended to the URL and a second
    + * request will be made.
    + *
    + * This should be configured to whatever your web server is using, if anything,
    + * for its [directory index](https://httpd.apache.org/docs/2.0/mod/mod_dir.html).
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build#generateSW|generateSW()}. When using
    + * {@link module:workbox-build.injectManifest|injectManifest()}, you can
    + * explicitly pass the desired value in to the
    + * {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc`
    + * file.
    + *
    + * @property {Array&lt;Object>} [runtimeCaching] Passing in an array of objects
    + * containing `urlPattern`s, `handler`s, and potentially `option`s that will add
    + * the appropriate code to the generated service worker to handle runtime
    + * caching.
    + *
    + * Requests for precached URLs that are picked up via `globPatterns` are handled
    + * by default, and don't need to be accomodated in `runtimeCaching`.
    + *
    + * The `handler` values correspond the names of the
    + * {@link module:workbox-sw.Strategies|strategies} supported by `workbox-sw`.
    + *
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build#generateSW|generateSW()}. When using
    + * {@link module:workbox-build.injectManifest|injectManifest()}, you can
    + * explicitly add in the corresponding runtime caching behavior via
    + * {@link module:workbox-sw.Router#registerRoute|registerRoute()} in your
    + * `swSrc` file.
    + *
    + * E.g.
    + * ```js
    + * [{
    + *   // You can use a RegExp as the pattern:
    + *   urlPattern: /.jpg$/,
    + *   handler: 'cacheFirst',
    + *   // Any options provided will be used when
    + *   // creating the caching strategy.
    + *   options: {
    + *     cacheName: 'image-cache',
    + *     cacheExpiration: {
    + *       maxEntries: 10,
    + *     },
    + *   },
    + * }, {
    + *   // You can also use Express-style strings:
    + *   urlPattern: 'https://example.com/path/to/:file',
    + *   handler: 'staleWhileRevalidate',
    + *   options: {
    + *     cacheableResponse: {
    +         statuses: [0],
    + *     },
    + *   },
    + * }]
    + * ```
    + *
    + * @property {Array&lt;RegExp>} [ignoreUrlParametersMatching=[/^utm_/]] Any
    + * search parameter names that match against one of the regex's in this array
    + * will be removed before looking for a precache match.
    + *
    + * This is useful if your users might request URLs that contain, for example,
    + * URL parameters used to track the source of the traffic. Those URL parameters
    + * would normally cause the cache lookup to fail, since the URL strings used
    + * as cache keys would not be expected to include them.
    + *
    + * You can use `[/./]` to ignore all URL parameters.
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build#generateSW|generateSW()}. When using
    + * {@link module:workbox-build.injectManifest|injectManifest()}, you can
    + * explicitly pass the desired value in to the
    + * {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc`
    + * file.
    + *
    + * E.g. `[/homescreen/]`
    + *
    + * @property {Boolean} [handleFetch=true] Whether or not `workbox-sw` should
    + * create a `fetch` event handler that responds to network requests. This is
    + * useful during development if you don't want the service worker serving stale
    + * content.
    + *
    + * Note: This option is only valid when used with
    + * {@link module:workbox-build#generateSW|generateSW()}. When using
    + * {@link module:workbox-build.injectManifest|injectManifest()}, you can
    + * explicitly pass the desired value in to the
    + * {@link module:workbox-sw.WorkboxSW|WorkboxSW() constructor} in your `swSrc`
    + * file.
    + *
    + * @memberof module:workbox-build
    + */
    +
    +module.exports = {
    +  copyWorkboxLibraries,
    +  generateSW,
    +  generateSWString,
    +  getManifest,
    +  injectManifest,
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_lib_copy-workbox-libraries.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_lib_copy-workbox-libraries.js.html new file mode 100644 index 00000000000..6f7ca40dbf5 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_lib_copy-workbox-libraries.js.html @@ -0,0 +1,114 @@ + + + + + + + + Source: workbox-build/src/lib/copy-workbox-libraries.js + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +const fse = require('fs-extra');
    +const path = require('path');
    +
    +const errors = require('./errors');
    +const useBuildType = require('./use-build-type');
    +
    +// Used to filter the libraries to copy based on our package.json dependencies.
    +const WORKBOX_PREFIX = 'workbox-';
    +const BUILD_TYPES = [
    +  'dev',
    +  'prod',
    +];
    +
    +/**
    + * This copies over a set of runtime libraries used by Workbox into a
    + * local directory, which should be deployed alongside your service worker file.
    + *
    + * As an alternative to deploying these local copies, you could instead use
    + * Workbox from its official CDN URL.
    + *
    + * This method is exposed for the benefit of developers using
    + * [injectManifest()]{@link module:workbox-build.injectManifest} who would
    + * prefer not to use the CDN copies of Workbox. Developers using
    + * [generateSW()]{@link module:workbox-build.generateSW} don't need to
    + * explicitly call this method, as it's called automatically when
    + * `importWorkboxFromCDN` is set to `false`.
    + *
    + * @param {string} destDirectory The path to the parent directory under which
    + * the new directory of libraries will be created.
    + * @return {Promise&lt;string>} The name of the newly created directory.
    + *
    + * @alias module:workbox-build.copyWorkboxLibraries
    + */
    +module.exports = async (destDirectory) => {
    +  const thisPkg = require('../../package.json');
    +  // Use the version string from workbox-build in the name of the parent
    +  // directory. This should be safe, because lerna will bump workbox-build's
    +  // pkg.version whenever one of the dependent libraries gets bumped, and we
    +  // care about versioning the dependent libraries.
    +  const workboxDirectoryName = `workbox-v${thisPkg.version}`;
    +  const workboxDirectoryPath = path.join(destDirectory, workboxDirectoryName);
    +  await fse.ensureDir(workboxDirectoryPath);
    +
    +  const copyPromises = [];
    +  const librariesToCopy = Object.keys(thisPkg.dependencies).filter(
    +    (dependency) => dependency.startsWith(WORKBOX_PREFIX));
    +  for (const library of librariesToCopy) {
    +    const pkg = require(`${library}/package.json`);
    +    const defaultPathToLibrary = require.resolve(`${library}/${pkg.main}`);
    +
    +    for (const buildType of BUILD_TYPES) {
    +      const srcPath = useBuildType(defaultPathToLibrary, buildType);
    +      const destPath = path.join(workboxDirectoryPath,
    +        path.basename(srcPath));
    +      copyPromises.push(fse.copy(srcPath, destPath));
    +      copyPromises.push(fse.copy(`${srcPath}.map`, `${destPath}.map`));
    +    }
    +  }
    +
    +  try {
    +    await Promise.all(copyPromises);
    +    return workboxDirectoryName;
    +  } catch (error) {
    +    throw Error(`${errors['unable-to-copy-workbox-libraries']} ${error}`);
    +  }
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_lib_filter-files.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_lib_filter-files.js.html new file mode 100644 index 00000000000..72d3423e52d --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_lib_filter-files.js.html @@ -0,0 +1,153 @@ + + + + + + + + Source: workbox-build/src/lib/filter-files.js + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +const maximumSizeTransform = require('./maximum-size-transform');
    +const modifyUrlPrefixTranform = require('./modify-url-prefix-transform');
    +const noRevisionForUrlsMatchingTransform =
    +  require('./no-revision-for-urls-matching-transform');
    +
    +/**
    + * A `ManifestTransform` function can be used to modify the modify the `url` or
    + * `revision` properties of some or all of the
    + * {@link module:workbox-build#ManifestEntry|ManifestEntries} in the manifest.
    + *
    + * Deleting the `revision` property of an entry will cause
    + * the corresponding `url` to be precached without cache-busting parameters
    + * applied, which is to say, it implies that the URL itself contains
    + * proper versioning info. If the `revision` property is present, it must be
    + * set to a string.
    + *
    + * @example &lt;caption>A transformation that prepended the origin of a CDN for any
    + * URL starting with '/assets/' could be implemented as:&lt;/caption>
    + *
    + * const cdnTransform = (manifestEntries) => manifestEntries.map(entry => {
    + *   const cdnOrigin = 'https://example.com';
    + *   if (entry.url.startsWith('/assets/')) {
    + *     entry.url = cdnOrigin + entry.url;
    + *   }
    + *   return entry;
    + * });
    + *
    + * @example &lt;caption>A transformation that removes the revision field when the
    + * URL contains an 8-character hash surrounded by '.', indicating that it
    + * already contains revision information:&lt;/caption>
    + *
    + * const removeRevisionTransform = (manifestEntries) => {
    + *   return manifestEntries.map(entry => {
    + *     const hashRegExp = /\.\w{8}\./;
    + *     if (entry.url.match(hashRegExp)) {
    + *       delete entry.revision;
    + *     }
    + *     return entry;
    + *   });
    + * };
    + *
    + * @callback ManifestTransform
    + * @param {Array&lt;ManifestEntry>} manifestEntries The full array of entries,
    + * prior to the current transformation.
    + * @return {Array&lt;ManifestEntry>} The array of entries with the transformation
    + * applied.
    + *
    + * @memberof module:workbox-build
    + */
    +
    +module.exports = ({
    +  dontCacheBustUrlsMatching,
    +  fileDetails,
    +  manifestTransforms,
    +  maximumFileSizeToCacheInBytes,
    +  modifyUrlPrefix,
    +}) => {
    +  // Take the array of fileDetail objects and convert it into an array of
    +  // {url, revision, size} objects, with \ replaced with /.
    +  const normalizedManifest = fileDetails.map((fileDetails) => {
    +    return {
    +      url: fileDetails.file.replace(/\\/g, '/'),
    +      revision: fileDetails.hash,
    +      size: fileDetails.size,
    +    };
    +  });
    +
    +  let transformsToApply = [];
    +
    +  if (maximumFileSizeToCacheInBytes) {
    +    transformsToApply.push(maximumSizeTransform(maximumFileSizeToCacheInBytes));
    +  }
    +
    +  if (modifyUrlPrefix) {
    +    transformsToApply.push(modifyUrlPrefixTranform(modifyUrlPrefix));
    +  }
    +
    +  if (dontCacheBustUrlsMatching) {
    +    transformsToApply.push(
    +      noRevisionForUrlsMatchingTransform(dontCacheBustUrlsMatching));
    +  }
    +
    +  // Any additional manifestTransforms that were passed will be applied last.
    +  transformsToApply = transformsToApply.concat(manifestTransforms || []);
    +
    +  // Apply the transformations sequentially.
    +  const transformedManifest = transformsToApply.reduce(
    +    (previousManifest, transform) => transform(previousManifest),
    +    normalizedManifest);
    +
    +  // Generate some metadata about the manifest before we clear out the size
    +  // properties from each entry.
    +  const count = transformedManifest.length;
    +  let size = 0;
    +  for (const manifestEntry of transformedManifest) {
    +    size += manifestEntry.size;
    +    delete manifestEntry.size;
    +  }
    +
    +  return {
    +    count,
    +    size,
    +    manifestEntries: transformedManifest,
    +  };
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_lib_get-file-manifest-entries.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_lib_get-file-manifest-entries.js.html new file mode 100644 index 00000000000..a54ba2a76d7 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-build_src_lib_get-file-manifest-entries.js.html @@ -0,0 +1,139 @@ + + + + + + + + Source: workbox-build/src/lib/get-file-manifest-entries.js + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +const assert = require('assert');
    +const path = require('path');
    +
    +const errors = require('./errors');
    +const filterFiles = require('./filter-files');
    +const getCompositeDetails = require('./get-composite-details');
    +const getFileDetails = require('./get-file-details');
    +const getStringDetails = require('./get-string-details');
    +
    +/**
    + * @typedef {Object} ManifestEntry
    + * @property {String} url The URL to the asset in the manifest.
    + * @property {String} revision The revision details for the file. This is a
    + * hash generated by node based on the file contents.
    + *
    + * @memberof module:workbox-build
    + */
    +
    +module.exports = async ({
    +  dontCacheBustUrlsMatching,
    +  globDirectory,
    +  globIgnores,
    +  globPatterns,
    +  manifestTransforms,
    +  maximumFileSizeToCacheInBytes,
    +  modifyUrlPrefix,
    +  swDest,
    +  templatedUrls,
    +}) => {
    +  // Initialize to an empty array so that we can still pass something to
    +  // filterFiles() and get a normalized output.
    +  let fileDetails = [];
    +  const fileSet = new Set();
    +
    +  if (globDirectory) {
    +    if (swDest) {
    +      // Ensure that we ignore the SW file we're eventually writing to disk.
    +      globIgnores.push(`**/${path.basename(swDest)}`);
    +    }
    +
    +    fileDetails = globPatterns.reduce((accumulated, globPattern) => {
    +      const globbedFileDetails = getFileDetails({
    +        globDirectory,
    +        globPattern,
    +        globIgnores,
    +      });
    +
    +      globbedFileDetails.forEach((fileDetails) => {
    +        if (fileSet.has(fileDetails.file)) {
    +          return;
    +        }
    +
    +        fileSet.add(fileDetails.file);
    +        accumulated.push(fileDetails);
    +      });
    +      return accumulated;
    +    }, []);
    +  }
    +
    +  if (templatedUrls) {
    +    for (let url of Object.keys(templatedUrls)) {
    +      assert(!fileSet.has(url), errors['templated-url-matches-glob']);
    +
    +      const dependencies = templatedUrls[url];
    +      if (Array.isArray(dependencies)) {
    +        const details = dependencies.reduce((previous, globPattern) => {
    +          try {
    +            const globbedFileDetails = getFileDetails({
    +              globDirectory,
    +              globPattern,
    +              globIgnores,
    +            });
    +            return previous.concat(globbedFileDetails);
    +          } catch (error) {
    +            const debugObj = {};
    +            debugObj[url] = dependencies;
    +            throw new Error(`${errors['bad-template-urls-asset']} ` +
    +              `'${globPattern}' from '${JSON.stringify(debugObj)}':\n` +
    +              error);
    +          }
    +        }, []);
    +        fileDetails.push(getCompositeDetails(url, details));
    +      } else if (typeof dependencies === 'string') {
    +        fileDetails.push(getStringDetails(url, dependencies));
    +      }
    +    }
    +  }
    +
    +  return filterFiles({fileDetails, maximumFileSizeToCacheInBytes,
    +    modifyUrlPrefix, dontCacheBustUrlsMatching, manifestTransforms});
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cache-expiration_CacheExpiration.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cache-expiration_CacheExpiration.mjs.html new file mode 100644 index 00000000000..9e04b30e977 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cache-expiration_CacheExpiration.mjs.html @@ -0,0 +1,301 @@ + + + + + + + + Source: workbox-cache-expiration/CacheExpiration.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +import CacheTimestampsModel from './models/CacheTimestampsModel.mjs';
    +import './_version.mjs';
    +
    +/**
    + * The `CacheExpiration` class allows you define an expiration and / or
    + * limit on the number of responses stored in a
    + * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).
    + *
    + * @memberof workbox.expiration
    + */
    +class CacheExpiration {
    +  /**
    +   * To construct a new CacheExpiration instance you must provide at least
    +   * one of the `config` properties.
    +   *
    +   * @param {string} cacheName Name of the cache to apply restrictions to.
    +   * @param {Object} config
    +   * @param {number} [config.maxEntries] The maximum number of entries to cache.
    +   * Entries used the least will be removed as the maximum is reached.
    +   * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
    +   * it's treated as stale and removed.
    +   */
    +  constructor(cacheName, config = {}) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isType(cacheName, 'string', {
    +        moduleName: 'workbox-cache-expiration',
    +        className: 'CacheExpiration',
    +        funcName: 'constructor',
    +        paramName: 'cacheName',
    +      });
    +
    +      if (!(config.maxEntries || config.maxAgeSeconds)) {
    +        throw new WorkboxError('max-entries-or-age-required', {
    +          moduleName: 'workbox-cache-expiration',
    +          className: 'CacheExpiration',
    +          funcName: 'constructor',
    +        });
    +      }
    +
    +      if (config.maxEntries) {
    +        assert.isType(config.maxEntries, 'number', {
    +          moduleName: 'workbox-cache-expiration',
    +          className: 'CacheExpiration',
    +          funcName: 'constructor',
    +          paramName: 'config.maxEntries',
    +        });
    +
    +        // TODO: Assert is positive
    +      }
    +
    +      if (config.maxAgeSeconds) {
    +        assert.isType(config.maxAgeSeconds, 'number', {
    +          moduleName: 'workbox-cache-expiration',
    +          className: 'CacheExpiration',
    +          funcName: 'constructor',
    +          paramName: 'config.maxAgeSeconds',
    +        });
    +
    +        // TODO: Assert is positive
    +      }
    +    }
    +
    +    this._isRunning = false;
    +    this._rerunRequested = false;
    +    this._maxEntries = config.maxEntries;
    +    this._maxAgeSeconds = config.maxAgeSeconds;
    +    this._cacheName = cacheName;
    +    this._timestampModel = new CacheTimestampsModel(cacheName);
    +  }
    +
    +  /**
    +   * Expires entries for the given cache and given criteria.
    +   */
    +  async expireEntries() {
    +    if (this._isRunning) {
    +      this._rerunRequested = true;
    +      return;
    +    }
    +    this._isRunning = true;
    +
    +    const now = Date.now();
    +
    +    // First, expire old entries, if maxAgeSeconds is set.
    +    const oldEntries = await this._findOldEntries(now);
    +
    +    // Once that's done, check for the maximum size.
    +    const extraEntries = await this._findExtraEntries();
    +
    +    // Use a Set to remove any duplicates following the concatenation, then
    +    // convert back into an array.
    +    const allUrls = [...new Set(oldEntries.concat(extraEntries))];
    +
    +    await Promise.all([
    +      this._deleteFromCache(allUrls),
    +      this._deleteFromIDB(allUrls),
    +    ]);
    +
    +    if (process.env.NODE_ENV !== 'production') {
    +      // TODO: break apart entries deleted due to expiration vs size restraints
    +      if (allUrls.length > 0) {
    +        logger.groupCollapsed(
    +          `Expired ${allUrls.length} ` +
    +          `${allUrls.length === 1 ? 'entry' : 'entries'} and removed ` +
    +          `${allUrls.length === 1 ? 'it' : 'them'} from the ` +
    +          `'${this._cacheName}' cache.`);
    +        logger.log(
    +          `Expired the following ${allUrls.length === 1 ? 'URL' : 'URLs'}:`);
    +        allUrls.forEach((url) => logger.log(`    ${url}`));
    +        logger.groupEnd();
    +      } else {
    +        logger.debug(`Cache expiration ran and found no entries to remove.`);
    +      }
    +    }
    +
    +    this._isRunning = false;
    +    if (this._rerunRequested) {
    +      this._rerunRequested = false;
    +      this.expireEntries();
    +    }
    +  }
    +
    +  /**
    +   * Expires entries based on the the maximum age.
    +   *
    +   * @param {number} expireFromTimestamp A timestamp.
    +   * @return {Promise&lt;Array&lt;string>>} A list of the URLs that were expired.
    +   *
    +   * @private
    +   */
    +  async _findOldEntries(expireFromTimestamp) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isType(expireFromTimestamp, 'number', {
    +        moduleName: 'workbox-cache-expiration',
    +        className: 'CacheExpiration',
    +        funcName: '_findOldEntries',
    +        paramName: 'expireFromTimestamp',
    +      });
    +    }
    +
    +    if (!this._maxAgeSeconds) {
    +      return [];
    +    }
    +
    +    const expireOlderThan = expireFromTimestamp - (this._maxAgeSeconds * 1000);
    +    const timestamps = await this._timestampModel.getAllTimestamps();
    +    const expiredUrls = [];
    +    timestamps.forEach((timestampDetails) => {
    +      if (timestampDetails.timestamp &lt; expireOlderThan) {
    +        expiredUrls.push(timestampDetails.url);
    +      }
    +    });
    +
    +    return expiredUrls;
    +  }
    +
    +  /**
    +   * @return {Promise&lt;Array>}
    +   *
    +   * @private
    +   */
    +  async _findExtraEntries() {
    +    const extraUrls = [];
    +
    +    if (!this._maxEntries) {
    +      return [];
    +    }
    +
    +    const timestamps = await this._timestampModel.getAllTimestamps();
    +    while (timestamps.length > this._maxEntries) {
    +      const lastUsed = timestamps.shift();
    +      extraUrls.push(lastUsed.url);
    +    }
    +
    +    return extraUrls;
    +  }
    +
    +  /**
    +   * @param {Array&lt;string>} urls Array of URLs to delete from cache.
    +   *
    +   * @private
    +   */
    +  async _deleteFromCache(urls) {
    +    const cache = await caches.open(this._cacheName);
    +    for (const url of urls) {
    +      await cache.delete(url);
    +    }
    +  }
    +
    +  /**
    +   * @param {Array&lt;string>} urls Array of URLs to delete from IDB
    +   *
    +   * @private
    +   */
    +  async _deleteFromIDB(urls) {
    +    for (const url of urls) {
    +      await this._timestampModel.deleteUrl(url);
    +    }
    +  }
    +
    +  /**
    +   * Update the timestamp for the given URL. This ensures the when
    +   * removing entries based on maximum entries, most recently used
    +   * is accurate or when expiring, the timestamp is up-to-date.
    +   *
    +   * @param {string} url
    +   */
    +  async updateTimestamp(url) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isType(url, 'string', {
    +        moduleName: 'workbox-cache-expiration',
    +        className: 'CacheExpiration',
    +        funcName: 'updateTimestamp',
    +        paramName: 'url',
    +      });
    +    }
    +
    +    const urlObject = new URL(url, location);
    +    urlObject.hash = '';
    +
    +    await this._timestampModel.setTimestamp(urlObject.href, Date.now());
    +  }
    +
    +  /**
    +   * Can be used to check if a URL has expired or not before it's used.
    +   *
    +   * This requires a look up from IndexedDB, so can be slow.
    +   *
    +   * Note: This method will not remove the cached entry, call
    +   * `expireEntries()` to remove indexedDB and Cache entries.
    +   *
    +   * @param {string} url
    +   * @return {boolean}
    +   */
    +  async isURLExpired(url) {
    +    if (!this._maxAgeSeconds) {
    +      throw new WorkboxError(`expired-test-without-max-age`, {
    +        methodName: 'isURLExpired',
    +        paramName: 'maxAgeSeconds',
    +      });
    +    }
    +    const urlObject = new URL(url, location);
    +    urlObject.hash = '';
    +
    +    const timestamp = await this._timestampModel.getTimestamp(urlObject.href);
    +    const expireOlderThan = Date.now() - (this._maxAgeSeconds * 1000);
    +    return (timestamp &lt; expireOlderThan);
    +  }
    +}
    +
    +export {CacheExpiration};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cache-expiration_CacheExpirationPlugin.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cache-expiration_CacheExpirationPlugin.mjs.html new file mode 100644 index 00000000000..d0ab0771e8e --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cache-expiration_CacheExpirationPlugin.mjs.html @@ -0,0 +1,239 @@ + + + + + + + + Source: workbox-cache-expiration/CacheExpirationPlugin.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2016 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +     http://www.apache.org/licenses/LICENSE-2.0
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {CacheExpiration} from './CacheExpiration.mjs';
    +import './_version.mjs';
    +
    +/**
    + * This plugin can be used in the Workbox API's to regularly enforce a
    + * limit on the age and / or the number of cached requests.
    + *
    + * Whenever a cached request is used or updated, this plugin will look
    + * at the used Cache and remove any old or extra requests.
    + *
    + * When using `maxAgeSeconds`, requests may be used *once* after expiring
    + * because the expiration clean up will not have occured until *after* the
    + * cached request has been used. If the request has a "Date" header, then
    + * a light weight expiration check is performed and the request will not be
    + * used immediately.
    + *
    + * When using `maxEntries`, the last request to be used will be the request
    + * that is removed from the Cache.
    + *
    + * @memberof workbox.expiration
    + */
    +class CacheExpirationPlugin {
    +  /**
    +   * @param {Object} config
    +   * @param {number} [config.maxEntries] The maximum number of entries to cache.
    +   * Entries used the least will be removed as the maximum is reached.
    +   * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
    +   * it's treated as stale and removed.
    +   */
    +  constructor(config = {}) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      if (!(config.maxEntries || config.maxAgeSeconds)) {
    +        throw new WorkboxError('max-entries-or-age-required', {
    +          moduleName: 'workbox-cache-expiration',
    +          className: 'CacheExpirationPlugin',
    +          funcName: 'constructor',
    +        });
    +      }
    +
    +      if (config.maxEntries) {
    +        assert.isType(config.maxEntries, 'number', {
    +          moduleName: 'workbox-cache-expiration',
    +          className: 'CacheExpirationPlugin',
    +          funcName: 'constructor',
    +          paramName: 'config.maxEntries',
    +        });
    +      }
    +
    +      if (config.maxAgeSeconds) {
    +        assert.isType(config.maxAgeSeconds, 'number', {
    +          moduleName: 'workbox-cache-expiration',
    +          className: 'CacheExpirationPlugin',
    +          funcName: 'constructor',
    +          paramName: 'config.maxAgeSeconds',
    +        });
    +      }
    +    }
    +
    +    this._config = config;
    +    this._maxAgeSeconds = config.maxAgeSeconds;
    +    this._cacheExpirations = new Map();
    +  }
    +
    +  /**
    +   * A simple helper method to return a CacheExpiration instance for a given
    +   * cache name.
    +   *
    +   * @param {string} cacheName
    +   * @return {CacheExpiration}
    +   *
    +   * @private
    +   */
    +  _getCacheExpiration(cacheName) {
    +    let cacheExpiration = this._cacheExpirations.get(cacheName);
    +    if (!cacheExpiration) {
    +      cacheExpiration = new CacheExpiration(cacheName, this._config);
    +      this._cacheExpirations.set(cacheName, cacheExpiration);
    +    }
    +    return cacheExpiration;
    +  }
    +
    +  /**
    +   * A "lifecycle" callback that will be triggered automatically by the
    +   * `workbox.runtimeCaching` handlers when a `Response` is about to be returned
    +   * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to
    +   * the handler. It allows the `Response` to be inspected for freshness and
    +   * prevents it from being used if the `Response`'s `Date` header value is
    +   * older than the configured `maxAgeSeconds`.
    +   *
    +   * @param {Object} input
    +   * @param {string} input.cacheName Name of the cache the responses belong to.
    +   * @param {Response} input.cachedResponse The `Response` object that's been
    +   *        read from a cache and whose freshness should be checked.
    +   * @return {Response} Either the `cachedResponse`, if it's
    +   *         fresh, or `null` if the `Response` is older than `maxAgeSeconds`.
    +   *
    +   * @private
    +   */
    +  cachedResponseWillBeUsed({cacheName, cachedResponse}) {
    +    let isFresh = this._isResponseDateFresh(cachedResponse);
    +
    +    // Expire entries to ensure that even if the expiration date has
    +    // expired, it'll only be used once.
    +    const cacheExpiration = this._getCacheExpiration(cacheName);
    +    cacheExpiration.expireEntries();
    +
    +    return isFresh ? cachedResponse : null;
    +  }
    +
    +  /**
    +   * @param {Response} cachedResponse
    +   * @return {boolean}
    +   *
    +   * @private
    +   */
    +  _isResponseDateFresh(cachedResponse) {
    +    if (!this._maxAgeSeconds) {
    +      // We aren't expiring by age, so return true, it's fresh
    +      return true;
    +    }
    +
    +    // Check if the 'date' header will suffice a quick expiration check.
    +    // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for
    +    // discussion.
    +    const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
    +    if (dateHeaderTimestamp === null) {
    +      // Unable to parse date, so assume it's fresh.
    +      return true;
    +    }
    +
    +    // If we have a valid headerTime, then our response is fresh iff the
    +    // headerTime plus maxAgeSeconds is greater than the current time.
    +    const now = Date.now();
    +    return dateHeaderTimestamp >= now - (this._maxAgeSeconds * 1000);
    +  }
    +
    +  /**
    +   * This method will extract the data header and parse it into a useful
    +   * value.
    +   *
    +   * @param {Response} cachedResponse
    +   * @return {number}
    +   *
    +   * @private
    +   */
    +  _getDateHeaderTimestamp(cachedResponse) {
    +    const dateHeader = cachedResponse.headers['date'];
    +    const parsedDate = new Date(dateHeader);
    +    const headerTime = parsedDate.getTime();
    +
    +    // If the Date header was invalid for some reason, parsedDate.getTime()
    +    // will return NaN.
    +    if (isNaN(headerTime)) {
    +      return null;
    +    }
    +
    +    return headerTime;
    +  }
    +
    +  /**
    +   * A "lifecycle" callback that will be triggered automatically by the
    +   * `workbox.runtimeCaching` handlers when an entry is added to a cache.
    +   *
    +   * @param {Object} input
    +   * @param {string} input.cacheName Name of the cache the responses belong to.
    +   * @param {string} input.request The Request for the cached entry.
    +   *
    +   * @private
    +   */
    +  async cacheDidUpdate({cacheName, request}) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isType(cacheName, 'string', {
    +        moduleName: 'workbox-cache-expiration',
    +        className: 'CacheExpirationPlugin',
    +        funcName: 'cacheDidUpdate',
    +        paramName: 'cacheName',
    +      });
    +      assert.isInstance(request, Request, {
    +        moduleName: 'workbox-cache-expiration',
    +        className: 'CacheExpirationPlugin',
    +        funcName: 'cacheDidUpdate',
    +        paramName: 'request',
    +      });
    +    }
    +
    +    const cacheExpiration = this._getCacheExpiration(cacheName);
    +    await cacheExpiration.updateTimestamp(request.url);
    +    await cacheExpiration.expireEntries();
    +  }
    +}
    +
    +export {CacheExpirationPlugin};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cache-expiration_index.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cache-expiration_index.mjs.html new file mode 100644 index 00000000000..dcb0844b226 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cache-expiration_index.mjs.html @@ -0,0 +1,55 @@ + + + + + + + + Source: workbox-cache-expiration/index.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +/**
    + * @namespace workbox.expiration
    + */
    +
    +import './_version.mjs';
    +
    +export * from './_public.mjs';
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_app.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_app.js.html new file mode 100644 index 00000000000..9870ffdf3cd --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_app.js.html @@ -0,0 +1,102 @@ + + + + + + + + Source: workbox-cli/src/app.js + + + + +
    +
    +
    + +
    + +
    +
    /**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    +**/
    +
    +const assert = require('assert');
    +const path = require('path');
    +const prettyBytes = require('pretty-bytes');
    +const workboxBuild = require('workbox-build');
    +
    +const errors = require('./lib/errors');
    +const logger = require('./lib/logger');
    +const readConfig = require('./lib/read-config');
    +const runWizard = require('./lib/run-wizard');
    +
    +module.exports = async (command, configFile) => {
    +  assert(command, errors['missing-command-param']);
    +
    +  switch (command) {
    +    case 'wizard': {
    +      await runWizard();
    +      break;
    +    }
    +
    +    case 'generateSW':
    +    case 'injectManifest': {
    +      assert(configFile, errors['missing-config-file-param']);
    +
    +      // TODO: Confirm that this works with Windows paths.
    +      const configPath = path.resolve(process.cwd(), configFile);
    +      let config;
    +      try {
    +        config = readConfig(configPath);
    +      } catch (error) {
    +        logger.error(errors['invalid-common-js-module']);
    +        throw error;
    +      }
    +
    +      try {
    +        const {size, count} = await workboxBuild[command](config);
    +        logger.log(`The service worker was written to ${config.swDest}\n` +
    +          `${count} files will be precached, totalling ${prettyBytes(size)}.`);
    +      } catch (error) {
    +        // See https://github.com/hapijs/joi/blob/v11.3.4/API.md#errors
    +        if (typeof error.annotate === 'function') {
    +          throw new Error(
    +            `${errors['config-validation-failed']}\n${error.annotate()}`);
    +        }
    +        logger.error(errors['workbox-build-runtime-error']);
    +        throw error;
    +      }
    +      break;
    +    }
    +
    +    default: {
    +      throw new Error(errors['unknown-command'] + ` ` + command);
    +    }
    +  }
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_bin.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_bin.js.html new file mode 100644 index 00000000000..0ed568500d3 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_bin.js.html @@ -0,0 +1,76 @@ + + + + + + + + Source: workbox-cli/src/bin.js + + + + +
    +
    +
    + +
    + +
    +
    #! /usr/bin/env node
    +
    +/**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    +**/
    +
    +const meow = require('meow');
    +const updateNotifier = require('update-notifier');
    +
    +const app = require('./app.js');
    +const cleanupStackTrace = require('./lib/cleanup-stack-trace.js');
    +const helpText = require('./lib/help-text');
    +const logger = require('./lib/logger');
    +
    +(async () => {
    +  const params = meow(helpText);
    +  updateNotifier({pkg: params.pkg}).notify();
    +
    +  try {
    +    await app(...params.input);
    +  } catch (error) {
    +    // Show the full error and stack trace if we're run with --debug.
    +    if (params.flags.debug) {
    +      logger.error(`\n${error.stack}`);
    +    } else {
    +      logger.error(`\n${error.message}`);
    +      logger.debug(`${cleanupStackTrace(error, 'app.js')}\n`);
    +    }
    +
    +    process.exit(1);
    +  }
    +})();
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_constants.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_constants.js.html new file mode 100644 index 00000000000..a7f9de93f5a --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_constants.js.html @@ -0,0 +1,53 @@ + + + + + + + + Source: workbox-cli/src/lib/constants.js + + + + +
    +
    +
    + +
    + +
    +
    /**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + **/
    +
    +module.exports = {
    +  ignoredDirectories: [
    +    'node_modules',
    +  ],
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_errors.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_errors.js.html new file mode 100644 index 00000000000..b7c57c6176a --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_errors.js.html @@ -0,0 +1,67 @@ + + + + + + + + Source: workbox-cli/src/lib/errors.js + + + + +
    +
    +
    + +
    + +
    +
    /**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    +**/
    +
    +const ol = require('common-tags').oneLine;
    +
    +module.exports = {
    +  'missing-command-param': `Please provide a command.`,
    +  'missing-config-file-param': `Please provide a configuration file.`,
    +  'invalid-common-js-module': ol`Please pass in a valid CommonJS module that
    +    exports your configuration.`,
    +  'config-validation-failed': `Your configuration is invalid:`,
    +  'workbox-build-runtime-error': `Service worker generation failed:`,
    +  'unknown-command': `Unknown command:`,
    +  'no-file-extensions-found': ol`No files could be found that are suitable for
    +    caching.`,
    +  'no-file-extensions-selected': `Please select at least one file extension.`,
    +  'invalid-sw-dest': ol`Please enter a valid path to use for the service worker
    +    file that's created.`,
    +  'glob-directory-invalid': ol`The path you entered isn't a valid directory.`,
    +  'invalid-config-location': ol`Please enter a valid path to use for the saved
    +    configuration file.`,
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_help-text.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_help-text.js.html new file mode 100644 index 00000000000..ffb981ece9f --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_help-text.js.html @@ -0,0 +1,76 @@ + + + + + + + + Source: workbox-cli/src/lib/help-text.js + + + + +
    +
    +
    + +
    + +
    +
    /**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    +**/
    +
    +module.exports = `Usage:
    +$ workbox &lt;command> [options]
    +  
    +Commands:
    +  wizard
    +    Runs the configuration wizard, which will generate a
    +    config file based on answers to questions.
    +  
    +  generateSW &lt;path/to/config.js>
    +    Creates a new service worker file based on the options
    +    in the config file. See https://goo.gl/zQz4By
    +  
    +  injectManifest &lt;path/to/config.js>
    +    Takes an existing service worker file and creates a
    +    copy of it with a precaching manifest "injected" into
    +    it. The precaching manifest is generated based on the
    +    options in the config file. See https://goo.gl/yB6KZL
    +    
    +Config file:
    +  In 'generateSW' or 'injectManifest' mode, the config file should be a
    +  JavaScript file, in CommonJS module format.
    +  The exported object's properties should follow https://goo.gl/YYPcyY
    +
    +Examples:
    +  $ workbox wizard
    +  $ workbox generateSW workbox-config.js
    +  $ workbox injectManifest configs/workbox-dev-config.js
    +`;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_logger.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_logger.js.html new file mode 100644 index 00000000000..fbeb433bd1a --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_logger.js.html @@ -0,0 +1,56 @@ + + + + + + + + Source: workbox-cli/src/lib/logger.js + + + + +
    +
    +
    + +
    + +
    +
    /**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    +**/
    +
    +const chalk = require('chalk');
    +
    +module.exports = {
    +  debug: (...args) => console.log(chalk.gray(...args)),
    +  log: (...args) => console.log(...args),
    +  warn: (...args) => console.warn(chalk.yellow(...args)),
    +  error: (...args) => console.error(chalk.red.bold(...args)),
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-config-location.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-config-location.js.html new file mode 100644 index 00000000000..b41946368be --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-config-location.js.html @@ -0,0 +1,77 @@ + + + + + + + + Source: workbox-cli/src/lib/questions/ask-config-location.js + + + + +
    +
    +
    + +
    + +
    +
    /**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + **/
    +
    +const assert = require('assert');
    +const inquirer = require('inquirer');
    +const ol = require('common-tags').oneLine;
    +
    +const errors = require('../errors');
    +
    +// The key used for the question/answer.
    +const name = 'configLocation';
    +
    +/**
    + * @return {Promise&lt;Object>} The answers from inquirer.
    + */
    +function askQuestion() {
    +  return inquirer.prompt([{
    +    name,
    +    message: ol`Where would you like to save these configuration options?`,
    +    type: 'input',
    +    default: 'workbox-config.js',
    +  }]);
    +}
    +
    +module.exports = async () => {
    +  const answers = await askQuestion();
    +  const configLocation = answers[name].trim();
    +
    +  assert(configLocation, errors['invalid-config-location']);
    +
    +  return configLocation;
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-extensions-to-cache.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-extensions-to-cache.js.html new file mode 100644 index 00000000000..2bfd16c8152 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-extensions-to-cache.js.html @@ -0,0 +1,132 @@ + + + + + + + + Source: workbox-cli/src/lib/questions/ask-extensions-to-cache.js + + + + +
    +
    +
    + +
    + +
    +
    /**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + **/
    +
    +const assert = require('assert');
    +const glob = require('glob');
    +const inquirer = require('inquirer');
    +const ora = require('ora');
    +const path = require('path');
    +
    +const errors = require('../errors');
    +const {ignoredDirectories} = require('../constants');
    +
    +// The key used for the question/answer.
    +const name = 'globPatterns';
    +
    +/**
    + * @param {string} globDirectory The directory used for the root of globbing.
    + * @return {Promise&lt;Array&lt;string>>} The unique file extensions corresponding
    + * to all of the files under globDirectory.
    + */
    +async function getAllFileExtensions(globDirectory) {
    +  const files = await new Promise((resolve, reject) => {
    +    // Use a pattern to match any file that contains a '.', since that signifies
    +    // the presence of a file extension.
    +    glob('**/*.*', {
    +      cwd: globDirectory,
    +      nodir: true,
    +      ignore: ignoredDirectories.map((directory) => `**/${directory}/**`),
    +    }, (error, files) => {
    +      if (error) {
    +        reject(error);
    +      } else {
    +        resolve(files);
    +      }
    +    });
    +  });
    +
    +  const extensions = new Set();
    +  for (const file of files) {
    +    const extension = path.extname(file);
    +    if (extension) {
    +      // Get rid of the leading . character.
    +      extensions.add(extension.replace(/^\./, ''));
    +    }
    +  }
    +
    +  return [...extensions];
    +}
    +
    +/**
    + * @param {string} globDirectory The directory used for the root of globbing.
    + * @return {Promise&lt;Object>} The answers from inquirer.
    + */
    +async function askQuestion(globDirectory) {
    +  // We need to get a list of extensions corresponding to files in the directory
    +  // to use when asking the next question. That could potentially take some
    +  // time, so we show a spinner and explanatory text.
    +  const spinner = ora({
    +    text: `Examining files in ${globDirectory}...`,
    +    stream: process.stdout,
    +  }).start();
    +  const fileExtensions = await getAllFileExtensions(globDirectory);
    +  spinner.stop();
    +
    +  assert(fileExtensions.length > 0, errors['no-file-extensions-found']);
    +
    +  return inquirer.prompt([{
    +    name,
    +    message: 'Which file types would you like to precache?',
    +    type: 'checkbox',
    +    choices: fileExtensions,
    +    default: fileExtensions,
    +  }]);
    +}
    +
    +module.exports = async (globDirectory) => {
    +  const answers = await askQuestion(globDirectory);
    +  const extensions = answers[name];
    +  assert(extensions.length > 0, errors['no-file-extensions-selected']);
    +
    +  // glob isn't happy with a single option inside of a {} group, so use a
    +  // pattern without a {} group when there's only one extension.
    +  const extensionsPattern = extensions.length === 1 ?
    +    extensions[0] :
    +    `{${extensions.join(',')}}`;
    +  return [`**/*.${extensionsPattern}`];
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-questions.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-questions.js.html new file mode 100644 index 00000000000..849970b91b5 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-questions.js.html @@ -0,0 +1,69 @@ + + + + + + + + Source: workbox-cli/src/lib/questions/ask-questions.js + + + + +
    +
    +
    + +
    + +
    +
    /**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + **/
    +
    +const askConfigLocation = require('./ask-config-location');
    +const askExtensionsToCache = require('./ask-extensions-to-cache');
    +const askRootOfWebApp = require('./ask-root-of-web-app');
    +const askSWDest = require('./ask-sw-dest');
    +
    +module.exports = async () => {
    +  const globDirectory = await askRootOfWebApp();
    +  const globPatterns = await askExtensionsToCache(globDirectory);
    +  const swDest = await askSWDest();
    +  const configLocation = await askConfigLocation();
    +  const config = {
    +    globDirectory,
    +    globPatterns,
    +    swDest,
    +  };
    +
    +  return {
    +    config,
    +    configLocation,
    +  };
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-root-of-web-app.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-root-of-web-app.js.html new file mode 100644 index 00000000000..005e1229ffc --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-root-of-web-app.js.html @@ -0,0 +1,122 @@ + + + + + + + + Source: workbox-cli/src/lib/questions/ask-root-of-web-app.js + + + + +
    +
    +
    + +
    + +
    +
    /**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + **/
    +
    +const assert = require('assert');
    +const fse = require('fs-extra');
    +const glob = require('glob');
    +const inquirer = require('inquirer');
    +
    +const {ignoredDirectories} = require('../constants');
    +const errors = require('../errors');
    +
    +const ROOT_PROMPT = 'Please enter the path to the root of your web app:';
    +
    +// The key used for the question/answer.
    +const name = 'globDirectory';
    +
    +/**
    + * @return {Promise&lt;Array&lt;string>>} The subdirectories of the current
    + * working directory, with hidden and ignored ones filtered out.
    + */
    +async function getSubdirectories() {
    +  return await new Promise((resolve, reject) => {
    +    glob('*/', {
    +      ignore: ignoredDirectories.map((directory) => `${directory}/`),
    +    }, (error, directories) => {
    +      if (error) {
    +        reject(error);
    +      } else {
    +        resolve(directories);
    +      }
    +    });
    +  });
    +}
    +
    +/**
    + * @return {Promise&lt;Object>} The answers from inquirer.
    + */
    +async function askQuestion() {
    +  const subdirectories = await getSubdirectories();
    +
    +  if (subdirectories.length > 0) {
    +    const manualEntryChoice = 'Manually enter path';
    +    return inquirer.prompt([{
    +      name,
    +      type: 'list',
    +      message: 'What is the root of your web app?',
    +      choices: subdirectories.concat([
    +        new inquirer.Separator(),
    +        manualEntryChoice,
    +      ]),
    +    }, {
    +      name,
    +      when: (answers) => answers[name] === manualEntryChoice,
    +      message: ROOT_PROMPT,
    +    }]);
    +  } else {
    +    return inquirer.prompt([{
    +      name,
    +      message: ROOT_PROMPT,
    +      default: '.',
    +    }]);
    +  }
    +}
    +
    +module.exports = async () => {
    +  const answers = await askQuestion();
    +  const globDirectory = answers[name];
    +
    +  try {
    +    const stat = await fse.stat(globDirectory);
    +    assert(stat.isDirectory());
    +  } catch (error) {
    +    throw new Error(errors['glob-directory-invalid']);
    +  }
    +
    +  return globDirectory;
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-sw-dest.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-sw-dest.js.html new file mode 100644 index 00000000000..6d38ea2a8c8 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_questions_ask-sw-dest.js.html @@ -0,0 +1,77 @@ + + + + + + + + Source: workbox-cli/src/lib/questions/ask-sw-dest.js + + + + +
    +
    +
    + +
    + +
    +
    /**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + **/
    +
    +const assert = require('assert');
    +const inquirer = require('inquirer');
    +const ol = require('common-tags').oneLine;
    +
    +const errors = require('../errors');
    +
    +// The key used for the question/answer.
    +const name = 'swDest';
    +
    +/**
    + * @return {Promise&lt;Object>} The answers from inquirer.
    + */
    +function askQuestion() {
    +  return inquirer.prompt([{
    +    name,
    +    message: ol`Where would you like your service worker file to be saved?`,
    +    type: 'input',
    +    default: 'build/sw.js',
    +  }]);
    +}
    +
    +module.exports = async () => {
    +  const answers = await askQuestion();
    +  const swDest = answers[name].trim();
    +
    +  assert(swDest, errors['invalid-sw-dest']);
    +
    +  return swDest;
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_run-wizard.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_run-wizard.js.html new file mode 100644 index 00000000000..0c85a01bf8f --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-cli_src_lib_run-wizard.js.html @@ -0,0 +1,69 @@ + + + + + + + + Source: workbox-cli/src/lib/run-wizard.js + + + + +
    +
    +
    + +
    + +
    +
    /**
    + * Copyright 2017 Google Inc.
    + *
    + * Licensed under the Apache License, Version 2.0 (the "License");
    + * you may not use this file except in compliance with the License.
    + * You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + **/
    +
    +const fse = require('fs-extra');
    +const ol = require('common-tags').oneLine;
    +
    +const askQuestions = require('./questions/ask-questions');
    +const logger = require('./logger');
    +
    +module.exports = async () => {
    +  const {configLocation, config} = await askQuestions();
    +
    +  const contents = `module.exports = ${JSON.stringify(config, null, 2)};`;
    +  await fse.writeFile(configLocation, contents);
    +
    +  logger.log(`To build your service worker, run
    +
    +  workbox generateSW ${configLocation}
    +
    +as part of a build process. See https://goo.gl/8zZy1P for details.`);
    +
    +  logger.log(ol`You can further customize your service worker by making changes
    +    to ${configLocation}. See https://goo.gl/YYPcyY for details.`);
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-core__default.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-core__default.mjs.html new file mode 100644 index 00000000000..b2e7af36dc0 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-core__default.mjs.html @@ -0,0 +1,218 @@ + + + + + + + + Source: workbox-core/_default.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import LOG_LEVELS from './models/LogLevels.mjs';
    +import {WorkboxError} from './_private/WorkboxError.mjs';
    +import {cacheNames} from './_private/cacheNames.mjs';
    +import {logger} from './_private/logger.mjs';
    +import {assert} from './_private/assert.mjs';
    +import {setLoggerLevel, getLoggerLevel} from './_private/logger.mjs';
    +import './_version.mjs';
    +
    +/**
    + * This class is never exposed publicly. Inidividual methods are exposed
    + * using jsdoc alias commands.
    + *
    + * @memberof workbox.core
    + * @private
    + */
    +class WorkboxCore {
    +  /**
    +   * You should not instantiate this object directly.
    +   *
    +   * @private
    +   */
    +  constructor() {
    +    // Give our version strings something to hang off of.
    +    try {
    +      self.workbox.v = self.workbox.v || {};
    +    } catch (err) {
    +      // NOOP
    +    }
    +
    +    // A WorkboxCore instance must be exported before we can use the logger.
    +    // This is so it can get the current log level.
    +    if (process.env.NODE_ENV !== 'production') {
    +      const padding = '   ';
    +      logger.groupCollapsed('Welcome to Workbox!');
    +      logger.unprefixed.log(
    +        `📖 Read the guides and documentation\n` +
    +        `${padding}/web/tools/workbox/`
    +      );
    +      logger.unprefixed.log(
    +        `❓ Use the [workbox] tag on StackOverflow to ask questions\n` +
    +        `${padding}https://stackoverflow.com/questions/ask?tags=workbox`
    +      );
    +      logger.unprefixed.log(
    +        `🐛 Found a bug? Report it on GitHub\n` +
    +        `${padding}https://github.com/GoogleChrome/workbox/issues/new`
    +      );
    +      logger.groupEnd();
    +    }
    +  }
    +
    +  /**
    +   * Get the current cache names used by Workbox.
    +   *
    +   * `cacheNames.precache` is used for precached assets,
    +   * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to
    +   * store `analytics.js`,
    +   * and `cacheNames.runtime` is used for everything else.
    +   *
    +   * @return {Object} An object with `precache` and `runtime` cache names.
    +   *
    +   * @alias workbox.core.cacheNames
    +   */
    +  get cacheNames() {
    +    return {
    +      googleAnalytics: cacheNames.getGoogleAnalyticsName(),
    +      precache: cacheNames.getPrecacheName(),
    +      runtime: cacheNames.getRuntimeName(),
    +    };
    +  }
    +
    +  /**
    +   * You can alter the default cache names used by the Workbox modules by
    +   * changing the cache name details.
    +   *
    +   * Cache names are generated as `&lt;prefix>-&lt;Cache Name>-&lt;suffix>`.
    +   *
    +   * @param {Object} details
    +   * @param {Object} details.prefix The string to add to the beginning of
    +   * the precache and runtime cache names.
    +   * @param {Object} details.suffix The string to add to the end of
    +   * the precache and runtime cache names.
    +   * @param {Object} details.precache The cache name to use for precache
    +   * caching.
    +   * @param {Object} details.runtime The cache name to use for runtime caching.
    +   * @param {Object} details.googleAnalytics The cache name to use for
    +   * `workbox-google-analytics` caching.
    +   *
    +   * @alias workbox.core.setCacheNameDetails
    +   */
    +  setCacheNameDetails(details) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      Object.keys(details).forEach((key) => {
    +        assert.isType(details[key], 'string', {
    +          moduleName: 'workbox-core',
    +          className: 'WorkboxCore',
    +          funcName: 'setCacheNameDetails',
    +          paramName: `details.${key}`,
    +        });
    +      });
    +
    +      if ('precache' in details &amp;&amp; details.precache.length === 0) {
    +        throw new WorkboxError('invalid-cache-name', {
    +          cacheNameId: 'precache',
    +          value: details.precache,
    +        });
    +      }
    +
    +      if ('runtime' in details &amp;&amp; details.runtime.length === 0) {
    +        throw new WorkboxError('invalid-cache-name', {
    +          cacheNameId: 'runtime',
    +          value: details.runtime,
    +        });
    +      }
    +
    +      if ('googleAnalytics' in details &amp;&amp;
    +        details.googleAnalytics.length === 0) {
    +        throw new WorkboxError('invalid-cache-name', {
    +          cacheNameId: 'googleAnalytics',
    +          value: details.googleAnalytics,
    +        });
    +      }
    +    }
    +
    +    cacheNames.updateDetails(details);
    +  }
    +
    +  /**
    +   * Get the current log level.
    +   *
    +   * @return {number}.
    +   *
    +   * @alias workbox.core.logLevel
    +   */
    +  get logLevel() {
    +    return getLoggerLevel();
    +  }
    +
    +  /**
    +   * Set the current log level passing in one of the values from
    +   * [LOG_LEVELS]{@link module:workbox-core.LOG_LEVELS}.
    +   *
    +   * @param {number} newLevel The new log level to use.
    +   *
    +   * @alias workbox.core.setLogLevel
    +   */
    +  setLogLevel(newLevel) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isType(newLevel, 'number', {
    +        moduleName: 'workbox-core',
    +        className: 'WorkboxCore',
    +        funcName: 'logLevel [setter]',
    +        paramName: `logLevel`,
    +      });
    +    }
    +
    +    if (newLevel > LOG_LEVELS.silent ||
    +      newLevel &lt; LOG_LEVELS.debug) {
    +      throw new WorkboxError('invalid-value', {
    +        paramName: 'logLevel',
    +        validValueDescription: `Please use a value from LOG_LEVELS, i.e ` +
    +          `'logLevel = workbox.core.LOG_LEVELS.debug'.`,
    +        value: newLevel,
    +      });
    +    }
    +
    +    setLoggerLevel(newLevel);
    +  }
    +}
    +
    +export default new WorkboxCore();
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-core_index.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-core_index.mjs.html new file mode 100644 index 00000000000..237470ff739 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-core_index.mjs.html @@ -0,0 +1,74 @@ + + + + + + + + Source: workbox-core/index.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import defaultExport from './_default.mjs';
    +import LOG_LEVELS from './models/LogLevels.mjs';
    +import * as _private from './_private.mjs';
    +import './_version.mjs';
    +
    +/**
    + * All of the Workbox service worker libraries use workbox-core for shared
    + * code as well as setting default values that need to be shared (like cache
    + * names).
    + *
    + * @namespace workbox.core
    + */
    +
    +/**
    + * Utilities that are shared with other Workbox modules.
    + *
    + * @alias workbox.core._private
    + * @private
    + */
    +
    +export {
    +  LOG_LEVELS,
    +  _private,
    +};
    +
    +export default defaultExport;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-core_models_LogLevels.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-core_models_LogLevels.mjs.html new file mode 100644 index 00000000000..34f3b18ae2c --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-core_models_LogLevels.mjs.html @@ -0,0 +1,71 @@ + + + + + + + + Source: workbox-core/models/LogLevels.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import '../_version.mjs';
    +
    +/**
    + * The available log levels in Workbox: debug, log, warn, error and silent.
    + *
    + * @property {int} debug Prints all logs from Workbox. Useful for debugging.
    + * @property {int} log Prints console log, warn, error and groups. Default for
    + * debug builds.
    + * @property {int} warn Prints console warn, error and groups. Default for
    + * non-debug builds.
    + * @property {int} error Print console error and groups.
    + * @property {int} silent Force no logging from Workbox.
    + *
    + * @alias workbox.core.LOG_LEVELS
    + */
    +
    +export default {
    +  debug: 0,
    +  log: 1,
    +  warn: 2,
    +  error: 3,
    +  silent: 4,
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-google-analytics__default.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-google-analytics__default.mjs.html new file mode 100644 index 00000000000..ac37956627f --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-google-analytics__default.mjs.html @@ -0,0 +1,231 @@ + + + + + + + + Source: workbox-google-analytics/_default.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2017 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {Queue} from 'workbox-background-sync/Queue.mjs';
    +import {QueuePlugin} from 'workbox-background-sync/QueuePlugin.mjs';
    +import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
    +import {Route} from 'workbox-routing/Route.mjs';
    +import {Router} from 'workbox-routing/Router.mjs';
    +import {NetworkFirst} from 'workbox-strategies/NetworkFirst.mjs';
    +import {NetworkOnly} from 'workbox-strategies/NetworkOnly.mjs';
    +import {
    +  QUEUE_NAME,
    +  MAX_RETENTION_TIME,
    +  GOOGLE_ANALYTICS_HOST,
    +  GTM_HOST,
    +  ANALYTICS_JS_PATH,
    +  GTAG_JS_PATH,
    +  COLLECT_PATH,
    +} from './utils/constants.mjs';
    +import './_version.mjs';
    +
    +/**
    + * Promisifies the FileReader API to await a text response from a Blob.
    + *
    + * @param {Blob} blob
    + * @return {Promise&lt;string>}
    + *
    + * @private
    + */
    +const getTextFromBlob = (blob) => {
    +  return new Promise((resolve, reject) => {
    +    const reader = new FileReader();
    +    reader.onloadend = () => resolve(reader.result);
    +    reader.onerror = () => reject(reader.error);
    +    reader.readAsText(blob);
    +  });
    +};
    +
    +/**
    + * Creates the requestWillDequeue callback to be used with the background
    + * sync queue plugin. The callback takes the failed request and adds the
    + * `qt` param based on the current time, as well as applies any other
    + * user-defined hit modifications.
    + *
    + * @param {Object} config See workbox.googleAnalytics.initialize.
    + * @return {Function} The requestWillDequeu callback function.
    + *
    + * @private
    + */
    +const createRequestWillReplayCallback = (config) => {
    +  return async ({url, timestamp, requestInit}) => {
    +    // Measurement protocol requests can set their payload parameters in either
    +    // the URL query string (for GET requests) or the POST body.
    +    let params;
    +    if (requestInit.body) {
    +      const payload = await getTextFromBlob(requestInit.body);
    +      params = new URLSearchParams(payload);
    +    } else {
    +      params = new URL(url).searchParams;
    +    }
    +
    +    // Set the qt param prior to apply the hitFilter or parameterOverrides.
    +    const queueTime = Date.now() - timestamp;
    +    params.set('qt', queueTime);
    +
    +    if (config.parameterOverrides) {
    +      for (const param of Object.keys(config.parameterOverrides)) {
    +        const value = config.parameterOverrides[param];
    +        params.set(param, value);
    +      }
    +    }
    +
    +    if (typeof config.hitFilter === 'function') {
    +      config.hitFilter.call(null, params);
    +    }
    +
    +    requestInit.body = params.toString();
    +    requestInit.method = 'POST';
    +    requestInit.mode = 'cors';
    +    requestInit.credentials = 'omit';
    +    requestInit.headers = '[["Content-Type", "text/plain"]]';
    +    requestInit.url = `https://${GOOGLE_ANALYTICS_HOST}/${COLLECT_PATH}`;
    +  };
    +};
    +
    +/**
    + * Creates GET and POST routes to catch failed Measurement Protocol hits.
    + *
    + * @param {Queue} queue
    + * @return {Array&lt;Route>} The created routes.
    + *
    + * @private
    + */
    +const createCollectRoutes = (queue) => {
    +  const match = ({url}) => url.hostname === GOOGLE_ANALYTICS_HOST &amp;&amp;
    +      url.pathname === COLLECT_PATH;
    +
    +  const handler = new NetworkOnly({
    +    plugins: [new QueuePlugin(queue)],
    +  });
    +
    +  return [
    +    new Route(match, handler, 'GET'),
    +    new Route(match, handler, 'POST'),
    +  ];
    +};
    +
    +/**
    + * Creates a route with a network first strategy for the analytics.js script.
    + *
    + * @param {string} cacheName
    + * @return {Route} The created route.
    + *
    + * @private
    + */
    +const createAnalyticsJsRoute = (cacheName) => {
    +  const match = ({url}) => url.hostname === GOOGLE_ANALYTICS_HOST &amp;&amp;
    +      url.pathname === ANALYTICS_JS_PATH;
    +  const handler = new NetworkFirst({cacheName});
    +
    +  return new Route(match, handler, 'GET');
    +};
    +
    +/**
    + * Creates a route with a network first strategy for the gtag.js script.
    + *
    + * @param {string} cacheName
    + * @return {Route} The created route.
    + *
    + * @private
    + */
    +const createGtagJsRoute = (cacheName) => {
    +  const match = ({url}) => url.hostname === GTM_HOST &amp;&amp;
    +      url.pathname === GTAG_JS_PATH;
    +  const handler = new NetworkFirst({cacheName});
    +
    +  return new Route(match, handler, 'GET');
    +};
    +
    +/**
    + * @param {Object=} [options]
    + * @param {Object} [options.cacheName] The cache name to store and retrieve
    + *     analytics.js. Defaults to the cache names provided by `workbox-core`.
    + * @param {Object} [options.parameterOverrides]
    + *     [Measurement Protocol parameters](/analytics/devguides/collection/protocol/v1/parameters),
    + *     expressed as key/value pairs, to be added to replayed Google Analytics
    + *     requests. This can be used to, e.g., set a custom dimension indicating
    + *     that the request was replayed.
    + * @param {Function} [options.hitFilter] A function that allows you to modify
    + *     the hit parameters prior to replaying
    + *     the hit. The function is invoked with the original hit's URLSearchParams
    + *     object as its only argument.
    + *
    + * @memberof workbox.googleAnalytics
    + */
    +const initialize = (options = {}) => {
    +  const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);
    +
    +  const queue = new Queue(QUEUE_NAME, {
    +    maxRetentionTime: MAX_RETENTION_TIME,
    +    callbacks: {
    +      requestWillReplay: createRequestWillReplayCallback(options),
    +    },
    +  });
    +
    +  const routes = [
    +    createAnalyticsJsRoute(cacheName),
    +    createGtagJsRoute(cacheName),
    +    ...createCollectRoutes(queue),
    +  ];
    +
    +  const router = new Router();
    +  for (const route of routes) {
    +    router.registerRoute(route);
    +  }
    +
    +  self.addEventListener('fetch', (evt) => {
    +    const responsePromise = router.handleRequest(evt);
    +    if (responsePromise) {
    +      evt.respondWith(responsePromise);
    +    }
    +  });
    +};
    +
    +export {
    +  initialize,
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-google-analytics_index.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-google-analytics_index.mjs.html new file mode 100644 index 00000000000..00e536a67dc --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-google-analytics_index.mjs.html @@ -0,0 +1,54 @@ + + + + + + + + Source: workbox-google-analytics/index.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2017 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import './_version.mjs';
    +
    +/**
    + * @namespace workbox.googleAnalytics
    + */
    +
    +export * from './_default.mjs';
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching__default.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching__default.mjs.html new file mode 100644 index 00000000000..3293edb0447 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching__default.mjs.html @@ -0,0 +1,289 @@ + + + + + + + + Source: workbox-precaching/_default.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.mjs';
    +import PrecacheController from './controllers/PrecacheController.mjs';
    +import './_version.mjs';
    +
    +if (process.env.NODE_ENV !== 'production') {
    +  assert.isSwEnv('workbox-precaching');
    +}
    +
    +let installActivateListenersAdded = false;
    +let fetchListenersAdded = false;
    +let suppressWarnings = false;
    +
    +const cacheName = cacheNames.getPrecacheName();
    +const precacheController = new PrecacheController(cacheName);
    +
    +const _removeIgnoreUrlParams = (origUrlObject, ignoreUrlParametersMatching) => {
    +  // Exclude initial '?'
    +  const searchString = origUrlObject.search.slice(1);
    +
    +  // Split into an array of 'key=value' strings
    +  const keyValueStrings = searchString.split('&amp;');
    +  const keyValuePairs = keyValueStrings.map((keyValueString) => {
    +    // Split each 'key=value' string into a [key, value] array
    +    return keyValueString.split('=');
    +  });
    +  const filteredKeyValuesPairs = keyValuePairs.filter((keyValuePair) => {
    +    return ignoreUrlParametersMatching
    +      .every((ignoredRegex) => {
    +        // Return true iff the key doesn't match any of the regexes.
    +        return !ignoredRegex.test(keyValuePair[0]);
    +      });
    +  });
    +  const filteredStrings = filteredKeyValuesPairs.map((keyValuePair) => {
    +    // Join each [key, value] array into a 'key=value' string
    +    return keyValuePair.join('=');
    +  });
    +
    +  // Join the array of 'key=value' strings into a string with '&amp;' in
    +  // between each
    +  const urlClone = new URL(origUrlObject);
    +  urlClone.search = filteredStrings.join('&amp;');
    +  return urlClone;
    +};
    +
    +/**
    + * This function will take the request URL and manipulate it based on the
    + * configuration options.
    + *
    + * @param {string} url
    + * @param {Object} options
    + * @return {string|null} Returns the URL in the cache that matches the request
    + * if available, other null.
    + *
    + * @private
    + */
    +const _getPrecachedUrl = (url, {
    +  ignoreUrlParametersMatching = [/^utm_/],
    +  directoryIndex = 'index.html',
    +} = {}) => {
    +  const urlObject = new URL(url, location);
    +
    +  // If we precache '/some-url' but the URL referenced from the browser
    +  // is '/some-url#1234', the comparison won't work unless we normalise
    +  // the URLS.
    +  // See https://github.com/GoogleChrome/workbox/issues/488.
    +  urlObject.hash = '';
    +
    +  const cachedUrls = precacheController.getCachedUrls();
    +  if (cachedUrls.indexOf(urlObject.href) !== -1) {
    +    // It's a perfect match
    +    if (process.env.NODE_ENV !== 'production') {
    +      logger.debug(`Precaching found an exact URL match for ` +
    +        getFriendlyURL(urlObject.toString()));
    +    }
    +    return urlObject.href;
    +  }
    +
    +  let strippedUrl = _removeIgnoreUrlParams(
    +    urlObject, ignoreUrlParametersMatching
    +  );
    +  if (cachedUrls.indexOf(strippedUrl.href) !== -1) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      logger.debug(`Precaching found an exact URL match for stripped URL` +
    +        getFriendlyURL(strippedUrl.toString()));
    +    }
    +    return strippedUrl.href;
    +  }
    +
    +  if (directoryIndex &amp;&amp; strippedUrl.pathname.endsWith('/')) {
    +    strippedUrl.pathname += directoryIndex;
    +    if (cachedUrls.indexOf(strippedUrl.href) !== -1) {
    +      if (process.env.NODE_ENV !== 'production') {
    +        logger.debug(`Precaching found an exact URL match with ` +
    +          `'directoryIndex' ${getFriendlyURL(strippedUrl.toString())}`);
    +      }
    +      return strippedUrl.href;
    +    }
    +  }
    +
    +  return null;
    +};
    +
    +const moduleExports = {};
    +
    +/**
    + * Add items to the precache list, removing any duplicates and
    + * store the files in the
    + * ["precache cache"]{@link module:workbox-core.cacheNames} when the service
    + * worker installs.
    + *
    + * This method can be called multiple times.
    + *
    + * Please note: This method **will not** serve any of the cached files for you,
    + * it only precaches files. To respond to a network request you call
    + * [addRoute()]{@link module:workbox-precaching.addRoute}.
    + *
    + * If you have a single array of files to precache, you can just call
    + * [precacheAndRoute()]{@link module:workbox-precaching.precacheAndRoute}.
    + *
    + * @param {Array&lt;Object|string>} entries Array of entries to precache.
    + *
    + * @alias workbox.precaching.precache
    + */
    +moduleExports.precache = (entries) => {
    +  precacheController.addToCacheList(entries);
    +
    +  if (installActivateListenersAdded || entries.length &lt;= 0) {
    +    return;
    +  }
    +
    +  installActivateListenersAdded = true;
    +  self.addEventListener('install', (event) => {
    +    event.waitUntil(precacheController.install({suppressWarnings}));
    +  });
    +  self.addEventListener('activate', (event) => {
    +    event.waitUntil(precacheController.cleanup());
    +  });
    +};
    +
    +/**
    + * Add a `fetch` listener to the service worker that will
    + * respond to
    + * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests}
    + * with precached assets.
    + *
    + * Requests for assets that aren't precached, the `FetchEvent` will not be
    + * responded to, allowing the event to fall through to other `fetch` event
    + * listeners.
    + *
    + * @param {Object} options
    + * @param {string} [options.directoryIndex=index.html] The `directoryIndex` will
    + * check cache entries for a URLs ending with '/' to see if there is a hit when
    + * appending the `directoryIndex` value.
    + * @param {Array&lt;RegExp>} [options.ignoreUrlParametersMatching=[/^utm_/]] An
    + * array of regex's to remove search params when looking for a cache match.
    + *
    + * @alias workbox.precaching.addRoute
    + */
    +moduleExports.addRoute = (options) => {
    +  if (fetchListenersAdded) {
    +    // TODO: Throw error here.
    +    return;
    +  }
    +
    +  fetchListenersAdded = true;
    +  self.addEventListener('fetch', (event) => {
    +    const precachedUrl = _getPrecachedUrl(event.request.url, options);
    +    if (!precachedUrl) {
    +      if (process.env.NODE_ENV !== 'production') {
    +        logger.debug(`Precaching found no match for ` +
    +          getFriendlyURL(event.request.url));
    +      }
    +      return;
    +    }
    +
    +    let responsePromise = caches.open(cacheName)
    +    .then((cache) => {
    +      return cache.match(precachedUrl);
    +    });
    +    if (process.env.NODE_ENV !== 'production') {
    +      responsePromise = responsePromise.then((response) => {
    +        // Workbox is going to handle the route.
    +        // print the routing details to the console.
    +        logger.groupCollapsed(`Precaching is responding to: ` +
    +          getFriendlyURL(event.request.url));
    +        logger.log(`Serving the precached url: ${precachedUrl}`);
    +
    +        // The Request and Response objects contains a great deal of
    +        // information, hide it under a group in case developers want to see it.
    +        logger.groupCollapsed(`View request details here.`);
    +        logger.unprefixed.log(event.request);
    +        logger.groupEnd();
    +
    +        logger.groupCollapsed(`View response details here.`);
    +        logger.unprefixed.log(response);
    +        logger.groupEnd();
    +
    +        logger.groupEnd();
    +        return response;
    +      });
    +    }
    +    event.respondWith(responsePromise);
    +  });
    +};
    +
    +/**
    + * This method will add entries to the precache list and add a route to
    + * respond to fetch events.
    + *
    + * This is a convenience method that will call
    + * [precache()]{@link module:workbox-precaching.precache} and
    + * [addRoute()]{@link module:workbox-precaching.addRoute} in a single call.
    + *
    + * @param {Array&lt;Object|string>} entries Array of entries to precache.
    + * @param {Object} options See
    + * [addRoute() options]{@link module:workbox-precaching.addRoute}.
    + *
    + * @alias workbox.precaching.precacheAndRoute
    + */
    +moduleExports.precacheAndRoute = (entries, options) => {
    +  moduleExports.precache(entries);
    +  moduleExports.addRoute(options);
    +};
    +
    +/**
    + * Warnings will be logged if any of the precached assets are entered without
    + * a `revision` property. This is extremely dangerous if the URL's aren't
    + * revisioned. However, the warnings can be supressed with this method.
    + *
    + * @param {boolean} suppress
    + *
    + * @alias workbox.precaching.suppressWarnings
    + */
    +moduleExports.suppressWarnings = (suppress) => {
    +  suppressWarnings = suppress;
    +};
    +
    +export default moduleExports;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching__types.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching__types.mjs.html new file mode 100644 index 00000000000..cab869afe41 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching__types.mjs.html @@ -0,0 +1,81 @@ + + + + + + + + Source: workbox-precaching/_types.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import './_version.mjs';
    +
    +/**
    + * @typedef {Object} InstallResult
    + * @property {
    + * Array&lt;module:workbox-precaching.PrecacheController.PrecacheEntry|string>
    + * } updatedEntries List of entries
    + * supplied for precaching that were precached.
    + * @property {
    + * Array&lt;module:workbox-precaching.PrecacheController.PrecacheEntry|string>
    + * } notUpdatedEntries List of entries
    + * supplied for precaching that were already precached.
    + *
    + * @memberof workbox.precaching
    + */
    +
    +/**
    + * @typedef {Object} CleanupResult
    + * @property {Array&lt;string>} deletedCacheRequests List of URLs that were
    + * deleted from the precache cache.
    + * @property {Array&lt;string>} deletedRevisionDetails
    + * List of URLs that were deleted from the precache cache.
    + *
    + * @memberof workbox.precaching
    + */
    +
    +/**
    + * @typedef {Object} PrecacheEntry
    + * @property {string} url URL to precache.
    + * @property {string} revision Revision information for the URL.
    + *
    + * @memberof workbox.precaching
    + */
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching_controllers_PrecacheController.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching_controllers_PrecacheController.mjs.html new file mode 100644 index 00000000000..5d462626daa --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching_controllers_PrecacheController.mjs.html @@ -0,0 +1,351 @@ + + + + + + + + Source: workbox-precaching/controllers/PrecacheController.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
    +import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
    +import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.mjs';
    +import {cacheWrapper} from 'workbox-core/_private/cacheWrapper.mjs';
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +import PrecacheEntry from '../models/PrecacheEntry.mjs';
    +import PrecachedDetailsModel from '../models/PrecachedDetailsModel.mjs';
    +import showWarningsIfNeeded from '../utils/showWarningsIfNeeded.mjs';
    +import openInstallLogGroup from '../utils/openInstallLogGroup.mjs';
    +import printCleanupDetails from '../utils/printCleanupDetails.mjs';
    +import cleanRedirect from '../utils/cleanRedirect.mjs';
    +import '../_version.mjs';
    +
    +/**
    + * Performs efficient precaching of assets.
    + *
    + * @memberof workbox.precaching
    + */
    +class PrecacheController {
    +  /**
    +   * Create a new PrecacheController.
    +   *
    +   * @param {string} cacheName
    +   */
    +  constructor(cacheName) {
    +    this._cacheName = cacheNames.getPrecacheName(cacheName);
    +    this._entriesToCacheMap = new Map();
    +    this._precacheDetailsModel = new PrecachedDetailsModel(this._cacheName);
    +  }
    +
    +  /**
    +   * This method will add items to the precache list, removing duplicates
    +   * and ensuring the information is valid.
    +   *
    +   * @param {
    +   * Array&lt;module:workbox-precaching.PrecacheController.PrecacheEntry|string>
    +   * } entries Array of entries to
    +   * precache.
    +   */
    +  addToCacheList(entries) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isArray(entries, {
    +        moduleName: 'workbox-precaching',
    +        className: 'PrecacheController',
    +        funcName: 'addToCacheList',
    +        paramName: 'entries',
    +      });
    +    }
    +
    +    entries.map((userEntry) => {
    +      this._addEntryToCacheList(
    +        this._parseEntry(userEntry)
    +      );
    +    });
    +  }
    +
    +  /**
    +   * This method returns a precache entry.
    +   *
    +   * @private
    +   * @param {string|Object} input
    +   * @return {PrecacheEntry}
    +   */
    +  _parseEntry(input) {
    +    switch (typeof input) {
    +      case 'string': {
    +        if (process.env.NODE_ENV !== 'production') {
    +          if (input.length === 0) {
    +            throw new WorkboxError(
    +              'add-to-cache-list-unexpected-type', {
    +                entry: input,
    +              }
    +            );
    +          }
    +        }
    +
    +        return new PrecacheEntry(input, input, input);
    +      }
    +      case 'object': {
    +        if (process.env.NODE_ENV !== 'production') {
    +          if (!input || !input.url) {
    +            throw new WorkboxError(
    +              'add-to-cache-list-unexpected-type', {
    +                entry: input,
    +              }
    +            );
    +          }
    +        }
    +
    +        return new PrecacheEntry(
    +          input, input.url, input.revision || input.url, !!input.revision);
    +      }
    +      default:
    +        throw new WorkboxError('add-to-cache-list-unexpected-type', {
    +          entry: input,
    +        });
    +    }
    +  }
    +
    +  /**
    +   * Adds an entry to the precache list, accounting for possible duplicates.
    +   *
    +   * @private
    +   * @param {PrecacheEntry} entryToAdd
    +   */
    +  _addEntryToCacheList(entryToAdd) {
    +    // Check if the entry is already part of the map
    +    const existingEntry = this._entriesToCacheMap.get(entryToAdd._entryId);
    +    if (!existingEntry) {
    +      this._entriesToCacheMap.set(entryToAdd._entryId, entryToAdd);
    +      return;
    +    }
    +
    +    // Duplicates are fine, but make sure the revision information
    +    // is the same.
    +    if (existingEntry._revision !== entryToAdd._revision) {
    +      throw new WorkboxError('add-to-cache-list-conflicting-entries', {
    +        firstEntry: existingEntry._originalInput,
    +        secondEntry: entryToAdd._originalInput,
    +      });
    +    }
    +  }
    +
    +  /**
    +   * Call this method from a service work install event to start
    +   * precaching assets.
    +   *
    +   * @param {Object} options
    +   * @param {boolean} options.suppressWarnings Suppress warning messages.
    +   * @return {
    +   * Promise&lt;module:workbox-precaching.PrecacheController.InstallResult>}
    +   */
    +  async install(options = {}) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      if (options.suppressWarnings !== true) {
    +        showWarningsIfNeeded(this._entriesToCacheMap);
    +      }
    +    }
    +
    +    const entriesToPrecache = [];
    +    const entriesAlreadyPrecached = [];
    +
    +    for (const precacheEntry of this._entriesToCacheMap.values()) {
    +      if (await this._precacheDetailsModel._isEntryCached(precacheEntry)) {
    +        entriesAlreadyPrecached.push(precacheEntry);
    +      } else {
    +        entriesToPrecache.push(precacheEntry);
    +      }
    +    }
    +
    +    if (process.env.NODE_ENV !== 'production') {
    +      openInstallLogGroup(entriesToPrecache, entriesAlreadyPrecached);
    +    }
    +
    +    // Wait for all requests to be cached.
    +    await Promise.all(entriesToPrecache.map((precacheEntry) => {
    +      return this._cacheEntry(precacheEntry);
    +    }));
    +
    +    if (process.env.NODE_ENV !== 'production') {
    +      logger.groupEnd();
    +    }
    +
    +    return {
    +      updatedEntries: entriesToPrecache,
    +      notUpdatedEntries: entriesAlreadyPrecached,
    +    };
    +  }
    +
    +  /**
    +   * Requests the entry and saves it to the cache if the response
    +   * is valid.
    +   *
    +   * @private
    +   * @param {BaseCacheEntry} precacheEntry The entry to fetch and cache.
    +   * @return {Promise&lt;boolean>} Returns a promise that resolves once the entry
    +   * has been fetched and cached or skipped if no update is needed. The
    +   * promise resolves with true if the entry was cached / updated and
    +   * false if the entry is already cached and up-to-date.
    +   */
    +  async _cacheEntry(precacheEntry) {
    +    let response = await fetchWrapper.fetch(
    +      precacheEntry._networkRequest,
    +    );
    +
    +    if (response.redirected) {
    +      response = await cleanRedirect(response);
    +    }
    +
    +    await cacheWrapper.put(this._cacheName,
    +      precacheEntry._cacheRequest, response);
    +
    +    await this._precacheDetailsModel._addEntry(precacheEntry);
    +
    +    return true;
    +  }
    +
    +  /**
    +   * Compare the URLs and determines which assets are no longer required
    +   * in the cache.
    +   *
    +   * This should be called in the service worker activate event.
    +   *
    +   * @return {
    +   * Promise&lt;module:workbox-precaching.PrecacheController.CleanupResult>}
    +   * Resolves with an object containing details of the deleted cache requests
    +   * and precache revision details.
    +   */
    +  async cleanup() {
    +    const expectedCacheUrls = [];
    +    this._entriesToCacheMap.forEach((entry) => {
    +      const fullUrl = new URL(entry._cacheRequest.url, location).toString();
    +      expectedCacheUrls.push(fullUrl);
    +    });
    +
    +    const [deletedCacheRequests, deletedRevisionDetails] = await Promise.all([
    +      this._cleanupCache(expectedCacheUrls),
    +      this._cleanupDetailsModel(expectedCacheUrls),
    +    ]);
    +
    +    if (process.env.NODE_ENV !== 'production') {
    +      printCleanupDetails(deletedCacheRequests, deletedRevisionDetails);
    +    }
    +
    +    return {
    +      deletedCacheRequests,
    +      deletedRevisionDetails,
    +    };
    +  }
    +
    +  /**
    +   * Goes through all the cache entries and removes any that are
    +   * outdated.
    +   *
    +   * @private
    +   * @param {Array&lt;string>} expectedCacheUrls Array of URLs that are
    +   * expected to be cached.
    +   * @return {Promise&lt;Array&lt;string>>} Resolves to an array of URLs
    +   * of cached requests that were deleted.
    +   */
    +  async _cleanupCache(expectedCacheUrls) {
    +    if (!await caches.has(this._cacheName)) {
    +      // Cache doesn't exist, so nothing to delete
    +      return [];
    +    }
    +
    +    const cache = await caches.open(this._cacheName);
    +    const cachedRequests = await cache.keys();
    +    const cachedRequestsToDelete = cachedRequests.filter((cachedRequest) => {
    +      return !expectedCacheUrls.includes(
    +        new URL(cachedRequest.url, location).toString()
    +      );
    +    });
    +
    +    await Promise.all(
    +      cachedRequestsToDelete.map((cacheUrl) => cache.delete(cacheUrl))
    +    );
    +
    +    return cachedRequestsToDelete.map((request) => request.url);
    +  }
    +
    +  /**
    +   * Goes through all entries in indexedDB and removes any that are outdated.
    +   *
    +   * @private
    +   * @param {Array&lt;string>} expectedCacheUrls Array of URLs that are
    +   * expected to be cached.
    +   * @return {Promise&lt;Array&lt;string>>} Resolves to an array of URLs removed
    +   * from indexedDB.
    +   */
    +  async _cleanupDetailsModel(expectedCacheUrls) {
    +    const revisionedEntries = await this._precacheDetailsModel._getAllEntries();
    +
    +    const detailsToDelete = (Object.keys(revisionedEntries))
    +      .filter((entryId) => {
    +        const entry = revisionedEntries[entryId];
    +        const fullUrl = new URL(entry.url, location).toString();
    +        return !expectedCacheUrls.includes(fullUrl);
    +      });
    +
    +    await Promise.all(
    +      detailsToDelete.map(
    +        (detailsId) => this._precacheDetailsModel._deleteEntry(detailsId)
    +      )
    +    );
    +    return detailsToDelete.map((detailsId) => {
    +      return revisionedEntries[detailsId].url;
    +    });
    +  }
    +
    +  /**
    +   * Returns an array of fully qualified URL's that will be precached.
    +   *
    +   * @return {Array&lt;string>} An array of URLs.
    +   */
    +  getCachedUrls() {
    +    return Array.from(this._entriesToCacheMap.keys())
    +    .map((url) => new URL(url, location).href);
    +  }
    +}
    +
    +export default PrecacheController;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching_index.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching_index.mjs.html new file mode 100644 index 00000000000..a95a171f7a6 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-precaching_index.mjs.html @@ -0,0 +1,67 @@ + + + + + + + + Source: workbox-precaching/index.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import defaultPrecachingExport from './_default.mjs';
    +import './_version.mjs';
    +
    +/**
    + * Most consumers of this module will want to use the
    + * [precacheAndRoute()]{@link workbox.precaching.precacheAndRoute}
    + * method to add assets to the Cache and respond to network requests with these
    + * cached assets.
    + *
    + * If you require finer grained control, you can use the
    + * [PrecacheController]{@link workbox.precaching.PrecacheController}
    + * to determine when performed.
    + *
    + * @namespace workbox.precaching
    + */
    +
    +export * from './_public.mjs';
    +
    +export default defaultPrecachingExport;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_NavigationRoute.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_NavigationRoute.mjs.html new file mode 100644 index 00000000000..c9660dfc211 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_NavigationRoute.mjs.html @@ -0,0 +1,153 @@ + + + + + + + + Source: workbox-routing/NavigationRoute.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2016 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    + */
    +
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +import {Route} from './Route.mjs';
    +import './_version.mjs';
    +
    +/**
    + * NavigationRoute makes it easy to create a [Route]{@link
    + * workbox.routing.Route} that matches for browser
    + * [navigation requests]{@link /web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}.
    + *
    + * It will only match incoming Requests whose
    + * [`mode`]{@link https://fetch.spec.whatwg.org/#concept-request-mode}
    + * is set to `navigate`.
    + *
    + * You can optionally only apply this route to a subset of navigation requests
    + * by using one or both of the `blacklist` and `whitelist` parameters.
    + *
    + * @memberof workbox.routing
    + * @extends workbox.routing.Route
    + */
    +class NavigationRoute extends Route {
    +  /**
    +   * If both `blacklist` and `whiltelist` are provided, the `blacklist` will
    +   * take precedence and the request will not match this route.
    +   *
    +   * The regular expressions in `whitelist` and `blacklist`
    +   * are matched against the concatenated
    +   * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname}
    +   * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search}
    +   * portions of the requested URL.
    +   *
    +   * @param {workbox.routing.Route~handlerCallback} handler A callback
    +   * function that returns a Promise resulting in a Response.
    +   * @param {Object} options
    +   * @param {Array&lt;RegExp>} [options.blacklist] If any of these patterns match,
    +   * the route will not handle the request (even if a whitelist RegExp matches).
    +   * @param {Array&lt;RegExp>} [options.whitelist=[/./]] If any of these patterns
    +   * match the URL's pathname and search parameter, the route will handle the
    +   * request (assuming the blacklist doesn't match).
    +   */
    +  constructor(handler, {whitelist = [/./], blacklist = []} = {}) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isArrayOfClass(whitelist, RegExp, {
    +        moduleName: 'workbox-routing',
    +        className: 'NavigationRoute',
    +        funcName: 'constructor',
    +        paramName: 'options.whitelist',
    +      });
    +      assert.isArrayOfClass(blacklist, RegExp, {
    +        moduleName: 'workbox-routing',
    +        className: 'NavigationRoute',
    +        funcName: 'constructor',
    +        paramName: 'options.blacklist',
    +      });
    +    }
    +
    +    super((...args) => this._match(...args), handler);
    +
    +    this._whitelist = whitelist;
    +    this._blacklist = blacklist;
    +  }
    +
    +  /**
    +   * Routes match handler.
    +   *
    +   * @param {Object} input
    +   * @param {FetchEvent} input.event
    +   * @param {URL} input.url
    +   * @return {boolean}
    +   *
    +   * @private
    +   */
    +  _match({event, url}) {
    +    if (event.request.mode !== 'navigate') {
    +      return false;
    +    }
    +
    +    const pathnameAndSearch = url.pathname + url.search;
    +
    +    if (this._blacklist.some((regExp) => regExp.test(pathnameAndSearch))) {
    +      if (process.env.NODE_ENV !== 'production') {
    +        logger.debug(`The navigation route is not being used, since the ` +
    +          `request URL matches both the whitelist and blacklist.`);
    +      }
    +      return false;
    +    }
    +
    +    if (this._whitelist.some((regExp) => regExp.test(pathnameAndSearch))) {
    +      if (process.env.NODE_ENV !== 'production') {
    +        logger.debug(`The navigation route is being used.`);
    +      }
    +      return true;
    +    } else {
    +      if (process.env.NODE_ENV !== 'production') {
    +        logger.debug(
    +          `The navigation route is not being used, since the ` +
    +          `URL being navigated to doesn't match the whitelist.`
    +        );
    +      }
    +    }
    +
    +    return false;
    +  }
    +}
    +
    +export {NavigationRoute};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_RegExpRoute.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_RegExpRoute.mjs.html new file mode 100644 index 00000000000..d826fb8f04a --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_RegExpRoute.mjs.html @@ -0,0 +1,125 @@ + + + + + + + + Source: workbox-routing/RegExpRoute.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2017 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +import {Route} from './Route.mjs';
    +import './_version.mjs';
    +
    +/**
    + * RegExpRoute makes it easy to create a regular expression based
    + * [Route]{@link workbox.routing.Route}.
    + *
    + * For same-origin requests the RegExp only needs to match part of the URL. For
    + * requests against third-party servers, you must define a RegExp that matches
    + * the start of the URL.
    + *
    + * [See the module docs for info.]{@link /web/tools/workbox/v3/modules/workbox-routing}
    + *
    + * @memberof workbox.routing
    + * @extends workbox.routing.Route
    + */
    +class RegExpRoute extends Route {
    +  /**
    +   * If the regulard expression contains
    +   * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},
    +   * th ecaptured values will be passed to the
    +   * [handler's]{@link workbox.routing.Route~handlerCallback} `params`
    +   * argument.
    +   *
    +   * @param {RegExp} regExp The regular expression to match against URLs.
    +   * @param {workbox.routing.Route~handlerCallback} handler A callback
    +   * function that returns a Promise resulting in a Response.
    +   * @param {string} [method='GET'] The HTTP method to match the Route
    +   * against.
    +   */
    +  constructor(regExp, handler, method) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isInstance(regExp, RegExp, {
    +        moduleName: 'workbox-routing',
    +        className: 'RegExpRoute',
    +        funcName: 'constructor',
    +        paramName: 'pattern',
    +      });
    +    }
    +
    +    const match = ({url}) => {
    +      const result = regExp.exec(url.href);
    +
    +      // Return null immediately if there's no match.
    +      if (!result) {
    +        return null;
    +      }
    +
    +      // Require that the match start at the first character in the URL string
    +      // if it's a cross-origin request.
    +      // See https://github.com/GoogleChrome/workbox/issues/281 for the context
    +      // behind this behavior.
    +      if ((url.origin !== location.origin) &amp;&amp; (result.index !== 0)) {
    +        if (process.env.NODE_ENV !== 'production') {
    +          logger.debug(
    +            `The regular expression '${regExp}' only partially matched ` +
    +            `against the cross-origin URL '${url}'. RegExpRoute's will only ` +
    +            `handle cross-origin requests if they match the entire URL.`
    +          );
    +        }
    +
    +        return null;
    +      }
    +
    +      // If the route matches, but there aren't any capture groups defined, then
    +      // this will return [], which is truthy and therefore sufficient to
    +      // indicate a match.
    +      // If there are capture groups, then it will return their values.
    +      return result.slice(1);
    +    };
    +
    +    super(match, handler, method);
    +  }
    +}
    +
    +export {RegExpRoute};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_Route.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_Route.mjs.html new file mode 100644 index 00000000000..c3553d11e85 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_Route.mjs.html @@ -0,0 +1,97 @@ + + + + + + + + Source: workbox-routing/Route.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2017 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +
    +import {defaultMethod, validMethods} from './utils/constants.mjs';
    +import normalizeHandler from './utils/normalizeHandler.mjs';
    +import './_version.mjs';
    +
    +/**
    + * A `Route` consists of a pair of callback functions, "match" and "handler".
    + * The "match" callback determine if a route should be used to "handle" a
    + * request by returning a non-falsy value if it can. The "handler" callback
    + * is called when there is a match and should return a Promise that resolves
    + * to a `Response`.
    + *
    + * @memberof workbox.routing
    + */
    +class Route {
    +  /**
    +   * Constructor for Route class.
    +   *
    +   * @param {workbox.routing.Route~matchCallback} match
    +   * A callback function that determines whether the route matches a given
    +   * `fetch` event by returning a non-falsy value.
    +   * @param {workbox.routing.Route~handlerCallback} handler A callback
    +   * function that returns a Promise resolving to a Response.
    +   * @param {string} [method='GET'] The HTTP method to match the Route
    +   * against.
    +   */
    +  constructor(match, handler, method) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isType(match, 'function', {
    +        moduleName: 'workbox-routing',
    +        className: 'Route',
    +        funcName: 'constructor',
    +        paramName: 'match',
    +      });
    +
    +      if (method) {
    +        assert.isOneOf(method, validMethods, {paramName: 'method'});
    +      }
    +    }
    +
    +    // These values are referenced directly by Router so cannot be
    +    // altered by minifification.
    +    this.handler = normalizeHandler(handler);
    +    this.match = match;
    +    this.method = method || defaultMethod;
    +  }
    +}
    +
    +export {Route};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_Router.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_Router.mjs.html new file mode 100644 index 00000000000..5642f0e5b62 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_Router.mjs.html @@ -0,0 +1,345 @@ + + + + + + + + Source: workbox-routing/Router.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2017 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
    +import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.mjs';
    +
    +import normalizeHandler from './utils/normalizeHandler.mjs';
    +import './_version.mjs';
    +
    +/**
    + * The Router can be used to process a FetchEvent through one or more
    + * [Routes]{@link workbox.routing.Route} responding  with a Request if
    + * a matching route exists.
    + *
    + * If no route matches a given a request, the Router will use a "default"
    + * handler if one is defined.
    + *
    + * Should the matching Route throw an error, the Router will use a "catch"
    + * handler if one is defined to gracefully deal with issues and respond with a
    + * Request.
    + *
    + * If a request matches multiple routes, the **earliest** registered route will
    + * be used to respond to the request.
    + *
    + * @memberof workbox.routing
    + */
    +class Router {
    +  /**
    +   * Initializes a new Router.
    +   */
    +  constructor() {
    +    // _routes will contain a mapping of HTTP method name ('GET', etc.) to an
    +    // array of all the corresponding Route instances that are registered.
    +    this._routes = new Map();
    +  }
    +
    +  /**
    +   * Apply the routing rules to a FetchEvent object to get a Response from an
    +   * appropriate Route's handler.
    +   *
    +   * @param {FetchEvent} event The event from a service worker's 'fetch' event
    +   * listener.
    +   * @return {Promise&lt;Response>|undefined} A promise is returned if a
    +   * registered route can handle the FetchEvent's request. If there is no
    +   * matching route and there's no `defaultHandler`, `undefined` is returned.
    +   */
    +  handleRequest(event) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isInstance(event, FetchEvent, {
    +        moduleName: 'workbox-routing',
    +        className: 'Router',
    +        funcName: 'handleRequest',
    +        paramName: 'event',
    +      });
    +    }
    +
    +    const url = new URL(event.request.url);
    +    if (!url.protocol.startsWith('http')) {
    +      if (process.env.NODE_ENV !== 'production') {
    +        logger.debug(
    +          `Workbox Router only supports URLs that start with 'http'.`);
    +      }
    +      return;
    +    }
    +
    +    let route = null;
    +    let handler = null;
    +    let params = null;
    +    let debugMessages = [];
    +
    +    const result = this._findHandlerAndParams(event, url);
    +    handler = result.handler;
    +    params = result.params;
    +    route = result.route;
    +    if (process.env.NODE_ENV !== 'production') {
    +      if (handler) {
    +        debugMessages.push([
    +          `Found a route to handle this request:`, route,
    +        ]);
    +
    +        if (params) {
    +          debugMessages.push([
    +            `Passing the following params to the route's handler:`, params,
    +          ]);
    +        }
    +      }
    +    }
    +
    +    // If we don't have a handler because there was no matching route, then
    +    // fall back to defaultHandler if that's defined.
    +    if (!handler &amp;&amp; this._defaultHandler) {
    +      if (process.env.NODE_ENV !== 'production') {
    +        debugMessages.push(`Failed to find a matching route. Falling ` +
    +          `back to the default handler.`);
    +
    +        // This is used for debugging in logs in the case of an error.
    +        route = '[Default Handler]';
    +      }
    +      handler = this._defaultHandler;
    +    }
    +
    +    if (!handler) {
    +      if (process.env.NODE_ENV !== 'production') {
    +        // No handler so Workbox will do nothing. If logs is set of debug
    +        // i.e. verbose, we should print out this information.
    +        logger.debug(`No route found for: ${getFriendlyURL(url)}`);
    +      }
    +      return;
    +    }
    +
    +    if (process.env.NODE_ENV !== 'production') {
    +      // We have a handler, meaning Workbox is going to handle the route.
    +      // print the routing details to the console.
    +      logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
    +      debugMessages.forEach((msg) => {
    +        if (Array.isArray(msg)) {
    +          logger.log(...msg);
    +        } else {
    +          logger.log(msg);
    +        }
    +      });
    +
    +      // The Request and Response objects contains a great deal of information,
    +      // hide it under a group in case developers want to see it.
    +      logger.groupCollapsed(`View request details here.`);
    +      logger.unprefixed.log(event.request);
    +      logger.groupEnd();
    +
    +      logger.groupEnd();
    +    }
    +
    +    // Wrap in try and catch in case the handle method throws a synchronous
    +    // error. It should still callback to the catch handler.
    +    let responsePromise;
    +    try {
    +      responsePromise = handler.handle({url, event, params});
    +    } catch (err) {
    +      responsePromise = Promise.reject(err);
    +    }
    +
    +    if (responsePromise &amp;&amp; this._catchHandler) {
    +      responsePromise = responsePromise.catch((err) => {
    +        if (process.env.NODE_ENV !== 'production') {
    +          // Still include URL here as it will be async from the console group
    +          // and may not make sense without the URL
    +          logger.groupCollapsed(`Error thrown when responding to: ` +
    +            ` ${getFriendlyURL(url)}. Falling back to Catch Handler.`);
    +          logger.unprefixed.error(`Error thrown by:`, route);
    +          logger.unprefixed.error(err);
    +          logger.groupEnd();
    +        }
    +        return this._catchHandler.handle({url, event, err});
    +      });
    +    }
    +
    +    return responsePromise;
    +  }
    +
    +  /**
    +   * Checks the incoming `event.request` against the registered routes, and if
    +   * there's a match, returns the corresponding handler along with any params
    +   * generated by the match.
    +   *
    +   * @param {FetchEvent} event
    +   * @param {URL} url
    +   * @return {Object} Returns an object with `handler` and `params` properties.
    +   * They are populated if a matching route was found or `undefined` otherwise.
    +   *
    +   * @private
    +   */
    +  _findHandlerAndParams(event, url) {
    +    const routes = this._routes.get(event.request.method) || [];
    +    for (const route of routes) {
    +      let matchResult = route.match({url, event});
    +      if (matchResult) {
    +        if (Array.isArray(matchResult) &amp;&amp; matchResult.length === 0) {
    +          // Instead of passing an empty array in as params, use undefined.
    +          matchResult = undefined;
    +        } else if ((matchResult.constructor === Object &amp;&amp;
    +          Object.keys(matchResult).length === 0) || matchResult === true) {
    +          // Instead of passing an empty object in as params, use undefined.
    +          matchResult = undefined;
    +        }
    +
    +        // Break out of the loop and return the appropriate values as soon as
    +        // we have a match.
    +        return {
    +          route,
    +          params: matchResult,
    +          handler: route.handler,
    +        };
    +      }
    +    }
    +
    +    // If we didn't have a match, then return undefined values.
    +    return {handler: undefined, params: undefined};
    +  }
    +
    +  /**
    +   * Define a default `handler` that's called when no routes explicitly
    +   * match the incoming request.
    +   *
    +   * Without a default handler, unmatched requests will go against the
    +   * network as if there were no service worker present.
    +   *
    +   * @param {workbox.routing.Route~handlerCallback} handler A callback
    +   * function that returns a Promise resulting in a Response.
    +   */
    +  setDefaultHandler(handler) {
    +    this._defaultHandler = normalizeHandler(handler);
    +  }
    +
    +  /**
    +   * If a Route throws an error while handling a request, this `handler`
    +   * will be called and given a chance to provide a response.
    +   *
    +   * @param {workbox.routing.Route~handlerCallback} handler A callback
    +   * function that returns a Promise resulting in a Response.
    +   */
    +  setCatchHandler(handler) {
    +    this._catchHandler = normalizeHandler(handler);
    +  }
    +
    +  /**
    +   * Registers a route with the router.
    +   *
    +   * @param {workbox.routing.Route} route The route to register.
    +   */
    +  registerRoute(route) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isType(route, 'object', {
    +        moduleName: 'workbox-routing',
    +        className: 'Router',
    +        funcName: 'registerRoute',
    +        paramName: 'route',
    +      });
    +
    +      assert.hasMethod(route, 'match', {
    +        moduleName: 'workbox-routing',
    +        className: 'Router',
    +        funcName: 'registerRoute',
    +        paramName: 'route',
    +      });
    +
    +      assert.isType(route.handler, 'object', {
    +        moduleName: 'workbox-routing',
    +        className: 'Router',
    +        funcName: 'registerRoute',
    +        paramName: 'route',
    +      });
    +
    +      assert.hasMethod(route.handler, 'handle', {
    +        moduleName: 'workbox-routing',
    +        className: 'Router',
    +        funcName: 'registerRoute',
    +        paramName: 'route.handler',
    +      });
    +
    +      assert.isType(route.method, 'string', {
    +        moduleName: 'workbox-routing',
    +        className: 'Router',
    +        funcName: 'registerRoute',
    +        paramName: 'route.method',
    +      });
    +    }
    +
    +    if (!this._routes.has(route.method)) {
    +      this._routes.set(route.method, []);
    +    }
    +
    +    // Give precedence to all of the earlier routes by adding this additional
    +    // route to the end of the array.
    +    this._routes.get(route.method).push(route);
    +  }
    +
    +  /**
    +   * Unregisters a route with the router.
    +   *
    +   * @param {workbox.routing.Route} route The route to unregister.
    +   */
    +  unregisterRoute(route) {
    +    if (!this._routes.has(route.method)) {
    +      throw new WorkboxError(
    +        'unregister-route-but-not-found-with-method', {
    +          method: route.method,
    +        }
    +      );
    +    }
    +
    +    const routeIndex = this._routes.get(route.method).indexOf(route);
    +    if (routeIndex > -1) {
    +      this._routes.get(route.method).splice(routeIndex, 1);
    +    } else {
    +      throw new WorkboxError('unregister-route-route-not-registered');
    +    }
    +  }
    +}
    +
    +export {Router};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing__default.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing__default.mjs.html new file mode 100644 index 00000000000..7e4ef468344 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing__default.mjs.html @@ -0,0 +1,219 @@ + + + + + + + + Source: workbox-routing/_default.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import {NavigationRoute} from './NavigationRoute.mjs';
    +import {RegExpRoute} from './RegExpRoute.mjs';
    +import {Router} from './Router.mjs';
    +import {Route} from './Route.mjs';
    +import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +import './_version.mjs';
    +
    +if (process.env.NODE_ENV !== 'production') {
    +  assert.isSwEnv('workbox-routing');
    +}
    +
    +/**
    + * @private
    + */
    +class DefaultRouter extends Router {
    +  /**
    +   * Easily register a RegExp, string, or function with a caching
    +   * strategy to the Router.
    +   *
    +   * This method will generate a Route for you if needed and
    +   * call [Router.registerRoute()]{@link
    +   * workbox.routing.Router#registerRoute}.
    +   *
    +   * @param {
    +   * RegExp|
    +   * string|
    +   * workbox.routing.Route~matchCallback|
    +   * workbox.routing.Route
    +   * } capture
    +   * If the capture param is a `Route`, all other arguments will be ignored.
    +   * @param {workbox.routing.Route~handlerCallback} handler A callback
    +   * function that returns a Promise resulting in a Response.
    +   * @param {string} [method='GET'] The HTTP method to match the Route
    +   * against.
    +   * @return {workbox.routing.Route} The generated `Route`(Useful for
    +   * unregistering).
    +   *
    +   * @alias workbox.routing.registerRoute
    +   */
    +  registerRoute(capture, handler, method = 'GET') {
    +    let route;
    +
    +    if (typeof capture === 'string') {
    +      const captureUrl = new URL(capture, location);
    +
    +      if (process.env.NODE_ENV !== 'production') {
    +        if (!(capture.startsWith('/') || capture.startsWith('http'))) {
    +          throw new WorkboxError('invalid-string', {
    +            moduleName: 'workbox-routing',
    +            className: 'DefaultRouter',
    +            funcName: 'registerRoute',
    +            paramName: 'capture',
    +          });
    +        }
    +
    +        // We want to check if Express-style wildcards are in the pathname only.
    +        // TODO: Remove this log message in v4.
    +        const valueToCheck = capture.startsWith('http') ?
    +          captureUrl.pathname :
    +          capture;
    +        // See https://github.com/pillarjs/path-to-regexp#parameters
    +        const wildcards = '[*:?+]';
    +        if (valueToCheck.match(new RegExp(`${wildcards}`))) {
    +          logger.debug(
    +            `The '$capture' parameter contains an Express-style wildcard ` +
    +            `character (${wildcards}). Strings are now always interpreted as ` +
    +            `exact matches; use a RegExp for partial or wildcard matches.`
    +          );
    +        }
    +      }
    +
    +      const matchCallback = ({url}) => {
    +        if (process.env.NODE_ENV !== 'production') {
    +          if ((url.pathname === captureUrl.pathname) &amp;&amp;
    +              (url.origin !== captureUrl.origin)) {
    +            logger.debug(
    +              `${capture} only partially matches the cross-origin URL ` +
    +              `${url}. This route will only handle cross-origin requests ` +
    +              `if they match the entire URL.`
    +            );
    +          }
    +        }
    +
    +        return url.href === captureUrl.href;
    +      };
    +
    +      route = new Route(matchCallback, handler, method);
    +    } else if (capture instanceof RegExp) {
    +      route = new RegExpRoute(capture, handler, method);
    +    } else if (typeof capture === 'function') {
    +      route = new Route(capture, handler, method);
    +    } else if (capture instanceof Route) {
    +      route = capture;
    +    } else {
    +      throw new WorkboxError('unsupported-route-type', {
    +        moduleName: 'workbox-routing',
    +        className: 'DefaultRouter',
    +        funcName: 'registerRoute',
    +        paramName: 'capture',
    +      });
    +    }
    +
    +    super.registerRoute(route);
    +    return route;
    +  }
    +
    +  /**
    +   * Register a route that will return a precached file for a navigation
    +   * request. This is useful for the
    +   * [application shell pattern]{@link /web/fundamentals/architecture/app-shell}.
    +   *
    +   * This method will generate a
    +   * [NavigationRoute]{@link workbox.routing.NavigationRoute}
    +   * and call
    +   * [Router.registerRoute()]{@link workbox.routing.Router#registerRoute}
    +   * .
    +   *
    +   * @param {string} cachedAssetUrl
    +   * @param {Object} [options]
    +   * @param {string} [options.cacheName] Cache name to store and retrieve
    +   * requests. Defaults to precache cache name provided by
    +   * [workbox-core.cacheNames]{@link workbox.core.cacheNames}.
    +   * @param {Array&lt;RegExp>} [options.blacklist=[]] If any of these patterns
    +   * match, the route will not handle the request (even if a whitelist entry
    +   * matches).
    +   * @param {Array&lt;RegExp>} [options.whitelist=[/./]] If any of these patterns
    +   * match the URL's pathname and search parameter, the route will handle the
    +   * request (assuming the blacklist doesn't match).
    +   * @return {workbox.routing.NavigationRoute} Returns the generated
    +   * Route.
    +   *
    +   * @alias workbox.routing.registerNavigationRoute
    +   */
    +  registerNavigationRoute(cachedAssetUrl, options = {}) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isType(cachedAssetUrl, 'string', {
    +        moduleName: 'workbox-routing',
    +        className: '[default export]',
    +        funcName: 'registerNavigationRoute',
    +        paramName: 'cachedAssetUrl',
    +      });
    +    }
    +
    +    const cacheName = cacheNames.getPrecacheName(options.cacheName);
    +    const handler = () => caches.match(cachedAssetUrl, {cacheName});
    +    const route = new NavigationRoute(handler, {
    +      whitelist: options.whitelist,
    +      blacklist: options.blacklist,
    +    });
    +    super.registerRoute(
    +      route
    +    );
    +    return route;
    +  }
    +}
    +
    +const router = new DefaultRouter();
    +
    +// By default, register a fetch event listener that will respond to a request
    +// only if there's a matching route.
    +self.addEventListener('fetch', (event) => {
    +  const responsePromise = router.handleRequest(event);
    +  if (responsePromise) {
    +    event.respondWith(responsePromise);
    +  }
    +});
    +
    +export default router;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing__types.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing__types.mjs.html new file mode 100644 index 00000000000..ec9c3047b05 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing__types.mjs.html @@ -0,0 +1,93 @@ + + + + + + + + Source: workbox-routing/_types.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2016 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    + */
    +
    +import './_version.mjs';
    +
    +/**
    + * The "match" callback is used to determine if a `Route` should handle a
    + * service worker's `fetch` event. Returning a truthy value means
    + * this `Route` will handle and respond to the event.
    + *
    + * Return `null` if this Route shouldn't match against the `fetch` event.
    + *
    + * Any truthy value returned by this callback will be passed to the
    + * Route's
    + * [handler callback]{@link workbox.routing.Route~handlerCallback}.
    + *
    + * @callback Route~matchCallback
    + * @param {Object} context
    + * @param {URL} context.url The request's URL.
    + * @param {FetchEvent} context.event The service worker`s `fetch`
    + * event.
    + * @return {Object|null} To signify a match, return anything other than `null`.
    + * Return `null` if the route shouldn't match.
    + * [handler]{@link workbox.routing.Route~handlerCallback}.
    + *
    + * @memberof workbox.routing
    + */
    +
    +/**
    + * The "handler" callback is called when a service worker's `fetch` event
    + * has been matched by a `Route`. This callback should return a Promise that
    + * resolves with a `Response`.
    + *
    + * If a value is returned by the
    + * [match callback]{@link workbox.routing.Route~matchCallback} it
    + * will be passed in as the `context.params` argument.
    + *
    + * @callback Route~handlerCallback
    + * @param {Object} context
    + * @param {URL} context.url The request's URL.
    + * @param {FetchEvent} context.event The service worker's `fetch`
    + * event.
    + * @param {Object} [context.params] Parameters returned by the Route's
    + * [match callback]{@link workbox.routing.Route~matchCallback} function.
    + * This will be undefined if nothing was returned.
    + * @return {Promise&lt;Response>} The response that will fulfill the request.
    + *
    + * @memberof workbox.routing
    + */
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_index.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_index.mjs.html new file mode 100644 index 00000000000..a24ff869ea8 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-routing_index.mjs.html @@ -0,0 +1,60 @@ + + + + + + + + Source: workbox-routing/index.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import defaultExport from './_default.mjs';
    +import './_version.mjs';
    +
    +/**
    + * @namespace workbox.routing
    + * @borrows workbox.routing.Router#setCatchHandler as setCatchHandler
    + * @borrows workbox.routing.Router#setDefaultHandler as setDefaultHandler
    + * @borrows workbox.routing.Router#unregisterRoute as unregisterRoute
    + */
    +
    +export * from './_public.mjs';
    +export default defaultExport;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_CacheFirst.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_CacheFirst.mjs.html new file mode 100644 index 00000000000..e53d53ffcd6 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_CacheFirst.mjs.html @@ -0,0 +1,187 @@ + + + + + + + + Source: workbox-strategies/CacheFirst.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2016 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
    +import {cacheWrapper} from 'workbox-core/_private/cacheWrapper.mjs';
    +import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.mjs';
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +
    +import messages from './utils/messages.mjs';
    +import './_version.mjs';
    +
    +/**
    + * An implementation of a [cache-first]{@link /web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network}
    + * request strategy.
    + *
    + * A cache first strategy is useful for assets that have beeng revisioned,
    + * such as URLs like `/styles/example.a8f5f1.css`, since they
    + * can be cached for long periods of time.
    + *
    + * @memberof workbox.strategies
    + */
    +class CacheFirst {
    +  // TODO: Replace `plugins` parameter link with link to d.g.c.
    +
    +  /**
    +   * @param {Object} options
    +   * @param {string} options.cacheName Cache name to store and retrieve
    +   * requests. Defaults to cache names provided by
    +   * [workbox-core]{@link workbox.core.cacheNames}.
    +   * @param {string} options.plugins [Plugins]{@link https://docs.google.com/document/d/1Qye_GDVNF1lzGmhBaUvbgwfBWRQDdPgwUAgsbs8jhsk/edit?usp=sharing}
    +   * to use in conjunction with this caching strategy.
    +   */
    +  constructor(options = {}) {
    +    this._cacheName = cacheNames.getRuntimeName(options.cacheName);
    +    this._plugins = options.plugins || [];
    +  }
    +
    +  /**
    +   * This method will perform a request strategy and follows an API that
    +   * will work with the
    +   * [Workbox Router]{@link workbox.routing.Router}.
    +   *
    +   * @param {Object} input
    +   * @param {FetchEvent} input.event The fetch event to run this strategy
    +   * against.
    +   * @return {Promise&lt;Response>}
    +   */
    +  async handle({event}) {
    +    const logs = [];
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isInstance(event, FetchEvent, {
    +        moduleName: 'workbox-strategies',
    +        className: 'CacheFirst',
    +        funcName: 'handle',
    +        paramName: 'event',
    +      });
    +    }
    +
    +    let response = await cacheWrapper.match(
    +      this._cacheName,
    +      event.request,
    +      null,
    +      this._plugins
    +    );
    +
    +    let error;
    +    if (!response) {
    +      if (process.env.NODE_ENV !== 'production') {
    +        logs.push(
    +          `No response found in the '${this._cacheName}' cache. ` +
    +          `Will respond with a network request.`);
    +      }
    +      try {
    +        response = await this._getFromNetwork(event);
    +      } catch (err) {
    +        error = err;
    +      }
    +
    +      if (process.env.NODE_ENV !== 'production') {
    +        if (response) {
    +          logs.push(`Got response from network.`);
    +        } else {
    +          logs.push(`Unable to get a response from the network.`);
    +        }
    +      }
    +    } else {
    +      if (process.env.NODE_ENV !== 'production') {
    +        logs.push(
    +          `Found a cached response in the '${this._cacheName}' cache.`);
    +      }
    +    }
    +
    +    if (process.env.NODE_ENV !== 'production') {
    +      logger.groupCollapsed(
    +        messages.strategyStart('CacheFirst', event));
    +      for (let log of logs) {
    +        logger.log(log);
    +      }
    +      messages.printFinalResponse(response);
    +      logger.groupEnd();
    +    }
    +
    +    if (error) {
    +      // Don't swallow error as we'll want it to throw and enable catch
    +      // handlers in router.
    +      throw error;
    +    }
    +
    +    return response;
    +  }
    +
    +  /**
    +   * Handles the network and cache part of CacheFirst.
    +   *
    +   * @param {FetchEvent} event
    +   * @return {Promise&lt;Response>}
    +   *
    +   * @private
    +   */
    +  async _getFromNetwork(event) {
    +    const response = await fetchWrapper.fetch(
    +      event.request,
    +      null,
    +      this._plugins
    +    );
    +
    +    // Keep the service worker while we put the request to the cache
    +    const responseClone = response.clone();
    +    event.waitUntil(
    +      cacheWrapper.put(
    +        this._cacheName,
    +        event.request,
    +        responseClone,
    +        this._plugins
    +      )
    +    );
    +
    +    return response;
    +  }
    +}
    +
    +export {CacheFirst};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_CacheOnly.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_CacheOnly.mjs.html new file mode 100644 index 00000000000..f4932b1c65c --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_CacheOnly.mjs.html @@ -0,0 +1,127 @@ + + + + + + + + Source: workbox-strategies/CacheOnly.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2016 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
    +import {cacheWrapper} from 'workbox-core/_private/cacheWrapper.mjs';
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +
    +import messages from './utils/messages.mjs';
    +import './_version.mjs';
    +
    +// TODO: Replace `Workbox plugins` link in the class description with a
    +// link to d.g.c.
    +// TODO: Replace `plugins` parameter link with link to d.g.c.
    +
    +/**
    + * An implementation of a
    + * [cache-only]{@link /web/fundamentals/instant-and-offline/offline-cookbook/#cache-only}
    + * request strategy.
    + *
    + * This class is useful if you want to take advantage of any [Workbox plugins]{@link https://docs.google.com/document/d/1Qye_GDVNF1lzGmhBaUvbgwfBWRQDdPgwUAgsbs8jhsk/edit?usp=sharing}.
    + *
    + * @memberof workbox.strategies
    + */
    +class CacheOnly {
    +  /**
    +   * @param {Object} options
    +   * @param {string} options.cacheName Cache name to store and retrieve
    +   * requests. Defaults to cache names provided by
    +   * [workbox-core]{@link workbox.core.cacheNames}.
    +   * @param {string} options.plugins [Plugins]{@link https://docs.google.com/document/d/1Qye_GDVNF1lzGmhBaUvbgwfBWRQDdPgwUAgsbs8jhsk/edit?usp=sharing}
    +   * to use in conjunction with this caching strategy.
    +   */
    +  constructor(options = {}) {
    +    this._cacheName = cacheNames.getRuntimeName(options.cacheName);
    +    this._plugins = options.plugins || [];
    +  }
    +
    +  /**
    +   * This method will perform a request strategy and follows an API that
    +   * will work with the
    +   * [Workbox Router]{@link workbox.routing.Router}.
    +   *
    +   * @param {Object} input
    +   * @param {FetchEvent} input.event The fetch event to run this strategy
    +   * against.
    +   * @return {Promise&lt;Response>}
    +   */
    +  async handle({event}) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isInstance(event, FetchEvent, {
    +        moduleName: 'workbox-strategies',
    +        className: 'CacheOnly',
    +        funcName: 'handle',
    +        paramName: 'event',
    +      });
    +    }
    +
    +    const response = await cacheWrapper.match(
    +      this._cacheName,
    +      event.request,
    +      null,
    +      this._plugins
    +    );
    +
    +    if (process.env.NODE_ENV !== 'production') {
    +      logger.groupCollapsed(
    +        messages.strategyStart('CacheOnly', event));
    +      if (response) {
    +        logger.log(`Found a cached response in the '${this._cacheName}'` +
    +          ` cache.`);
    +        messages.printFinalResponse(response);
    +      } else {
    +        logger.log(`No response found in the '${this._cacheName}' cache.`);
    +      }
    +      logger.groupEnd();
    +    }
    +
    +    return response;
    +  }
    +}
    +
    +export {CacheOnly};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_NetworkFirst.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_NetworkFirst.mjs.html new file mode 100644 index 00000000000..dec2720a93d --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_NetworkFirst.mjs.html @@ -0,0 +1,270 @@ + + + + + + + + Source: workbox-strategies/NetworkFirst.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2016 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
    +import {cacheWrapper} from 'workbox-core/_private/cacheWrapper.mjs';
    +import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.mjs';
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +
    +import messages from './utils/messages.mjs';
    +import cacheOkAndOpaquePlugin from './plugins/cacheOkAndOpaquePlugin.mjs';
    +import './_version.mjs';
    +
    +// TODO: Change opaque responses to d.g.c link
    +// TODO: Replace `plugins` parameter link with link to d.g.c.
    +
    +/**
    + * An implementation of a
    + * [network first]{@link /web/fundamentals/instant-and-offline/offline-cookbook/#network-falling-back-to-cache}
    + * request strategy.
    + *
    + * By default, this strategy will cache responses with a 200 status code as
    + * well as [opaque responses]{@link https://docs.google.com/document/d/1nHIjXdmXs9nT6_lcGcsZY5UZ-tL9JxXESlKbzAJdBG4/edit?usp=sharing}.
    + * Opaque responses are are cross-origin requests where the response doesn't
    + * support [CORS]{@link https://enable-cors.org/}.
    + *
    + * @memberof workbox.strategies
    + */
    +class NetworkFirst {
    +  /**
    +   * @param {Object} options
    +   * @param {string} options.cacheName Cache name to store and retrieve
    +   * requests. Defaults to cache names provided by
    +   * [workbox-core]{@link workbox.core.cacheNames}.
    +   * @param {string} options.plugins [Plugins]{@link https://docs.google.com/document/d/1Qye_GDVNF1lzGmhBaUvbgwfBWRQDdPgwUAgsbs8jhsk/edit?usp=sharing}
    +   * to use in conjunction with this caching strategy.
    +   * @param {number} options.networkTimeoutSeconds If set, any network requests
    +   * that fail to respond within the timeout will fallback to the cache.
    +   *
    +   * This option can be used to combat
    +   * "[lie-fi]{@link /web/fundamentals/performance/poor-connectivity/#lie-fi}"
    +   * scenarios.
    +   */
    +  constructor(options = {}) {
    +    this._cacheName = cacheNames.getRuntimeName(options.cacheName);
    +
    +    if (options.plugins) {
    +      let isUsingCacheWillUpdate =
    +        options.plugins.some((plugin) => !!plugin.cacheWillUpdate);
    +      this._plugins = isUsingCacheWillUpdate ?
    +        options.plugins : [cacheOkAndOpaquePlugin, ...options.plugins];
    +    } else {
    +      // No plugins passed in, use the default plugin.
    +      this._plugins = [cacheOkAndOpaquePlugin];
    +    }
    +
    +    this._networkTimeoutSeconds = options.networkTimeoutSeconds;
    +    if (process.env.NODE_ENV !== 'production') {
    +      if (this._networkTimeoutSeconds) {
    +        assert.isType(this._networkTimeoutSeconds, 'number', {
    +          moduleName: 'workbox-strategies',
    +          className: 'NetworkFirst',
    +          funcName: 'constructor',
    +          paramName: 'networkTimeoutSeconds',
    +        });
    +      }
    +    }
    +  }
    +
    +  /**
    +   * This method will perform a request strategy and follows an API that
    +   * will work with the
    +   * [Workbox Router]{@link workbox.routing.Router}.
    +   *
    +   * @param {Object} input
    +   * @param {FetchEvent} input.event The fetch event to run this strategy
    +   * against.
    +   * @return {Promise&lt;Response>}
    +   */
    +  async handle({event}) {
    +    const logs = [];
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isInstance(event, FetchEvent, {
    +        moduleName: 'workbox-strategies',
    +        className: 'NetworkFirst',
    +        funcName: 'handle',
    +        paramName: 'event',
    +      });
    +    }
    +
    +    const promises = [];
    +    let timeoutId;
    +
    +    if (this._networkTimeoutSeconds) {
    +      const {id, promise} = this._getTimeoutPromise(event, logs);
    +      timeoutId = id;
    +      promises.push(promise);
    +    }
    +
    +    const networkPromise = this._getNetworkPromise(timeoutId, event, logs);
    +    promises.push(networkPromise);
    +
    +    const response = await Promise.race(promises);
    +
    +    if (process.env.NODE_ENV !== 'production') {
    +      logger.groupCollapsed(
    +        messages.strategyStart('NetworkFirst', event));
    +      for (let log of logs) {
    +        logger.log(log);
    +      }
    +      messages.printFinalResponse(response);
    +      logger.groupEnd();
    +    }
    +
    +    return response;
    +  }
    +
    +  /**
    +   * @param {FetchEvent} event
    +   * @param {Array} logs A reference to the logs array
    +   * @return {Promise&lt;Response>}
    +   *
    +   * @private
    +   */
    +  _getTimeoutPromise(event, logs) {
    +    let timeoutId;
    +    const timeoutPromise = new Promise((resolve) => {
    +      const onNetworkTimeout = async () => {
    +        if (process.env.NODE_ENV !== 'production') {
    +          logs.push(`Timing out the network response at ` +
    +            `${this._networkTimeoutSeconds} seconds.`);
    +        }
    +
    +        resolve(await this._respondFromCache(event.request));
    +      };
    +
    +      timeoutId = setTimeout(
    +        onNetworkTimeout,
    +        this._networkTimeoutSeconds * 1000,
    +      );
    +    });
    +
    +    return {
    +      promise: timeoutPromise,
    +      id: timeoutId,
    +    };
    +  }
    +
    +  /**
    +   * @param {number} timeoutId
    +   * @param {FetchEvent} event
    +   * @param {Array} logs A reference to the logs Array.
    +   * @return {Promise&lt;Response>}
    +   *
    +   * @private
    +   */
    +  async _getNetworkPromise(timeoutId, event, logs) {
    +    let error;
    +    let response;
    +    try {
    +      response = await fetchWrapper.fetch(
    +        event.request,
    +        this._plugins
    +      );
    +    } catch (err) {
    +      error = err;
    +    }
    +
    +    if (timeoutId) {
    +      clearTimeout(timeoutId);
    +    }
    +
    +    if (process.env.NODE_ENV !== 'production') {
    +      if (response) {
    +        logs.push(`Got response from network.`);
    +      } else {
    +        logs.push(`Unable to get a response from the network. Will respond ` +
    +          `with a cached response.`);
    +      }
    +    }
    +
    +    if (error || !response) {
    +      response = await this._respondFromCache(event.request);
    +      if (process.env.NODE_ENV !== 'production') {
    +        if (response) {
    +          logs.push(`Found a cached response in the '${this._cacheName}'` +
    +            ` cache.`);
    +        } else {
    +          logs.push(`No response found in the '${this._cacheName}' cache.`);
    +        }
    +      }
    +    } else {
    +       // Keep the service worker alive while we put the request in the cache
    +      const responseClone = response.clone();
    +      event.waitUntil(
    +        cacheWrapper.put(
    +          this._cacheName,
    +          event.request,
    +          responseClone,
    +          this._plugins
    +        )
    +      );
    +    }
    +
    +    return response;
    +  }
    +
    +  /**
    +   * Used if the network timeouts or fails to make the request.
    +   *
    +   * @param {Request} request The fetchEvent request to match in the cache
    +   * @return {Promise&lt;Object>}
    +   *
    +   * @private
    +   */
    +  _respondFromCache(request) {
    +    return cacheWrapper.match(
    +      this._cacheName,
    +      request,
    +      null,
    +      this._plugins
    +    );
    +  }
    +}
    +
    +export {NetworkFirst};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_NetworkOnly.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_NetworkOnly.mjs.html new file mode 100644 index 00000000000..acc6958b93f --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_NetworkOnly.mjs.html @@ -0,0 +1,136 @@ + + + + + + + + Source: workbox-strategies/NetworkOnly.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2016 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
    +import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.mjs';
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +import messages from './utils/messages.mjs';
    +import './_version.mjs';
    +
    +// TODO: Replace `Workbox plugins` link in the class description with a
    +// link to d.g.c.
    +// TODO: Replace `plugins` parameter link with link to d.g.c.
    +
    +/**
    + * An implementation of a
    + * [network-only]{@link /web/fundamentals/instant-and-offline/offline-cookbook/#network-only}
    + * request strategy.
    + *
    + * This class is useful if you want to take advantage of any [Workbox plugins]{@link https://docs.google.com/document/d/1Qye_GDVNF1lzGmhBaUvbgwfBWRQDdPgwUAgsbs8jhsk/edit?usp=sharing}.
    + *
    + * @memberof workbox.strategies
    + */
    +class NetworkOnly {
    +  /**
    +   * @param {Object} options
    +   * @param {string} options.cacheName Cache name to store and retrieve
    +   * requests. Defaults to cache names provided by
    +   * [workbox-core]{@link workbox.core.cacheNames}.
    +   * @param {string} options.plugins [Plugins]{@link https://docs.google.com/document/d/1Qye_GDVNF1lzGmhBaUvbgwfBWRQDdPgwUAgsbs8jhsk/edit?usp=sharing}
    +   * to use in conjunction with this caching strategy.
    +   */
    +  constructor(options = {}) {
    +    this._cacheName = cacheNames.getRuntimeName(options.cacheName);
    +    this._plugins = options.plugins || [];
    +  }
    +
    +  /**
    +   * This method will perform a request strategy and follows an API that
    +   * will work with the
    +   * [Workbox Router]{@link workbox.routing.Router}.
    +   *
    +   * @param {Object} input
    +   * @param {FetchEvent} input.event The fetch event to run this strategy
    +   * against.
    +   * @return {Promise&lt;Response>}
    +   */
    +  async handle({event}) {
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isInstance(event, FetchEvent, {
    +        moduleName: 'workbox-strategies',
    +        className: 'NetworkOnly',
    +        funcName: 'handle',
    +        paramName: 'event',
    +      });
    +    }
    +
    +    let error;
    +    let response;
    +    try {
    +      response = await fetchWrapper.fetch(
    +        event.request,
    +        null,
    +        this._plugins
    +      );
    +    } catch (err) {
    +      error = err;
    +    }
    +
    +    if (process.env.NODE_ENV !== 'production') {
    +      logger.groupCollapsed(
    +        messages.strategyStart('NetworkOnly', event));
    +      if (response) {
    +        logger.log(`Got response from network.`);
    +      } else {
    +        logger.log(`Unable to get a response from the network.`);
    +      }
    +      messages.printFinalResponse(response);
    +      logger.groupEnd();
    +    }
    +
    +    // If there was an error thrown, re-throw it to ensure the Routers
    +    // catch handler is triggered.
    +    if (error) {
    +      throw error;
    +    }
    +
    +    return response;
    +  }
    +}
    +
    +export {NetworkOnly};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_StaleWhileRevalidate.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_StaleWhileRevalidate.mjs.html new file mode 100644 index 00000000000..41b01b8f83c --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_StaleWhileRevalidate.mjs.html @@ -0,0 +1,186 @@ + + + + + + + + Source: workbox-strategies/StaleWhileRevalidate.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2016 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
    +import {cacheWrapper} from 'workbox-core/_private/cacheWrapper.mjs';
    +import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.mjs';
    +import {logger} from 'workbox-core/_private/logger.mjs';
    +import {assert} from 'workbox-core/_private/assert.mjs';
    +
    +import messages from './utils/messages.mjs';
    +import cacheOkAndOpaquePlugin from './plugins/cacheOkAndOpaquePlugin.mjs';
    +import './_version.mjs';
    +
    +// TODO: Replace `Workbox plugins` link in the class description with a
    +// link to d.g.c.
    +// TODO: Replace `plugins` parameter link with link to d.g.c.
    +
    +/**
    + * An implementation of a
    + * [stale-while-revalidate]{@link /web/fundamentals/instant-and-offline/offline-cookbook/#stale-while-revalidate}
    + * request strategy.
    + *
    + * Resources are requested from both the cache and the network in parallel.
    + * The strategy will respond with the cached version if available, otherwise
    + * wait for the network response. The cache is updated with the network response
    + * with each successful request.
    + *
    + * By default, this strategy will cache responses with a 200 status code as
    + * well as [opaque responses]{@link https://docs.google.com/document/d/1nHIjXdmXs9nT6_lcGcsZY5UZ-tL9JxXESlKbzAJdBG4/edit?usp=sharing}.
    + * Opaque responses are are cross-origin requests where the response doesn't
    + * support [CORS]{@link https://enable-cors.org/}.
    + *
    + * @memberof workbox.strategies
    + */
    +class StaleWhileRevalidate {
    +  /**
    +   * @param {Object} options
    +   * @param {string} options.cacheName Cache name to store and retrieve
    +   * requests. Defaults to cache names provided by
    +   * [workbox-core]{@link workbox.core.cacheNames}.
    +   * @param {string} options.plugins [Plugins]{@link https://docs.google.com/document/d/1Qye_GDVNF1lzGmhBaUvbgwfBWRQDdPgwUAgsbs8jhsk/edit?usp=sharing}
    +   * to use in conjunction with this caching strategy.
    +   */
    +  constructor(options = {}) {
    +    this._cacheName = cacheNames.getRuntimeName(options.cacheName);
    +      this._plugins = options.plugins || [];
    +
    +    if (options.plugins) {
    +      let isUsingCacheWillUpdate =
    +        options.plugins.some((plugin) => !!plugin.cacheWillUpdate);
    +      this._plugins = isUsingCacheWillUpdate ?
    +        options.plugins : [cacheOkAndOpaquePlugin, ...options.plugins];
    +    } else {
    +      // No plugins passed in, use the default plugin.
    +      this._plugins = [cacheOkAndOpaquePlugin];
    +    }
    +  }
    +
    +  /**
    +   * This method will perform a request strategy and follows an API that
    +   * will work with the
    +   * [Workbox Router]{@link workbox.routing.Router}.
    +   *
    +   * @param {Object} input
    +   * @param {FetchEvent} input.event The fetch event to run this strategy
    +   * against.
    +   * @return {Promise&lt;Response>}
    +   */
    +  async handle({event}) {
    +    const logs = [];
    +    if (process.env.NODE_ENV !== 'production') {
    +      assert.isInstance(event, FetchEvent, {
    +        moduleName: 'workbox-strategies',
    +        className: 'StaleWhileRevalidate',
    +        funcName: 'handle',
    +        paramName: 'event',
    +      });
    +    }
    +
    +    const fetchAndCachePromise = this._getFromNetwork(event);
    +
    +    let response = await cacheWrapper.match(
    +      this._cacheName,
    +      event.request,
    +      null,
    +      this._plugins
    +    );
    +
    +    if (response) {
    +      if (process.env.NODE_ENV !== 'production') {
    +        logs.push(`Found a cached response in the '${this._cacheName}'` +
    +          ` cache. Will update with the network response in the background.`);
    +      }
    +      event.waitUntil(fetchAndCachePromise);
    +    } else {
    +      if (process.env.NODE_ENV !== 'production') {
    +        logs.push(`No response found in the '${this._cacheName}' cache. ` +
    +          `Will wait for the network response.`);
    +      }
    +      response = await fetchAndCachePromise;
    +    }
    +
    +    if (process.env.NODE_ENV !== 'production') {
    +      logger.groupCollapsed(
    +        messages.strategyStart('StaleWhileRevalidate', event));
    +      for (let log of logs) {
    +        logger.log(log);
    +      }
    +      messages.printFinalResponse(response);
    +      logger.groupEnd();
    +    }
    +
    +    return response;
    +  }
    +
    +  /**
    +   * @param {FetchEvent} event
    +   * @return {Promise&lt;Response>}
    +   *
    +   * @private
    +   */
    +  async _getFromNetwork(event) {
    +    const response = await fetchWrapper.fetch(
    +      event.request,
    +      null,
    +      this._plugins
    +    );
    +
    +    event.waitUntil(
    +      cacheWrapper.put(
    +        this._cacheName,
    +        event.request,
    +        response.clone(),
    +        this._plugins
    +      )
    +    );
    +
    +    return response;
    +  }
    +}
    +
    +export {StaleWhileRevalidate};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies__default.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies__default.mjs.html new file mode 100644 index 00000000000..b8ae01972fc --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies__default.mjs.html @@ -0,0 +1,100 @@ + + + + + + + + Source: workbox-strategies/_default.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    + Copyright 2016 Google Inc. All Rights Reserved.
    + Licensed under the Apache License, Version 2.0 (the "License");
    + you may not use this file except in compliance with the License.
    + You may obtain a copy of the License at
    +
    +     http://www.apache.org/licenses/LICENSE-2.0
    +
    + Unless required by applicable law or agreed to in writing, software
    + distributed under the License is distributed on an "AS IS" BASIS,
    + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + See the License for the specific language governing permissions and
    + limitations under the License.
    +*/
    +
    +import {CacheFirst} from './CacheFirst.mjs';
    +import {CacheOnly} from './CacheOnly.mjs';
    +import {NetworkFirst} from './NetworkFirst.mjs';
    +import {NetworkOnly} from './NetworkOnly.mjs';
    +import {StaleWhileRevalidate} from './StaleWhileRevalidate.mjs';
    +import pluginBuilder from './utils/pluginBuilder.mjs';
    +import './_version.mjs';
    +
    +/**
    + * @function workbox.strategies.cacheFirst
    + * @param {StrategyOptions} options
    + */
    +
    +/**
    + * @function workbox.strategies.cacheOnly
    + * @param {StrategyOptions} options
    + */
    +
    +/**
    + * @function workbox.strategies.networkFirst
    + * @param {StrategyOptions} options
    + */
    +
    +/**
    + * @function workbox.strategies.networkOnly
    + * @param {StrategyOptions} options
    + */
    +
    +/**
    + * @function workbox.strategies.staleWhileRevalidate
    + * @param {StrategyOptions} options
    + */
    +
    +const mapping = {
    +  cacheFirst: CacheFirst,
    +  cacheOnly: CacheOnly,
    +  networkFirst: NetworkFirst,
    +  networkOnly: NetworkOnly,
    +  staleWhileRevalidate: StaleWhileRevalidate,
    +};
    +
    +const defaultExport = {};
    +Object.keys(mapping).forEach((keyName) => {
    +  defaultExport[keyName] = (options = {}) => {
    +    const StrategyClass = mapping[keyName];
    +    const plugins = pluginBuilder(options);
    +    return new StrategyClass(
    +      Object.assign(options, {plugins})
    +    );
    +  };
    +});
    +
    +export default defaultExport;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies__types.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies__types.mjs.html new file mode 100644 index 00000000000..29590ea293a --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies__types.mjs.html @@ -0,0 +1,62 @@ + + + + + + + + Source: workbox-strategies/_types.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import './_version.mjs';
    +
    +/**
    + * @typedef {Object} StrategyOptions
    + * @property {String} cacheName Name of cache to use
    + * for caching (both lookup and updating).
    + * @property {Object} cacheExpiration Defining this
    + * object will add a cache expiration plugins to this strategy.
    + * @property {Number} cacheExpiration.maxEntries
    + * The maximum number of entries to store in a cache.
    + * @property {Number} cacheExpiration.maxAgeSeconds
    + * The maximum lifetime of a request to stay in the cache before it's removed.
    + * @memberof workbox.strategies
    + */
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_index.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_index.mjs.html new file mode 100644 index 00000000000..856afda9e4c --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-strategies_index.mjs.html @@ -0,0 +1,60 @@ + + + + + + + + Source: workbox-strategies/index.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +/**
    + * There are common caching strategies that most service workers will need
    + * and use. This module provides simple implementations of these strategies.
    + *
    + * @namespace workbox.strategies
    + */
    +
    +import defaultExport from './_default.mjs';
    +import './_version.mjs';
    +
    +export default defaultExport;
    +export * from './_public.mjs';
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-sw_controllers_WorkboxSW.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-sw_controllers_WorkboxSW.mjs.html new file mode 100644 index 00000000000..f37b25b04e6 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-sw_controllers_WorkboxSW.mjs.html @@ -0,0 +1,205 @@ + + + + + + + + Source: workbox-sw/controllers/WorkboxSW.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +import '../_version.mjs';
    +
    +const CDN_PATH = `WORKBOX_CDN_ROOT_URL`;
    +
    +// TODO Make this list be generated during build time using the package.json's.
    +// workbox namespace value.
    +const MODULE_KEY_TO_NAME_MAPPING = {
    +  backgroundSync: 'background-sync',
    +  core: 'core',
    +  expiration: 'cache-expiration',
    +  googleAnalytics: 'google-analytics',
    +  strategies: 'strategies',
    +  precaching: 'precaching',
    +  routing: 'routing',
    +};
    +
    +/**
    + * This class can be used to make it easy to use the various parts of
    + * Workbox.
    + *
    + * @private
    + */
    +class WorkboxSW {
    +  /**
    +   * Creates a proxy that automatically loads workbox namespaces on demand.
    +   *
    +   * @private
    +   */
    +  constructor() {
    +    this.v = {};
    +    this._options = {
    +      debug: self.location.hostname === 'localhost',
    +      modulePathPrefix: null,
    +      modulePathCb: null,
    +    };
    +
    +    this._env = this._options.debug ? 'dev' : 'prod';
    +    this._modulesLoaded = false;
    +
    +    return new Proxy(this, {
    +      get(target, key) {
    +        if (target[key]) {
    +          return target[key];
    +        }
    +
    +        const moduleName = MODULE_KEY_TO_NAME_MAPPING[key];
    +        if (moduleName) {
    +          target.loadModule(`workbox-${moduleName}`);
    +        }
    +
    +        return target[key];
    +      },
    +    });
    +  }
    +
    +  /**
    +   * Updates the configuration options. You can specify whether to treat as a
    +   * debug build and whether to use a CDN or a specific path when importing
    +   * other workbox-modules
    +   *
    +   * @param {Object=} [options]
    +   *
    +   * @alias workbox.setConfig
    +   */
    +  setConfig(options = {}) {
    +    if (!this._modulesLoaded) {
    +      Object.assign(this._options, options);
    +      this._env = this._options.debug ? 'dev' : 'prod';
    +    } else {
    +      throw new Error('Config must be set before accessing workbox.* modules');
    +    }
    +  }
    +
    +  /**
    +   * Force a service worker to become active, instead of waiting. This is
    +   * normally used in conjunction with `clientsClaim()`.
    +   *
    +   * @alias workbox.skipWaiting
    +   */
    +  skipWaiting() {
    +    self.addEventListener('install', () => self.skipWaiting());
    +  }
    +
    +  /**
    +   * Claim any currently available clients once the service worker
    +   * becomes active. This is normally used in conjunction with `skipWaiting()`.
    +   *
    +   * @alias workbox.clientsClaim
    +   */
    +  clientsClaim() {
    +    self.addEventListener('activate', () => self.clients.claim());
    +  }
    +
    +  /**
    +   * Load a Workbox module by passing in the appropriate module name.
    +   *
    +   * This is not generally needed unless you know there are modules that are
    +   * dynamically used and you want to safe guard use of the module while the
    +   * user may be offline.
    +   *
    +   * @param {string} moduleName
    +   *
    +   * @alias workbox.loadModule
    +   */
    +  loadModule(moduleName) {
    +    const modulePath = this._getImportPath(moduleName);
    +    try {
    +      importScripts(modulePath);
    +      this._modulesLoaded = true;
    +    } catch (err) {
    +      // TODO Add context of this error if using the CDN vs the local file.
    +
    +      // We can't rely on workbox-core being loaded so using console
    +      // eslint-disable-next-line
    +      console.error(
    +        `Unable to import module '${moduleName}' from '${modulePath}'.`);
    +      throw err;
    +    }
    +  }
    +
    +  /**
    +   * This method will get the path / CDN URL to be used for importScript calls.
    +   *
    +   * @param {string} moduleName
    +   * @return {string} URL to the desired module.
    +   *
    +   * @private
    +   */
    +  _getImportPath(moduleName) {
    +    if (this._options.modulePathCb) {
    +      return this._options.modulePathCb(moduleName, this._options.debug);
    +    }
    +
    +    // TODO: This needs to be dynamic some how.
    +    let pathParts = [CDN_PATH];
    +
    +    const fileName = `${moduleName}.${this._env}.js`;
    +
    +    const pathPrefix = this._options.modulePathPrefix;
    +    if (pathPrefix) {
    +      // Split to avoid issues with developers ending / not ending with slash
    +      pathParts = pathPrefix.split('/');
    +
    +      // We don't need a slash at the end as we will be adding
    +      // a filename regardless
    +      if (pathParts[pathParts.length - 1] === '') {
    +        pathParts.splice(pathParts.length - 1, 1);
    +      }
    +    }
    +
    +    pathParts.push(fileName);
    +
    +    return pathParts.join('/');
    +  }
    +}
    +
    +export default WorkboxSW;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-sw_index.mjs.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-sw_index.mjs.html new file mode 100644 index 00000000000..4d79c0fba43 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-sw_index.mjs.html @@ -0,0 +1,59 @@ + + + + + + + + Source: workbox-sw/index.mjs + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +/**
    + * This module is a single import that can be used to dynamically import
    + * additional Workbox modules with no effort.
    + *
    + * @namespace workbox
    + */
    +
    +import defaultExport from './_default.mjs';
    +import './_version.mjs';
    +
    +export default defaultExport;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-webpack-plugin_src_index.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-webpack-plugin_src_index.js.html new file mode 100644 index 00000000000..983f73cf8f9 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-webpack-plugin_src_index.js.html @@ -0,0 +1,195 @@ + + + + + + + + Source: workbox-webpack-plugin/src/index.js + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +const path = require('path');
    +const getEntries = require('./lib/get-manifest-entries-with-webpack');
    +const generateManifest = require('./lib/generate-manifest-with-webpack');
    +const generateOrCopySW = require('./lib/generate-or-copy-sw');
    +const webpackAsset = require('./lib/utils/webpack-asset');
    +const copyWorkboxSW = require('./lib/utils/copy-workbox-sw');
    +const {setReadFile} = require('./lib/utils/read-file');
    +
    +/**
    + * This module exports the `WorkboxWebpackPlugin`.
    + *
    + * Use an instance of `WorkboxWebpackPlugin` in the
    + * [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
    + * webpack config.
    + *
    + * @module workbox-webpack-plugin
    + */
    +class WorkboxWebpackPlugin {
    +  /**
    +   * Creates an instance of WorkboxWebpackPlugin.
    +   *
    +   * @param {module:workbox-build.Configuration} [config] All the options as
    +   *        passed to {@link module:workbox-build.generateSWString}.
    +   * @param {Array&lt;String>} [config.chunks] Array of chunk names to use for
    +   *        generating the asset manifest. All assets belonging to the provided
    +   *        chunk names will be included in the asset manifest. Any chunks that
    +   *        are not listed or do not have a name will be removed.
    +   * @param {Array&lt;String>} [config.excludeChunks] Array of chunk names to
    +   *        exclude from the asset manifest. Any asset beloning to the provided
    +   *        chunk names will not be included in the asset manifest. This does
    +   *        not affect chunks with no chunk name.
    +   * @param {string} [config.filename = 'sw.js'] Name of the service worker file
    +   * @param {string} [config.manifestFilename = 'file-manifest[hash].js'] Name
    +   *        of the manifest file that will be written to the build directory
    +   * @param {string} [config.swSrc] Path to an existing service worker file.
    +   *        Will be added to the webpack compilation and prepended with
    +   *        importScripts('workbox-sw.js', 'file-manifest.js')
    +   */
    +  constructor(config = {}) {
    +    this.config = config;
    +  }
    +
    +  /**
    +   * @return {Object} All workbox configuration options that can be accepted
    +   * by {@link module:workbox-build.generateSWString}
    +   *
    +   * @private
    +   */
    +  get generateSWStringOptions() {
    +    const {
    +      importScripts = [],
    +      // TODO: decide on other options that should be passed to
    +      // `generateSWString`. What operations should be possible for webpack
    +      // users? eg, should webpack users also be able to specify a
    +      // `globDirectory` that allows manifestEntries to be added that are
    +      // outside webpack's scope?
    +    } = this.config;
    +
    +    return {
    +      importScripts,
    +    };
    +  }
    +
    +  /**
    +   * @param {Object} [compiler] default compiler object passed from webpack
    +   *
    +   * @private
    +   */
    +  apply(compiler) {
    +    /**
    +     * The plugin was instantiated and the webpack compilation has just begun.
    +     * We configure the workbox-webpack-plugin/utils/read-file module to use
    +     * webpack's compilation.inputFileSystem._readFile method for reading files.
    +     *
    +     * TODO: Determine if this is absolutely necessary. It might be possible to
    +     * only do this in development (when the file system is a "memory" file
    +     * system). If that is the case, it might be better to set different values
    +     * for setReadFile using compiler.plugin('run') for production and
    +     * compiler.plugin('watch-run') for development.
    +     */
    +    setReadFile(compiler.inputFileSystem._readFile);
    +
    +    /**
    +     * During the make phase of the webpack compilation, we use
    +     * workbox-webpack-plugin/utils/copy-workbox-sw to add a built version of
    +     * workbox-sw to the webpack compilation assets array.
    +     */
    +    compiler.plugin('make', async (compilation, next) => {
    +      const {
    +        workboxSW,
    +        workboxSWMap,
    +        workboxSWName,
    +      } = await copyWorkboxSW();
    +
    +      // Add the workbox-sw file to compilation assets.
    +      compilation.assets[workboxSWName] = webpackAsset(workboxSW);
    +      compilation.assets[`${workboxSWName}.map`] = webpackAsset(workboxSWMap);
    +      // The version of workbox-sw is included in it's filename so we need
    +      // that information to import it in the generated service worker.
    +      this.workboxSWFilename = workboxSWName;
    +      next();
    +    });
    +
    +    /**
    +     * During the emit phase of the webpack compilation, we:
    +     *  1. Get the manifest entries.
    +     *  2. Use the entries to generate a file-manifest.
    +     *  3. Generate a service worker with the file-manifest name and workbox-sw
    +     *     name, or copy a service worker from the config.swSrc, then prepend
    +     *     it with the required importScripts(workbox-sw.js, file-manifest.js).
    +     *  4. Add both the file-manifest and the service worker to the webpack
    +     *     assets.
    +     */
    +    compiler.plugin('emit', async (compilation, next) => {
    +      const {
    +        manifestFilename = `file-manifest.${compilation.hash}.js`,
    +        swSrc,
    +        filename = (swSrc &amp;&amp; path.basename(swSrc)) || 'sw.js',
    +      } = this.config;
    +
    +      const entries = getEntries(compiler, compilation, this.config);
    +
    +      const importScripts = (this.config.importScripts || []).concat([
    +        this.workboxSWFilename,
    +        manifestFilename,
    +      ]);
    +
    +      const [fileManifest, serviceWorker] = await Promise.all([
    +        // service worker and fileManifest are not (yet) assets when the
    +        // manifest is generated
    +        generateManifest(entries),
    +        generateOrCopySW(
    +          Object.assign(this.generateSWStringOptions, {
    +            importScripts,
    +          }),
    +          swSrc
    +        ),
    +      ]);
    +
    +      compilation.assets[manifestFilename] = webpackAsset(fileManifest);
    +      compilation.assets[filename] = webpackAsset(serviceWorker);
    +      next();
    +    });
    +  }
    +}
    +
    +module.exports = WorkboxWebpackPlugin;
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-webpack-plugin_src_lib_utils_read-file.js.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-webpack-plugin_src_lib_utils_read-file.js.html new file mode 100644 index 00000000000..14ed6950c26 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox-webpack-plugin_src_lib_utils_read-file.js.html @@ -0,0 +1,90 @@ + + + + + + + + Source: workbox-webpack-plugin/src/lib/utils/read-file.js + + + + +
    +
    +
    + +
    + +
    +
    /*
    +  Copyright 2017 Google Inc.
    +
    +  Licensed under the Apache License, Version 2.0 (the "License");
    +  you may not use this file except in compliance with the License.
    +  You may obtain a copy of the License at
    +
    +      https://www.apache.org/licenses/LICENSE-2.0
    +
    +  Unless required by applicable law or agreed to in writing, software
    +  distributed under the License is distributed on an "AS IS" BASIS,
    +  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +  See the License for the specific language governing permissions and
    +  limitations under the License.
    +*/
    +
    +/**
    + * Use the `compiler.inputFileSystem._readFile` method instead of `fs.readFile`,
    + * `readFile` is configured to use `compiler.inputFileSystem._readFile` during
    + * the run phase of the webpack compilation lifecycle by passing the function
    + * to the `setReadFile` function.
    + */
    +let readFileFn;
    +
    +/**
    + * Sets the read file function.
    + *
    + * @param {Function} fn The function to use.
    + *
    + * @private
    + */
    +function setReadFile(fn) {
    +  readFileFn = fn;
    +}
    +
    +/**
    + * A wrapper that calls readFileFn and returns a promise for the contents.
    + *
    + * @param {string} filePath The file to read.
    + * @return {Promise&lt;string>} The contents of the file.
    + *
    + * @private
    + */
    +function readFile(filePath) {
    +  return new Promise((resolve, reject) => {
    +    readFileFn(filePath, 'utf8', (error, data) => {
    +      if (error) {
    +        return reject(error);
    +      }
    +      resolve(data);
    +    });
    +  });
    +}
    +
    +module.exports = {
    +  readFile,
    +  setReadFile,
    +};
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync.Queue.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync.Queue.html new file mode 100644 index 00000000000..bab3dd73e2b --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync.Queue.html @@ -0,0 +1,179 @@ + + + + + + + + Class: Queue + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    Queue

    +

    new Queue(name, options)

    +

    Creates an instance of Queue with the given options

    +
    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    name

    +
    +

    string

    +

    The unique name for this queue. This name must be unique as it's used to register sync events and store requests in IndexedDB specific to this instance. An error will be thrown if a duplicate name is detected.

    +
    +

    options

    +
    +

    Optional

    +

    Object

    +

    Values in options have the following properties:

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    callbacks

    +
    +

    Optional

    +

    Object

    +

    Callbacks to observe the lifecycle of queued requests. Use these to respond to or modify the requests during the replay process.

    +
    +

    callbacks.requestWillEnqueue

    +
    +

    Optional

    +

    function(StorableRequest)

    +

    Invoked immediately before the request is stored to IndexedDB. Use this callback to modify request data at store time.

    +
    +

    callbacks.requestWillReplay

    +
    +

    Optional

    +

    function(StorableRequest)

    +

    Invoked immediately before the request is re-fetched. Use this callback to modify request data at fetch time.

    +
    +

    callbacks.queueDidReplay

    +
    +

    Optional

    +

    function(Array of StorableRequest)

    +

    Invoked after all requests in the queue have successfully replayed.

    +
    +

    maxRetentionTime

    +
    +

    Optional

    +

    number

    +

    The amount of time (in ms) a request may be retried. After this amount of time has passed, the request will be deleted from the queue.

    +
    +
    +
    +
    +
    +
    +
    +
    +

    Property

    +
    +

    name

    +

    +
    +
    Returns
    +
    +

    string 

    +
    +
    +
    +

    Methods

    +
    +

    addRequest

    +
    async
    +

    addRequest(request)

    +

    Stores the passed request into IndexedDB. The database used is + workbox-background-sync and the object store name is the same as the name this instance was created with (to guarantee it's unique).

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    request

    +
    +

    Request

    +

    The request object to store.

    +
    +
    +
    +
    +

    replayRequests

    +
    async
    +

    replayRequests()

    +

    Retrieves all stored requests in IndexedDB and retries them. If the queue contained requests that were successfully replayed, the + queueDidReplay callback is invoked (which implies the queue is now empty). If any of the requests fail, a new sync registration is created to retry again later.

    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync.QueuePlugin.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync.QueuePlugin.html new file mode 100644 index 00000000000..6a0e2d9c814 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync.QueuePlugin.html @@ -0,0 +1,61 @@ + + + + + + + + Class: QueuePlugin + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    QueuePlugin

    +

    new QueuePlugin(queue) +

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    queue

    +
    +

    Queue

    +

    The Queue instance to add failed requests to.

    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync.html new file mode 100644 index 00000000000..bf0f67260b5 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.backgroundSync.html @@ -0,0 +1,38 @@ + + + + + + + + Namespace: backgroundSync + + + + +
    +
    +
    +
    + +
    +

    Classes

    + +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.core.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.core.html new file mode 100644 index 00000000000..b78a1b09bfa --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.core.html @@ -0,0 +1,233 @@ + + + + + + + + Namespace: core + + + + +
    +
    +
    +
    + +
    +

    Properties

    +
    +

    cacheNames

    +
    static
    +

    +

    Get the current cache names used by Workbox.

    +

    cacheNames.precache is used for precached assets, + cacheNames.googleAnalytics is used by workbox-google-analytics to store analytics.js, and cacheNames.runtime is used for everything else.

    +
    +
    Returns
    +
    +

    Object An object with precache and runtime cache names.

    +
    +
    +

    LOG_LEVELS

    +
    static
    +

    +

    The available log levels in Workbox: debug, log, warn, error and silent.

    +
    +

    Properties

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    debug

    +
    +

    int

    +

    Prints all logs from Workbox. Useful for debugging.

    +
    +

    log

    +
    +

    int

    +

    Prints console log, warn, error and groups. Default for debug builds.

    +
    +

    warn

    +
    +

    int

    +

    Prints console warn, error and groups. Default for non-debug builds.

    +
    +

    error

    +
    +

    int

    +

    Print console error and groups.

    +
    +

    silent

    +
    +

    int

    +

    Force no logging from Workbox.

    +
    +
    +
    +
    +

    logLevel

    +
    static
    +

    +

    Get the current log level.

    +
    +
    Returns
    +
    +

    number .

    +
    +
    +
    +

    Methods

    +
    +

    setCacheNameDetails

    +
    static
    +

    setCacheNameDetails(details)

    +

    You can alter the default cache names used by the Workbox modules by changing the cache name details.

    +

    Cache names are generated as <prefix>-<Cache Name>-<suffix>.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    details

    +
    +

    Object

    +

    Values in details have the following properties:

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    prefix

    +
    +

    Object

    +

    The string to add to the beginning of the precache and runtime cache names.

    +
    +

    suffix

    +
    +

    Object

    +

    The string to add to the end of the precache and runtime cache names.

    +
    +

    precache

    +
    +

    Object

    +

    The cache name to use for precache caching. +

    +
    +

    runtime

    +
    +

    Object

    +

    The cache name to use for runtime caching.

    +
    +

    googleAnalytics

    +
    +

    Object

    +

    The cache name to use for + workbox-google-analytics caching.

    +
    +
    +
    +
    +
    +

    setLogLevel

    +
    static
    +

    setLogLevel(newLevel)

    +

    Set the current log level passing in one of the values from LOG_LEVELS. +

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    newLevel

    +
    +

    number

    +

    The new log level to use.

    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.expiration.CacheExpiration.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.expiration.CacheExpiration.html new file mode 100644 index 00000000000..375e5c3731d --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.expiration.CacheExpiration.html @@ -0,0 +1,166 @@ + + + + + + + + Class: CacheExpiration + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    CacheExpiration

    +

    new CacheExpiration(cacheName, config)

    +

    To construct a new CacheExpiration instance you must provide at least one of the config properties.

    +
    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    cacheName

    +
    +

    string

    +

    Name of the cache to apply restrictions to.

    +
    +

    config

    +
    +

    Object

    +

    Values in config have the following properties:

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    maxEntries

    +
    +

    Optional

    +

    number

    +

    The maximum number of entries to cache. Entries used the least will be removed as the maximum is reached.

    +
    +

    maxAgeSeconds

    +
    +

    Optional

    +

    number

    +

    The maximum age of an entry before it's treated as stale and removed.

    +
    +
    +
    +
    +
    +
    +
    +
    +

    Methods

    +
    +

    expireEntries

    +
    async
    +

    expireEntries()

    +

    Expires entries for the given cache and given criteria.

    +
    +
    +

    isURLExpired

    +
    async
    +

    isURLExpired(url) returns boolean

    +

    Can be used to check if a URL has expired or not before it's used.

    +

    This requires a look up from IndexedDB, so can be slow.

    +

    Note: This method will not remove the cached entry, call + expireEntries() to remove indexedDB and Cache entries.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    url

    +
    +

    string

    +
    +
    +
    +
    Returns
    +
    +

    boolean 

    +
    +
    +

    updateTimestamp

    +
    async
    +

    updateTimestamp(url)

    +

    Update the timestamp for the given URL. This ensures the when removing entries based on maximum entries, most recently used is accurate or when expiring, the timestamp is up-to-date.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    url

    +
    +

    string

    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.expiration.CacheExpirationPlugin.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.expiration.CacheExpirationPlugin.html new file mode 100644 index 00000000000..62d4f63e814 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.expiration.CacheExpirationPlugin.html @@ -0,0 +1,94 @@ + + + + + + + + Class: CacheExpirationPlugin + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    CacheExpirationPlugin

    +

    new CacheExpirationPlugin(config) +

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    config

    +
    +

    Object

    +

    Values in config have the following properties:

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    maxEntries

    +
    +

    Optional

    +

    number

    +

    The maximum number of entries to cache. Entries used the least will be removed as the maximum is reached.

    +
    +

    maxAgeSeconds

    +
    +

    Optional

    +

    number

    +

    The maximum age of an entry before it's treated as stale and removed.

    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.expiration.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.expiration.html new file mode 100644 index 00000000000..3e11dfc8052 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.expiration.html @@ -0,0 +1,42 @@ + + + + + + + + Namespace: expiration + + + + +
    +
    +
    +
    + +
    +

    Classes

    + +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.googleAnalytics.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.googleAnalytics.html new file mode 100644 index 00000000000..9958b0d8b00 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.googleAnalytics.html @@ -0,0 +1,99 @@ + + + + + + + + Namespace: googleAnalytics + + + + +
    +
    +
    +
    + +
    +

    Method

    +
    +

    initialize

    +
    static
    +

    initialize(options)

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    Optional

    +

    Object

    +

    Values in options have the following properties:

    + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    cacheName

    +
    +

    Optional

    +

    Object

    +

    The cache name to store and retrieve analytics.js. Defaults to the cache names provided by workbox-core.

    +
    +

    parameterOverrides

    +
    +

    Optional

    +

    Object

    +

    Measurement Protocol parameters, expressed as key/value pairs, to be added to replayed Google Analytics requests. This can + be used to, e.g., set a custom dimension indicating that the request was replayed.

    +
    +

    hitFilter

    +
    +

    Optional

    +

    function()

    +

    A function that allows you to modify the hit parameters prior to replaying the hit. The function is invoked with the original hit's URLSearchParams object as its only argument.

    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.html new file mode 100644 index 00000000000..bf0d2bf4810 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.html @@ -0,0 +1,108 @@ + + + + + + + + Namespace: workbox + + + + +
    +
    +
    +
    + +
    +

    Namespaces

    + +

    Methods

    +
    +

    clientsClaim

    +
    static
    +

    clientsClaim()

    +

    Claim any currently available clients once the service worker becomes active. This is normally used in conjunction with skipWaiting().

    +
    +
    +

    loadModule

    +
    static
    +

    loadModule(moduleName)

    +

    Load a Workbox module by passing in the appropriate module name.

    +

    This is not generally needed unless you know there are modules that are dynamically used and you want to safe guard use of the module while the user may be offline.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    moduleName

    +
    +

    string

    +
    +
    +
    +
    +

    setConfig

    +
    static
    +

    setConfig(options)

    +

    Updates the configuration options. You can specify whether to treat as a debug build and whether to use a CDN or a specific path when importing other workbox-modules

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    Optional

    +

    Object

    +
    +
    +
    +
    +

    skipWaiting

    +
    static
    +

    skipWaiting()

    +

    Force a service worker to become active, instead of waiting. This is normally used in conjunction with clientsClaim().

    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.precaching.PrecacheController.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.precaching.PrecacheController.html new file mode 100644 index 00000000000..ab51910f5b0 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.precaching.PrecacheController.html @@ -0,0 +1,158 @@ + + + + + + + + Class: PrecacheController + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    PrecacheController

    +

    new PrecacheController(cacheName) +

    +

    Create a new PrecacheController.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    cacheName

    +
    +

    string

    +
    +
    +
    +
    +
    +
    +
    +

    Methods

    +
    +

    addToCacheList

    +

    addToCacheList(entries)

    +

    This method will add items to the precache list, removing duplicates and ensuring the information is valid.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    entries

    +
    +

    Array of (module:workbox-precaching.PrecacheController.PrecacheEntry or string)

    +

    Array of entries to precache. +

    +
    +
    +
    +
    +

    cleanup

    +
    async
    +

    cleanup() returns Promise containing module:workbox-precaching.PrecacheController.CleanupResult

    +

    Compare the URLs and determines which assets are no longer required in the cache.

    +

    This should be called in the service worker activate event.

    +
    +
    Returns
    +
    +

    Promise containing module:workbox-precaching.PrecacheController.CleanupResult Resolves with an object containing details of the deleted cache requests and precache revision details.

    +
    +
    +

    getCachedUrls

    +

    getCachedUrls() returns Array of string

    +

    Returns an array of fully qualified URL's that will be precached.

    +
    +
    Returns
    +
    +

    Array of string An array of URLs.

    +
    +
    +

    install

    +
    async
    +

    install(options) returns Promise containing module:workbox-precaching.PrecacheController.InstallResult

    +

    Call this method from a service work install event to start precaching assets.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    Object

    +

    Values in options have the following properties:

    + + + + + + + + + + +
    +

    Parameter

    +
    +

    suppressWarnings

    +
    +

    boolean

    +

    Suppress warning messages.

    +
    +
    +
    +
    +
    Returns
    +
    +

    Promise containing module:workbox-precaching.PrecacheController.InstallResult 

    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.precaching.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.precaching.html new file mode 100644 index 00000000000..32889981d0d --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.precaching.html @@ -0,0 +1,300 @@ + + + + + + + + Namespace: precaching + + + + +
    +
    +
    +
    + +
    +

    Class

    + +

    Methods

    +
    +

    addRoute

    +
    static
    +

    addRoute(options)

    +

    Add a fetch listener to the service worker that will respond to + network requests with precached assets.

    +

    Requests for assets that aren't precached, the FetchEvent will not be responded to, allowing the event to fall through to other fetch event listeners. +

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    Object

    +

    Values in options have the following properties:

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    directoryIndex

    +
    +

    Optional

    +

    string

    +

    The directoryIndex will check cache entries for a URLs ending with '/' to see if there is a hit when appending the directoryIndex value.

    +
    +

    ignoreUrlParametersMatching

    +
    +

    Optional

    +

    Array of RegExp

    +

    An array of regex's to remove search params when looking for a cache match.

    +
    +
    +
    +
    +
    +

    precache

    +
    static
    +

    precache(entries)

    +

    Add items to the precache list, removing any duplicates and store the files in the "precache cache" when the service worker installs.

    +

    This method can be called multiple times.

    +

    Please note: This method will not serve any of the cached files for you, it only precaches files. To respond to a network request you call addRoute(). +

    +

    If you have a single array of files to precache, you can just call precacheAndRoute(). +

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    entries

    +
    +

    Array of (Object or string)

    +

    Array of entries to precache.

    +
    +
    +
    +
    +

    precacheAndRoute

    +
    static
    +

    precacheAndRoute(entries, options)

    +

    This method will add entries to the precache list and add a route to respond to fetch events.

    +

    This is a convenience method that will call precache() and addRoute() in a single call.

    +
    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    entries

    +
    +

    Array of (Object or string)

    +

    Array of entries to precache.

    +
    +

    options

    +
    +

    Object

    +

    See addRoute() options.

    +
    +
    +
    +
    +

    suppressWarnings

    +
    static
    +

    suppressWarnings(suppress)

    +

    Warnings will be logged if any of the precached assets are entered without a revision property. This is extremely dangerous if the URL's aren't revisioned. However, the warnings can be supressed with this method.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    suppress

    +
    +

    boolean

    +
    +
    +
    +
    +
    +

    Abstract types

    +
    +

    CleanupResult

    +
    static
    +

    Object

    +
    +

    Properties

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    deletedCacheRequests

    +
    +

    Array of string

    +

    List of URLs that were deleted from the precache cache.

    +
    +

    deletedRevisionDetails

    +
    +

    Array of string

    +

    List of URLs that were deleted from the precache cache.

    +
    +
    +
    +
    +

    InstallResult

    +
    static
    +

    Object

    +
    +

    Properties

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    updatedEntries

    +
    +

    Array of (module:workbox-precaching.PrecacheController.PrecacheEntry or string)

    +

    List of entries supplied for precaching that were precached.

    +
    +

    notUpdatedEntries

    +
    +

    Array of (module:workbox-precaching.PrecacheController.PrecacheEntry or string)

    +

    List of entries supplied for precaching that were already precached.

    +
    +
    +
    +
    +

    PrecacheEntry

    +
    static
    +

    Object

    +
    +

    Properties

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    url

    +
    +

    string

    +

    URL to precache.

    +
    +

    revision

    +
    +

    string

    +

    Revision information for the URL.

    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.NavigationRoute.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.NavigationRoute.html new file mode 100644 index 00000000000..72da334c113 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.NavigationRoute.html @@ -0,0 +1,107 @@ + + + + + + + + Class: NavigationRoute + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    + +

    new NavigationRoute(handler, options)

    +

    If both blacklist and whiltelist are provided, the blacklist will take precedence and the request will not match this route.

    +

    The regular expressions in whitelist and blacklist are matched against the concatenated + pathname and search portions of the requested URL.

    +
    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    handler

    +
    +

    workbox.routing.Route~handlerCallback

    +

    A callback function that returns a Promise resulting in a Response.

    +
    +

    options

    +
    +

    Object

    +

    Values in options have the following properties:

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    blacklist

    +
    +

    Optional

    +

    Array of RegExp

    +

    If any of these patterns match, the route will not handle the request (even if a whitelist RegExp matches).

    +
    +

    whitelist

    +
    +

    Optional

    +

    Array of RegExp

    +

    If any of these patterns match the URL's pathname and search parameter, the route will handle the request (assuming the blacklist doesn't match).

    +
    +
    +
    +
    +
    Extends
    +
    workbox.routing.Route
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.RegExpRoute.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.RegExpRoute.html new file mode 100644 index 00000000000..637d12a4496 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.RegExpRoute.html @@ -0,0 +1,89 @@ + + + + + + + + Class: RegExpRoute + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    RegExpRoute

    +

    new RegExpRoute(regExp, handler, method)

    +

    If the regulard expression contains + capture groups, th ecaptured values will be passed to the + handler's params argument. +

    +
    + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    regExp

    +
    +

    RegExp

    +

    The regular expression to match against URLs.

    +
    +

    handler

    +
    +

    workbox.routing.Route~handlerCallback

    +

    A callback function that returns a Promise resulting in a Response.

    +
    +

    method

    +
    +

    Optional

    +

    string

    +

    The HTTP method to match the Route against. +

    +
    +
    +
    +
    Extends
    +
    workbox.routing.Route
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.Route.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.Route.html new file mode 100644 index 00000000000..0f534c9e4b4 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.Route.html @@ -0,0 +1,219 @@ + + + + + + + + Class: Route + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    Route

    +

    new Route(match, handler, method)

    +

    Constructor for Route class.

    +
    + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    match

    +
    +

    workbox.routing.Route~matchCallback

    +

    A callback function that determines whether the route matches a given + fetch event by returning a non-falsy value.

    +
    +

    handler

    +
    +

    workbox.routing.Route~handlerCallback

    +

    A callback function that returns a Promise resolving to a Response.

    +
    +

    method

    +
    +

    Optional

    +

    string

    +

    The HTTP method to match the Route against. +

    +
    +
    +
    +
    +
    +
    +
    +

    Abstract types

    +
    +

    handlerCallback

    +
    inner
    +

    handlerCallback(context) returns Promise containing Response

    +

    The "handler" callback is called when a service worker's fetch event has been matched by a Route. This callback should return a Promise that resolves with a Response.

    +

    If a value is returned by the + match callback it will be passed in as the context.params argument.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    context

    +
    +

    Object

    +

    Values in context have the following properties:

    + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    url

    +
    +

    URL

    +

    The request's URL.

    +
    +

    event

    +
    +

    FetchEvent

    +

    The service worker's fetch event. +

    +
    +

    params

    +
    +

    Optional

    +

    Object

    +

    Parameters returned by the Route's + match callback function. This will be undefined if nothing was returned.

    +
    +
    +
    +
    +
    Returns
    +
    +

    Promise containing Response The response that will fulfill the request.

    +
    +
    +

    matchCallback

    +
    inner
    +

    matchCallback(context) returns (Object or null)

    +

    The "match" callback is used to determine if a Route should handle a service worker's fetch event. Returning a truthy value means this Route will handle and respond to the event.

    +

    Return null if this Route shouldn't match against the fetch event.

    +

    Any truthy value returned by this callback will be passed to the Route's + handler callback.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    context

    +
    +

    Object

    +

    Values in context have the following properties:

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    url

    +
    +

    URL

    +

    The request's URL.

    +
    +

    event

    +
    +

    FetchEvent

    +

    The service workersfetch` event. +

    +
    +
    +
    +
    +
    Returns
    +
    +

    (Object or null) To signify a match, return anything other than null. Return null if the route shouldn't match. + handler.

    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.Router.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.Router.html new file mode 100644 index 00000000000..d8c64040d37 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.Router.html @@ -0,0 +1,181 @@ + + + + + + + + Class: Router + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    Router

    +

    new Router() +

    +

    Initializes a new Router.

    +
    +
    +
    +
    +
    +

    Methods

    +
    +

    handleRequest

    +

    handleRequest(event) returns (Promise containing Response or undefined)

    +

    Apply the routing rules to a FetchEvent object to get a Response from an appropriate Route's handler.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    event

    +
    +

    FetchEvent

    +

    The event from a service worker's 'fetch' event listener. +

    +
    +
    +
    +
    Returns
    +
    +

    (Promise containing Response or undefined) A promise is returned if a registered route can handle the FetchEvent's request. If there is no matching route and there's no defaultHandler, undefined is returned.

    +
    +
    +

    registerRoute

    +

    registerRoute(route)

    +

    Registers a route with the router.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    route

    +
    +

    workbox.routing.Route

    +

    The route to register.

    +
    +
    +
    +
    +

    setCatchHandler

    +

    setCatchHandler(handler)

    +

    If a Route throws an error while handling a request, this handler will be called and given a chance to provide a response.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    handler

    +
    +

    workbox.routing.Route~handlerCallback

    +

    A callback function that returns a Promise resulting in a Response.

    +
    +
    +
    +
    +

    setDefaultHandler

    +

    setDefaultHandler(handler)

    +

    Define a default handler that's called when no routes explicitly match the incoming request.

    +

    Without a default handler, unmatched requests will go against the network as if there were no service worker present.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    handler

    +
    +

    workbox.routing.Route~handlerCallback

    +

    A callback function that returns a Promise resulting in a Response.

    +
    +
    +
    +
    +

    unregisterRoute

    +

    unregisterRoute(route)

    +

    Unregisters a route with the router.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    route

    +
    +

    workbox.routing.Route

    +

    The route to unregister.

    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.html new file mode 100644 index 00000000000..d7c7ef6e142 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.routing.html @@ -0,0 +1,271 @@ + + + + + + + + Namespace: routing + + + + +
    +
    +
    +
    + +
    +

    Classes

    + +

    Methods

    +
    +

    registerNavigationRoute

    +
    static
    +

    registerNavigationRoute(cachedAssetUrl, options) returns workbox.routing.NavigationRoute

    +

    Register a route that will return a precached file for a navigation request. This is useful for the + application shell pattern.

    +

    This method will generate a + NavigationRoute and call + Router.registerRoute() . +

    +
    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    cachedAssetUrl

    +
    +

    string

    +
    +

    options

    +
    +

    Optional

    +

    Object

    +

    Values in options have the following properties:

    + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    cacheName

    +
    +

    Optional

    +

    string

    +

    Cache name to store and retrieve requests. Defaults to precache cache name provided by + workbox-core.cacheNames.

    +
    +

    blacklist

    +
    +

    Optional

    +

    Array of RegExp

    +

    If any of these patterns match, the route will not handle the request (even if a whitelist entry matches). +

    +
    +

    whitelist

    +
    +

    Optional

    +

    Array of RegExp

    +

    If any of these patterns match the URL's pathname and search parameter, the route will handle the request (assuming the blacklist doesn't match).

    +
    +
    +
    +
    +
    Returns
    +
    +

    workbox.routing.NavigationRoute Returns the generated Route. +

    +
    +
    +

    registerRoute

    +
    static
    +

    registerRoute(capture, handler, method) returns workbox.routing.Route

    +

    Easily register a RegExp, string, or function with a caching strategy to the Router.

    +

    This method will generate a Route for you if needed and call Router.registerRoute().

    +
    + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    capture

    +
    +

    (RegExp, string, workbox.routing.Route~matchCallback, or workbox.routing.Route)

    +

    If the capture param is a Route, all other arguments will be ignored.

    +
    +

    handler

    +
    +

    workbox.routing.Route~handlerCallback

    +

    A callback function that returns a Promise resulting in a Response.

    +
    +

    method

    +
    +

    Optional

    +

    string

    +

    The HTTP method to match the Route against. +

    +
    +
    +
    +
    Returns
    +
    +

    workbox.routing.Route The generated Route(Useful for unregistering). +

    +
    +
    +

    setCatchHandler

    +
    static
    +

    setCatchHandler(handler)

    +

    If a Route throws an error while handling a request, this handler will be called and given a chance to provide a response.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    handler

    +
    +

    A callback function that returns a Promise resulting in a Response.

    +
    +
    +
    +
    +

    setDefaultHandler

    +
    static
    +

    setDefaultHandler(handler)

    +

    Define a default handler that's called when no routes explicitly match the incoming request.

    +

    Without a default handler, unmatched requests will go against the network as if there were no service worker present.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    handler

    +
    +

    A callback function that returns a Promise resulting in a Response.

    +
    +
    +
    +
    +

    unregisterRoute

    +
    static
    +

    unregisterRoute(route)

    +

    Unregisters a route with the router.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    route

    +
    +

    The route to unregister.

    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.CacheFirst.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.CacheFirst.html new file mode 100644 index 00000000000..136aa5ee290 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.CacheFirst.html @@ -0,0 +1,143 @@ + + + + + + + + Class: CacheFirst + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    CacheFirst

    +

    new CacheFirst(options) +

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    Object

    +

    Values in options have the following properties:

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    cacheName

    +
    +

    string

    +

    Cache name to store and retrieve requests. Defaults to cache names provided by + workbox-core.

    +
    +

    plugins

    +
    +

    string

    +

    Plugins to use in conjunction with this caching strategy.

    +
    +
    +
    +
    +
    +
    +
    +
    +

    Method

    +
    +

    handle

    +
    async
    +

    handle(input) returns Promise containing Response

    +

    This method will perform a request strategy and follows an API that will work with the + Workbox Router.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    input

    +
    +

    Object

    +

    Values in input have the following properties:

    + + + + + + + + + + +
    +

    Parameter

    +
    +

    event

    +
    +

    FetchEvent

    +

    The fetch event to run this strategy against. +

    +
    +
    +
    +
    +
    Returns
    +
    +

    Promise containing Response 

    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.CacheOnly.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.CacheOnly.html new file mode 100644 index 00000000000..c14993b1c0a --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.CacheOnly.html @@ -0,0 +1,144 @@ + + + + + + + + Class: CacheOnly + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    CacheOnly

    +

    new CacheOnly(options) +

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    Object

    +

    Values in options have the following properties:

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    cacheName

    +
    +

    string

    +

    Cache name to store and retrieve requests. Defaults to cache names provided by + workbox-core.

    +
    +

    plugins

    +
    +

    string

    +

    Plugins to use in conjunction with this caching strategy.

    +
    +
    +
    +
    +
    +
    +
    +
    +

    Method

    +
    +

    handle

    +
    async
    +

    handle(input) returns Promise containing Response

    +

    This method will perform a request strategy and follows an API that will work with the + Workbox Router.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    input

    +
    +

    Object

    +

    Values in input have the following properties:

    + + + + + + + + + + +
    +

    Parameter

    +
    +

    event

    +
    +

    FetchEvent

    +

    The fetch event to run this strategy against. +

    +
    +
    +
    +
    +
    Returns
    +
    +

    Promise containing Response 

    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.NetworkFirst.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.NetworkFirst.html new file mode 100644 index 00000000000..77db344285d --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.NetworkFirst.html @@ -0,0 +1,157 @@ + + + + + + + + Class: NetworkFirst + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    NetworkFirst

    +

    new NetworkFirst(options) +

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    Object

    +

    Values in options have the following properties:

    + + + + + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    cacheName

    +
    +

    string

    +

    Cache name to store and retrieve requests. Defaults to cache names provided by + workbox-core.

    +
    +

    plugins

    +
    +

    string

    +

    Plugins to use in conjunction with this caching strategy.

    +
    +

    networkTimeoutSeconds

    +
    +

    number

    +

    If set, any network requests that fail to respond within the timeout will fallback to the cache.

    +

    This option can be used to combat " + lie-fi" scenarios. +

    +
    +
    +
    +
    +
    +
    +
    +
    +

    Method

    +
    +

    handle

    +
    async
    +

    handle(input) returns Promise containing Response

    +

    This method will perform a request strategy and follows an API that will work with the + Workbox Router.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    input

    +
    +

    Object

    +

    Values in input have the following properties:

    + + + + + + + + + + +
    +

    Parameter

    +
    +

    event

    +
    +

    FetchEvent

    +

    The fetch event to run this strategy against. +

    +
    +
    +
    +
    +
    Returns
    +
    +

    Promise containing Response 

    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.NetworkOnly.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.NetworkOnly.html new file mode 100644 index 00000000000..8122c92437d --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.NetworkOnly.html @@ -0,0 +1,144 @@ + + + + + + + + Class: NetworkOnly + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    NetworkOnly

    +

    new NetworkOnly(options) +

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    Object

    +

    Values in options have the following properties:

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    cacheName

    +
    +

    string

    +

    Cache name to store and retrieve requests. Defaults to cache names provided by + workbox-core.

    +
    +

    plugins

    +
    +

    string

    +

    Plugins to use in conjunction with this caching strategy.

    +
    +
    +
    +
    +
    +
    +
    +
    +

    Method

    +
    +

    handle

    +
    async
    +

    handle(input) returns Promise containing Response

    +

    This method will perform a request strategy and follows an API that will work with the + Workbox Router.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    input

    +
    +

    Object

    +

    Values in input have the following properties:

    + + + + + + + + + + +
    +

    Parameter

    +
    +

    event

    +
    +

    FetchEvent

    +

    The fetch event to run this strategy against. +

    +
    +
    +
    +
    +
    Returns
    +
    +

    Promise containing Response 

    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.StaleWhileRevalidate.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.StaleWhileRevalidate.html new file mode 100644 index 00000000000..2270af2f817 --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.StaleWhileRevalidate.html @@ -0,0 +1,147 @@ + + + + + + + + Class: StaleWhileRevalidate + + + + +
    +
    +
    +
    + +
    +

    Constructor

    +
    +

    StaleWhileRevalidate

    +

    new StaleWhileRevalidate(options) +

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    Object

    +

    Values in options have the following properties:

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    cacheName

    +
    +

    string

    +

    Cache name to store and retrieve requests. Defaults to cache names provided by + workbox-core.

    +
    +

    plugins

    +
    +

    string

    +

    Plugins to use in conjunction with this caching strategy.

    +
    +
    +
    +
    +
    +
    +
    +
    +

    Method

    +
    +

    handle

    +
    async
    +

    handle(input) returns Promise containing Response

    +

    This method will perform a request strategy and follows an API that will work with the + Workbox Router.

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    input

    +
    +

    Object

    +

    Values in input have the following properties:

    + + + + + + + + + + +
    +

    Parameter

    +
    +

    event

    +
    +

    FetchEvent

    +

    The fetch event to run this strategy against. +

    +
    +
    +
    +
    +
    Returns
    +
    +

    Promise containing Response 

    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.html b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.html new file mode 100644 index 00000000000..51451e5280b --- /dev/null +++ b/src/content/en/tools/workbox/v3/reference-docs/latest/workbox.strategies.html @@ -0,0 +1,246 @@ + + + + + + + + Namespace: strategies + + + + +
    +
    +
    +
    + +
    +

    Classes

    + +

    Methods

    +
    +

    cacheFirst

    +
    static
    +

    cacheFirst(options)

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    StrategyOptions

    +
    +
    +
    +
    +

    cacheOnly

    +
    static
    +

    cacheOnly(options)

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    StrategyOptions

    +
    +
    +
    +
    +

    networkFirst

    +
    static
    +

    networkFirst(options)

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    StrategyOptions

    +
    +
    +
    +
    +

    networkOnly

    +
    static
    +

    networkOnly(options)

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    StrategyOptions

    +
    +
    +
    +
    +

    staleWhileRevalidate

    +
    static
    +

    staleWhileRevalidate(options)

    +
    + + + + + + + + + + +
    +

    Parameter

    +
    +

    options

    +
    +

    StrategyOptions

    +
    +
    +
    +
    +
    +

    Abstract type

    +
    +

    StrategyOptions

    +
    static
    +

    Object

    +
    +

    Properties

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    cacheName

    +
    +

    String

    +

    Name of cache to use for caching (both lookup and updating).

    +
    +

    cacheExpiration

    +
    +

    Object

    +

    Defining this object will add a cache expiration plugins to this strategy.

    +

    Values in cacheExpiration have the following properties:

    + + + + + + + + + + + + + + +
    +

    Parameter

    +
    +

    maxEntries

    +
    +

    Number

    +

    The maximum number of entries to store in a cache.

    +
    +

    maxAgeSeconds

    +
    +

    Number

    +

    The maximum lifetime of a request to stay in the cache before it's removed.

    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + \ No newline at end of file diff --git a/src/templates/reference-docs/jsdoc/views/details-table-row.hbs b/src/templates/reference-docs/jsdoc/views/details-table-row.hbs index 982f4835009..38ecebab387 100644 --- a/src/templates/reference-docs/jsdoc/views/details-table-row.hbs +++ b/src/templates/reference-docs/jsdoc/views/details-table-row.hbs @@ -24,9 +24,9 @@ {{#if (hasModifiers this)}}

    {{modifierText this}}

    {{/if}} - {{#if ../children}} + {{#if children}}

    {{translate 'tables.body.eachValueHasProperties' name=name}}

    - {{#withOnly values=../children}} + {{#withOnly values=children}} {{#embed 'details-table'}}{{/embed}} {{/withOnly}} {{/if}}