|
1 |
| -// noop |
| 1 | +/* global importScripts, workbox, idbKeyval */ |
| 2 | + |
| 3 | +importScripts(`idb-keyval-iife.min.js`) |
| 4 | +const WHITELIST_KEY = `custom-navigation-whitelist` |
| 5 | + |
| 6 | +const navigationRoute = new workbox.routing.NavigationRoute(({ event }) => { |
| 7 | + const { pathname } = new URL(event.request.url) |
| 8 | + |
| 9 | + return idbKeyval.get(WHITELIST_KEY).then((customWhitelist = []) => { |
| 10 | + // Respond with the offline shell if we match the custom whitelist |
| 11 | + if (customWhitelist.includes(pathname)) { |
| 12 | + const offlineShell = `%pathPrefix%/offline-plugin-app-shell-fallback/index.html` |
| 13 | + const cacheName = workbox.core.cacheNames.precache |
| 14 | + |
| 15 | + return caches.match(offlineShell, { cacheName }) |
| 16 | + } |
| 17 | + |
| 18 | + return fetch(event.request) |
| 19 | + }) |
| 20 | +}) |
| 21 | + |
| 22 | +workbox.routing.registerRoute(navigationRoute) |
| 23 | + |
| 24 | +let updatingWhitelist = null |
| 25 | + |
| 26 | +function rawWhitelistPathnames(pathnames) { |
| 27 | + if (updatingWhitelist !== null) { |
| 28 | + // Prevent the whitelist from being updated twice at the same time |
| 29 | + return updatingWhitelist.then(() => rawWhitelistPathnames(pathnames)) |
| 30 | + } |
| 31 | + |
| 32 | + updatingWhitelist = idbKeyval |
| 33 | + .get(WHITELIST_KEY) |
| 34 | + .then((customWhitelist = []) => { |
| 35 | + pathnames.forEach(pathname => { |
| 36 | + if (!customWhitelist.includes(pathname)) customWhitelist.push(pathname) |
| 37 | + }) |
| 38 | + |
| 39 | + return idbKeyval.set(WHITELIST_KEY, customWhitelist) |
| 40 | + }) |
| 41 | + .then(() => { |
| 42 | + updatingWhitelist = null |
| 43 | + }) |
| 44 | + |
| 45 | + return updatingWhitelist |
| 46 | +} |
| 47 | + |
| 48 | +function rawResetWhitelist() { |
| 49 | + if (updatingWhitelist !== null) { |
| 50 | + return updatingWhitelist.then(() => rawResetWhitelist()) |
| 51 | + } |
| 52 | + |
| 53 | + updatingWhitelist = idbKeyval.set(WHITELIST_KEY, []).then(() => { |
| 54 | + updatingWhitelist = null |
| 55 | + }) |
| 56 | + |
| 57 | + return updatingWhitelist |
| 58 | +} |
| 59 | + |
| 60 | +const messageApi = { |
| 61 | + whitelistPathnames(event) { |
| 62 | + let { pathnames } = event.data |
| 63 | + |
| 64 | + pathnames = pathnames.map(({ pathname, includesPrefix }) => { |
| 65 | + if (!includesPrefix) { |
| 66 | + return `%pathPrefix%${pathname}` |
| 67 | + } else { |
| 68 | + return pathname |
| 69 | + } |
| 70 | + }) |
| 71 | + |
| 72 | + event.waitUntil(rawWhitelistPathnames(pathnames)) |
| 73 | + }, |
| 74 | + |
| 75 | + resetWhitelist(event) { |
| 76 | + event.waitUntil(rawResetWhitelist()) |
| 77 | + }, |
| 78 | +} |
| 79 | + |
| 80 | +self.addEventListener(`message`, event => { |
| 81 | + const { gatsbyApi } = event.data |
| 82 | + if (gatsbyApi) messageApi[gatsbyApi](event) |
| 83 | +}) |
0 commit comments