forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvirtual-server-main.js
More file actions
1 lines (1 loc) · 7.19 KB
/
virtual-server-main.js
File metadata and controls
1 lines (1 loc) · 7.19 KB
1
importScripts("phoenix/virtualfs.js"),importScripts("phoenix/virtualServer/mime-types.js"),importScripts("phoenix/virtualServer/config.js"),importScripts("phoenix/virtualServer/content-type.js"),importScripts("phoenix/virtualServer/webserver.js"),importScripts("https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js");const _debugSWCacheLogs=!1;workbox.setConfig({debug:_debugSWCacheLogs});const Route=workbox.routing.Route,cacheFirst=workbox.strategies.CacheFirst,StaleWhileRevalidate=workbox.strategies.StaleWhileRevalidate,ExpirationPlugin=workbox.expiration.ExpirationPlugin,DAYS_30_IN_SEC=2592e3,CACHE_NAME_EVERYTHING="everythingV2",CACHE_NAME_CORE_SCRIPTS="coreScripts",CACHE_NAME_EXTERNAL="external",WEB_CACHE_FILE_PATH="/webCacheVersion.txt";function _debugCacheLog(...args){_debugSWCacheLogs&&console.log(...args)}function _removeParams(url){return url.indexOf("?")>-1&&(url=url.substring(0,url.indexOf("?"))),location.href.indexOf("#")>-1&&(url=url.substring(0,url.indexOf("#"))),url}self._debugLivePreviewLog=function(...args){self._debugSWLivePreviewLogs&&console.log(...args)};let baseURL=location.href;baseURL=_removeParams(location.href),location.href.indexOf("/")>-1&&(baseURL=baseURL.substring(0,baseURL.lastIndexOf("/"))),baseURL.endsWith("/")||(baseURL+="/"),console.log("Service worker: base URL is: ",baseURL);const virtualServerBaseURL=`${baseURL}${Config.route}`;console.log("Service worker: Virtual server base URL is: ",virtualServerBaseURL);const wwwRegex=new RegExp(`${Config.route}(/.*)`);function _isVirtualServing(url){return url.startsWith(virtualServerBaseURL)}function _shouldVirtualServe(request){return _isVirtualServing(request.url.href)}function _isCacheableExternalUrl(url){let EXTERNAL_URLS=["https://storage.googleapis.com/workbox-cdn/"];for(let start of EXTERNAL_URLS)if(url.startsWith(start))return!0;return!1}workbox.routing.registerRoute(_shouldVirtualServe,({url:url})=>{let path=url.pathname.match(wwwRegex)[1];const download=!1;let phoenixInstanceID;if((path=decodeURI(path)).startsWith("/PHOENIX_LIVE_PREVIEW_")){let pathSplit=path.split("/");phoenixInstanceID=pathSplit[1].replace("PHOENIX_LIVE_PREVIEW_",""),pathSplit.shift(),pathSplit.shift(),path=`/${pathSplit.join("/")}`}return Serve.serve(path,!1,phoenixInstanceID)},"GET"),workbox.routing.registerRoute(_shouldVirtualServe,({url:url})=>(url.pathname=`${Config.route}/`,Promise.resolve(Response.redirect(url,302))),"GET"),addEventListener("message",event=>{let eventType;switch(event.data&&event.data.type){case"SKIP_WAITING":self.skipWaiting();break;case"INIT_PHOENIX_CONFIG":Config.debug=event.data.debugMode,self._debugSWLivePreviewLogs=event.data.logLivePreview,self.__WB_DISABLE_DEV_LOGS=Config.debug&&_debugSWCacheLogs,event.ports[0].postMessage({baseURL:baseURL});break;case"setInstrumentedURLs":return self.Serve.setInstrumentedURLs(event),!0;default:let msgProcessed;self.Serve&&self.Serve.processVirtualServerMessage&&self.Serve.processVirtualServerMessage(event)||console.error("Service worker cannot process, received unknown message: ",event)}});const DONT_CACHE_BASE_URLS=[`${location.origin}/src/`,`${location.origin}/test/`,`${location.origin}/dist/`,`${location.origin}/cacheManifest.json`,`${location.origin}/web-cache/`,`${baseURL}src/`,`${baseURL}test/`,`${baseURL}dist/`,`${baseURL}cacheManifest.json`,`${baseURL}web-cache/`];function _isNotCacheableUrl(url){for(let start of DONT_CACHE_BASE_URLS)if(url.startsWith(start))return!0;return!1}const CORE_SCRIPTS_URLS=[`${location.origin}/index.html`,`${location.origin}/`,`${location.origin}/virtual-server-main.js`,`${location.origin}/phoenix/virtual-server-loader.js`,`${baseURL}index.html`,`${baseURL}`,`${baseURL}virtual-server-main.js`,`${baseURL}phoenix/virtual-server-loader.js`];function _isCoreScript(url){for(let coreScript of CORE_SCRIPTS_URLS)if(url===coreScript)return!0;return!1}function _belongsToEverythingCache(request){let href=request.url.split("#")[0];if("video"===request.destination||"audio"===request.destination)return _debugCacheLog("Not Caching audio/video URL: ",request),!1;if(_isNotCacheableUrl(href))return _debugCacheLog("Not Caching un cacheable URL in everything cache: ",request),!1;if(_isCoreScript(href))return _debugCacheLog("Not Caching core scripts in everything cache: ",request),!1;if(!href.startsWith(baseURL))return _debugCacheLog("Not Caching external url in everything cache: ",request),!1;let disAllowedExtensions=/.zip$|.map$/i;return!(!href.startsWith(baseURL)||disAllowedExtensions.test(href))||(_debugCacheLog("Not Caching URL: ",request),!1)}let _everythingCache,_version,_everythingCacheName;function _getLatestCacheName(){return new Promise(resolve=>{fs.readFile(WEB_CACHE_FILE_PATH,"utf8",(err,version)=>{!err&&version?(_version=version,resolve(version)):resolve(CACHE_NAME_EVERYTHING)})})}async function _updateEverythingCache(){const cacheToUse=await _getLatestCacheName();return _everythingCacheName===cacheToUse&&_everythingCache?_everythingCache:(console.log("Service Worker: Using cache",cacheToUse),_everythingCache=await caches.open(cacheToUse),_everythingCacheName=cacheToUse,_everythingCache)}async function _getEverythingCache(){return _everythingCache||await _updateEverythingCache()}fs.watchAsync(WEB_CACHE_FILE_PATH).then(watcher=>{watcher.on(fs.WATCH_EVENTS.ADD_FILE,_updateEverythingCache),watcher.on(fs.WATCH_EVENTS.CHANGE,_updateEverythingCache)}).catch(console.error);const everythingCacheHandler=async({request:request,event:event})=>{let cache=await _getEverythingCache(),cachedResponse=await cache.match(new URL(request.url));if(cachedResponse)return cachedResponse;const versionedBase=`${baseURL}web-cache/${_version}`;_debugCacheLog("cache miss, fetching",request.url,"versioned base is",versionedBase);let versionedURL=request.url,shouldCache=!1;_version&&!versionedURL.startsWith(versionedBase)&&versionedURL.startsWith(baseURL)&&(shouldCache=!0,versionedURL=versionedURL.replace(baseURL,`${baseURL}web-cache/${_version}/`));let fetchResponse=await fetch(versionedURL,{method:"GET"});if(fetchResponse.ok&&shouldCache){const responseToCache=fetchResponse.clone(),responseBlob=await responseToCache.blob(),newResponse=new Response(responseBlob,{status:responseToCache.status,statusText:responseToCache.statusText,headers:responseToCache.headers});event.waitUntil(cache.put(new URL(request.url),newResponse))}else fetchResponse.ok||(fetchResponse=await fetch(request.url,{method:"GET"}));return fetchResponse},allCachedRoutes=new Route(({request:request})=>"GET"===request.method&&_belongsToEverythingCache(request)&&!_isVirtualServing(request.url),everythingCacheHandler),freshnessPreferredRoutes=new Route(({request:request})=>"GET"===request.method&&_isCoreScript(request.url)&&!_isVirtualServing(request.url),new StaleWhileRevalidate({cacheName:"coreScripts",plugins:[new ExpirationPlugin({maxAgeSeconds:2592e3,purgeOnQuotaError:!0})]})),externalCachedRoutes=new Route(({request:request})=>"GET"===request.method&&_isCacheableExternalUrl(request.url)&&!_isVirtualServing(request.url),new StaleWhileRevalidate({cacheName:"external",plugins:[new ExpirationPlugin({maxAgeSeconds:2592e3,purgeOnQuotaError:!0})]}));workbox.routing.registerRoute(allCachedRoutes),workbox.routing.registerRoute(freshnessPreferredRoutes),workbox.routing.registerRoute(externalCachedRoutes),workbox.core.clientsClaim();