Falln87/godot_editor
0
1// This service worker is required to expose an exported Godot project as a2// Progressive Web App. It provides an offline fallback page telling the user3// that they need an Internet connection to run the project if desired.4// Incrementing CACHE_VERSION will kick off the install event and force5// previously cached resources to be updated from the network.6const CACHE_VERSION = "3.4.4.rc.custom_build";7const CACHE_NAME = "GodotEngine-cache";8const OFFLINE_URL = "offline.html";9// Files that will be cached on load.10const CACHED_FILES = ["godot.tools.html", "offline.html", "godot.tools.js", "godot.tools.worker.js", "godot.tools.audio.worklet.js", "logo.svg", "favicon.png"];11// Files that we might not want the user to preload, and will only be cached on first load.12const CACHABLE_FILES = ["godot.tools.wasm"];13const FULL_CACHE = CACHED_FILES.concat(CACHABLE_FILES);14 15self.addEventListener("install", (event) => {16 event.waitUntil(async function () {17 const cache = await caches.open(CACHE_NAME);18 // Clear old cache (including optionals).19 await Promise.all(FULL_CACHE.map(path => cache.delete(path)));20 // Insert new one.21 const done = await cache.addAll(CACHED_FILES);22 return done;23 }());24});25 26self.addEventListener("activate", (event) => {27 event.waitUntil(async function () {28 if ("navigationPreload" in self.registration) {29 await self.registration.navigationPreload.enable();30 }31 }());32 // Tell the active service worker to take control of the page immediately.33 self.clients.claim();34});35 36self.addEventListener("fetch", (event) => {37 const isNavigate = event.request.mode === "navigate";38 const url = event.request.url || "";39 const referrer = event.request.referrer || "";40 const base = referrer.slice(0, referrer.lastIndexOf("/") + 1);41 const local = url.startsWith(base) ? url.replace(base, "") : "";42 const isCachable = FULL_CACHE.some(v => v === local) || (base === referrer && base.endsWith(CACHED_FILES[0]));43 if (isNavigate || isCachable) {44 event.respondWith(async function () {45 try {46 // Use the preloaded response, if it's there47 let request = event.request.clone();48 let response = await event.preloadResponse;49 if (!response) {50 // Or, go over network.51 response = await fetch(event.request);52 }53 if (isCachable) {54 // Update the cache55 const cache = await caches.open(CACHE_NAME);56 cache.put(request, response.clone());57 }58 return response;59 } catch (error) {60 const cache = await caches.open(CACHE_NAME);61 if (event.request.mode === "navigate") {62 // Check if we have full cache.63 const cached = await Promise.all(FULL_CACHE.map(name => cache.match(name)));64 const missing = cached.some(v => v === undefined);65 const cachedResponse = missing ? await caches.match(OFFLINE_URL) : await caches.match(CACHED_FILES[0]);66 return cachedResponse;67 }68 const cachedResponse = await caches.match(event.request);69 return cachedResponse;70 }71 }());72 }73});74 