0.2.0-dev Download ZIP
165 lines ·5.6 KB Raw
| 1 | // This service worker is required to expose an exported Godot project as a |
| 2 | // Progressive Web App. It provides an offline fallback page telling the user |
| 3 | // that they need an Internet connection to run the project if desired. |
| 4 | // Incrementing CACHE_VERSION will kick off the install event and force |
| 5 | // previously cached resources to be updated from the network. |
| 6 | /** @type {string} */ |
| 7 | const CACHE_VERSION = '___GODOT_VERSION___'; |
| 8 | /** @type {string} */ |
| 9 | const CACHE_PREFIX = '___GODOT_NAME___-sw-cache-'; |
| 10 | const CACHE_NAME = CACHE_PREFIX + CACHE_VERSION; |
| 11 | /** @type {string} */ |
| 12 | const OFFLINE_URL = '___GODOT_OFFLINE_PAGE___'; |
| 13 | /** @type {boolean} */ |
| 14 | const ENSURE_CROSSORIGIN_ISOLATION_HEADERS = ___GODOT_ENSURE_CROSSORIGIN_ISOLATION_HEADERS___; |
| 15 | // Files that will be cached on load. |
| 16 | /** @type {string[]} */ |
| 17 | const CACHED_FILES = ___GODOT_CACHE___; |
| 18 | // Files that we might not want the user to preload, and will only be cached on first load. |
| 19 | /** @type {string[]} */ |
| 20 | const CACHEABLE_FILES = ___GODOT_OPT_CACHE___; |
| 21 | const FULL_CACHE = CACHED_FILES.concat(CACHEABLE_FILES); |
| 22 | |
| 23 | self.addEventListener('install', (event) => { |
| 24 | event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(CACHED_FILES))); |
| 25 | }); |
| 26 | |
| 27 | self.addEventListener('activate', (event) => { |
| 28 | event.waitUntil(caches.keys().then( |
| 29 | function (keys) { |
| 30 | // Remove old caches. |
| 31 | return Promise.all(keys.filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME).map((key) => caches.delete(key))); |
| 32 | } |
| 33 | ).then(function () { |
| 34 | // Enable navigation preload if available. |
| 35 | return ('navigationPreload' in self.registration) ? self.registration.navigationPreload.enable() : Promise.resolve(); |
| 36 | })); |
| 37 | }); |
| 38 | |
| 39 | /** |
| 40 | * Ensures that the response has the correct COEP/COOP headers |
| 41 | * @param {Response} response |
| 42 | * @returns {Response} |
| 43 | */ |
| 44 | function ensureCrossOriginIsolationHeaders(response) { |
| 45 | if (response.headers.get('Cross-Origin-Embedder-Policy') === 'require-corp' |
| 46 | && response.headers.get('Cross-Origin-Opener-Policy') === 'same-origin') { |
| 47 | return response; |
| 48 | } |
| 49 | |
| 50 | const crossOriginIsolatedHeaders = new Headers(response.headers); |
| 51 | crossOriginIsolatedHeaders.set('Cross-Origin-Embedder-Policy', 'require-corp'); |
| 52 | crossOriginIsolatedHeaders.set('Cross-Origin-Opener-Policy', 'same-origin'); |
| 53 | const newResponse = new Response(response.body, { |
| 54 | status: response.status, |
| 55 | statusText: response.statusText, |
| 56 | headers: crossOriginIsolatedHeaders, |
| 57 | }); |
| 58 | |
| 59 | return newResponse; |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Calls fetch and cache the result if it is cacheable |
| 64 | * @param {FetchEvent} event |
| 65 | * @param {Cache} cache |
| 66 | * @param {boolean} isCacheable |
| 67 | * @returns {Response} |
| 68 | */ |
| 69 | async function fetchAndCache(event, cache, isCacheable) { |
| 70 | // Use the preloaded response, if it's there |
| 71 | /** @type { Response } */ |
| 72 | let response = await event.preloadResponse; |
| 73 | if (response == null) { |
| 74 | // Or, go over network. |
| 75 | response = await self.fetch(event.request); |
| 76 | } |
| 77 | |
| 78 | if (ENSURE_CROSSORIGIN_ISOLATION_HEADERS) { |
| 79 | response = ensureCrossOriginIsolationHeaders(response); |
| 80 | } |
| 81 | |
| 82 | if (isCacheable) { |
| 83 | // And update the cache |
| 84 | cache.put(event.request, response.clone()); |
| 85 | } |
| 86 | |
| 87 | return response; |
| 88 | } |
| 89 | |
| 90 | self.addEventListener( |
| 91 | 'fetch', |
| 92 | /** |
| 93 | * Triggered on fetch |
| 94 | * @param {FetchEvent} event |
| 95 | */ |
| 96 | (event) => { |
| 97 | const isNavigate = event.request.mode === 'navigate'; |
| 98 | const url = event.request.url || ''; |
| 99 | const referrer = event.request.referrer || ''; |
| 100 | const base = referrer.slice(0, referrer.lastIndexOf('/') + 1); |
| 101 | const local = url.startsWith(base) ? url.replace(base, '') : ''; |
| 102 | const isCacheable = FULL_CACHE.some((v) => v === local) || (base === referrer && base.endsWith(CACHED_FILES[0])); |
| 103 | if (isNavigate || isCacheable) { |
| 104 | event.respondWith((async () => { |
| 105 | // Try to use cache first |
| 106 | const cache = await caches.open(CACHE_NAME); |
| 107 | if (isNavigate) { |
| 108 | // Check if we have full cache during HTML page request. |
| 109 | /** @type {Response[]} */ |
| 110 | const fullCache = await Promise.all(FULL_CACHE.map((name) => cache.match(name))); |
| 111 | const missing = fullCache.some((v) => v === undefined); |
| 112 | if (missing) { |
| 113 | try { |
| 114 | // Try network if some cached file is missing (so we can display offline page in case). |
| 115 | const response = await fetchAndCache(event, cache, isCacheable); |
| 116 | return response; |
| 117 | } catch (e) { |
| 118 | // And return the hopefully always cached offline page in case of network failure. |
| 119 | console.error('Network error: ', e); // eslint-disable-line no-console |
| 120 | return caches.match(OFFLINE_URL); |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | let cached = await cache.match(event.request); |
| 125 | if (cached != null) { |
| 126 | if (ENSURE_CROSSORIGIN_ISOLATION_HEADERS) { |
| 127 | cached = ensureCrossOriginIsolationHeaders(cached); |
| 128 | } |
| 129 | return cached; |
| 130 | } |
| 131 | // Try network if don't have it in cache. |
| 132 | const response = await fetchAndCache(event, cache, isCacheable); |
| 133 | return response; |
| 134 | })()); |
| 135 | } else if (ENSURE_CROSSORIGIN_ISOLATION_HEADERS) { |
| 136 | event.respondWith((async () => { |
| 137 | let response = await fetch(event.request); |
| 138 | response = ensureCrossOriginIsolationHeaders(response); |
| 139 | return response; |
| 140 | })()); |
| 141 | } |
| 142 | } |
| 143 | ); |
| 144 | |
| 145 | self.addEventListener('message', (event) => { |
| 146 | // No cross origin |
| 147 | if (event.origin !== self.origin) { |
| 148 | return; |
| 149 | } |
| 150 | const id = event.source.id || ''; |
| 151 | const msg = event.data || ''; |
| 152 | // Ensure it's one of our clients. |
| 153 | self.clients.get(id).then(function (client) { |
| 154 | if (!client) { |
| 155 | return; // Not a valid client. |
| 156 | } |
| 157 | if (msg === 'claim') { |
| 158 | self.skipWaiting().then(() => self.clients.claim()); |
| 159 | } else if (msg === 'clear') { |
| 160 | caches.delete(CACHE_NAME); |
| 161 | } else if (msg === 'update') { |
| 162 | self.skipWaiting().then(() => self.clients.claim()).then(() => self.clients.matchAll()).then((all) => all.forEach((c) => c.navigate(c.url))); |
| 163 | } |
| 164 | }); |
| 165 | }); |