@xiboplayer/pwa 0.4.8 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/cms-api-Cqh1b8je.js.map +1 -1
- package/dist/assets/{index-BVL7mqy8.js → index-66_11hkr.js} +2 -2
- package/dist/assets/{index-BVL7mqy8.js.map → index-66_11hkr.js.map} +1 -1
- package/dist/assets/index-B2e9LkNw.js +2 -0
- package/dist/assets/{index-BbPUooc2.js.map → index-B2e9LkNw.js.map} +1 -1
- package/dist/assets/{index-BbY9Gv8G.js → index-Bk3xGi9A.js} +2 -2
- package/dist/assets/{index-BbY9Gv8G.js.map → index-Bk3xGi9A.js.map} +1 -1
- package/dist/assets/{index-DGgd6YH4.js → index-CCUivrBn.js} +2 -2
- package/dist/assets/{index-DGgd6YH4.js.map → index-CCUivrBn.js.map} +1 -1
- package/dist/assets/index-CN4YZpqx.js +2 -0
- package/dist/assets/{index-QRZVtUP0.js.map → index-CN4YZpqx.js.map} +1 -1
- package/dist/assets/{index-DotIJR4q.js → index-DaTnG3Ri.js} +2 -2
- package/dist/assets/{index-DotIJR4q.js.map → index-DaTnG3Ri.js.map} +1 -1
- package/dist/assets/{index-DkCAUmMF.js → index-Do4yVSNc.js} +2 -2
- package/dist/assets/{index-DkCAUmMF.js.map → index-Do4yVSNc.js.map} +1 -1
- package/dist/assets/{index-H6ov_pKS.js → index-_Kvq-_Zm.js} +2 -2
- package/dist/assets/{index-H6ov_pKS.js.map → index-_Kvq-_Zm.js.map} +1 -1
- package/dist/assets/{index-9fl0y0Mg.js → index-pcbcUHVR.js} +2 -2
- package/dist/assets/{index-9fl0y0Mg.js.map → index-pcbcUHVR.js.map} +1 -1
- package/dist/assets/{main-cHm2a2zI.js → main-93Kmpgur.js} +6 -6
- package/dist/assets/main-93Kmpgur.js.map +1 -0
- package/dist/assets/setup-C_0dET1G.js +2 -0
- package/dist/assets/setup-C_0dET1G.js.map +1 -0
- package/dist/assets/sync-manager-Dm6IKYtR.js.map +1 -1
- package/dist/assets/{widget-html-PM6HCqWf.js → widget-html-Cb84FvUB.js} +2 -2
- package/dist/assets/{widget-html-PM6HCqWf.js.map → widget-html-Cb84FvUB.js.map} +1 -1
- package/dist/assets/xmds-client-BPdCcQeh.js.map +1 -1
- package/dist/index.html +15 -8
- package/dist/setup.html +32 -1
- package/dist/sw-pwa.js +1 -4
- package/dist/sw-pwa.js.map +1 -1
- package/package.json +1 -1
- package/dist/assets/index-BbPUooc2.js +0 -2
- package/dist/assets/index-QRZVtUP0.js +0 -2
- package/dist/assets/main-cHm2a2zI.js.map +0 -1
- package/dist/assets/setup-DteaE4RV.js +0 -2
- package/dist/assets/setup-DteaE4RV.js.map +0 -1
package/dist/sw-pwa.js
CHANGED
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
import{D as me}from"./assets/widget-html-PM6HCqWf.js";import{VERSION as ye}from"./assets/index-9fl0y0Mg.js";import"./assets/cms-api-Cqh1b8je.js";const b=(()=>{var r;return typeof self<"u"&&((r=self.registration)!=null&&r.scope)?new URL(self.registration.scope).pathname.replace(/\/$/,""):"/player/pwa"})();function M(r,e=1){if(r===0)return"0 Bytes";if(r<1024)return`${r} Bytes`;const t=r/1024;if(t<1024)return`${t.toFixed(e)} KB`;const s=t/1024;return s<1024?`${s.toFixed(e)} MB`:`${(s/1024).toFixed(e)} GB`}function se(r,e){const t=r.replace(/bytes=/,"").split("-"),s=parseInt(t[0],10),n=t[1]?parseInt(t[1],10):e-1;return{start:s,end:n}}function Ce(r,e,t){const s=Math.floor(r/t),n=Math.floor(e/t);return{startChunk:s,endChunk:n,count:n-s+1}}function ne(r,e,t,s,n){if(r.length===1){const c=e%s,l=t-e+1;return r[0].slice(c,c+l)}const a=[],i=e%s,o=t%s;a.push(r[0].slice(i));for(let c=1;c<r.length-1;c++)a.push(r[c]);return r.length>1&&a.push(r[r.length-1].slice(0,o+1)),new Blob(a,{type:n})}class N{constructor(e){this.name=e,this.level=typeof self<"u"&&self.swLogLevel||"INFO"}debug(...e){this.level==="DEBUG"&&console.log(`[${this.name}] DEBUG:`,...e)}info(...e){(this.level==="DEBUG"||this.level==="INFO")&&console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}}function ke(r){r||(r=new N("ChunkConfig"));const e=typeof navigator<"u"&&navigator.deviceMemory||null;let t=4;if(e)t=e,r.info("Detected device memory:",e,"GB");else if(typeof navigator<"u"){const o=navigator.userAgent.toLowerCase();o.includes("raspberry pi")||o.includes("armv6")?(t=.5,r.info("Detected Pi Zero (512 MB RAM estimated)")):o.includes("armv7")?(t=1,r.info("Detected ARM device (1 GB RAM estimated)")):r.info("Using default RAM estimate:",t,"GB")}let s,n,a,i;return t<=.5?(s=10*1024*1024,n=25,a=25*1024*1024,i=1,r.info("Low-memory config: 10 MB chunks, 25 MB cache, 1 concurrent download")):t<=1?(s=20*1024*1024,n=50,a=50*1024*1024,i=2,r.info("1GB-RAM config: 20 MB chunks, 50 MB cache, 2 concurrent downloads")):t<=2?(s=30*1024*1024,n=100,a=75*1024*1024,i=2,r.info("2GB-RAM config: 30 MB chunks, 100 MB cache, 2 concurrent downloads")):t<=4?(s=50*1024*1024,n=200,a=100*1024*1024,i=4,r.info("4GB-RAM config: 50 MB chunks, 200 MB cache, 4 concurrent downloads")):(s=100*1024*1024,n=500,a=200*1024*1024,i=6,r.info("High-RAM config: 100 MB chunks, 500 MB cache, 6 concurrent downloads")),{chunkSize:s,blobCacheSize:n,threshold:a,concurrency:i}}class be{constructor({cacheName:e="xibo-media-v1",chunkSize:t}={}){this.cache=null,this.cacheName=e,this.chunkSize=t,this.log=new N("Cache"),this.metadataCache=new Map}async init(){this.cache=await caches.open(this.cacheName)}async get(e){return this.cache||await this.init(),await this.cache.match(e,{ignoreSearch:!0,ignoreVary:!0})}async put(e,t,s){this.cache||await this.init();const n=new Response(t,{headers:{"Content-Type":s,"Content-Length":t.size,"Access-Control-Allow-Origin":"*","Accept-Ranges":"bytes"}});await this.cache.put(e,n)}async delete(e){this.cache||await this.init();const t=this.metadataCache.get(e);if(this.metadataCache.delete(e),t){const s=[this.cache.delete(`${e}/metadata`)];for(let n=0;n<t.numChunks;n++)s.push(this.cache.delete(`${e}/chunk-${n}`));return await Promise.all(s),!0}return await this.cache.delete(e)}async clear(){this.cache||await this.init();const e=await this.cache.keys();await Promise.all(e.map(t=>this.cache.delete(t))),this.metadataCache.clear(),this.log.info("Cleared",e.length,"cached files")}async fileExists(e){this.cache||await this.init();const t=this.metadataCache.get(e);if(t)return{exists:!0,chunked:!0,metadata:t};if(await this.get(e))return{exists:!0,chunked:!1,metadata:null};const n=await this.getMetadata(e);return n&&n.chunked?(this.metadataCache.set(e,n),{exists:!0,chunked:!0,metadata:n}):{exists:!1,chunked:!1,metadata:null}}async getFileSize(e){const t=await this.fileExists(e);if(!t.exists)return null;if(t.chunked)return t.metadata.totalSize;const s=await this.get(e),n=s==null?void 0:s.headers.get("Content-Length");return n?parseInt(n):null}async putChunked(e,t,s){this.cache||await this.init();const n=this.chunkSize,a=t.size,i=Math.ceil(a/n);this.log.info(`Storing as ${i} chunks: ${e} (${M(a)})`);const o={totalSize:a,chunkSize:n,numChunks:i,contentType:s,chunked:!0,complete:!1,createdAt:Date.now()},c=new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}});await this.cache.put(`${e}/metadata`,c),this.metadataCache.set(e,o);for(let l=0;l<i;l++){const d=l*n,f=Math.min(d+n,a),h=t.slice(d,f),g=new Response(h,{headers:{"Content-Type":s,"Content-Length":h.size,"X-Chunk-Index":l,"X-Total-Chunks":i}});await this.cache.put(`${e}/chunk-${l}`,g),((l+1)%5===0||l===i-1)&&this.log.info(`Stored chunk ${l+1}/${i} (${M(h.size)})`)}o.complete=!0,await this.cache.put(`${e}/metadata`,new Response(JSON.stringify(o),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(e,o),this.log.info(`Chunked storage complete: ${e}`)}async getMetadata(e){const t=this.metadataCache.get(e);if(t)return t;this.cache||await this.init();const s=await this.cache.match(`${e}/metadata`);if(!s)return null;const n=await s.text(),a=JSON.parse(n);return this.metadataCache.set(e,a),a}async updateMetadata(e,t){this.cache||await this.init(),await this.cache.put(`${e}/metadata`,new Response(JSON.stringify(t),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(e,t)}async getAllFiles(){this.cache||await this.init();const e=await this.cache.keys(),t=[],s=new Set;for(const n of e){const i=new URL(n.url).pathname;if(i.includes("/chunk-")||i.endsWith("/metadata")){const c=i.replace(/\/(chunk-\d+|metadata)$/,"");if(s.has(c))continue;s.add(c);const l=await this.getMetadata(c),d=c.match(/\/cache\/(media|layout|widget)\/(.+)/);d&&t.push({id:d[2],type:d[1],size:(l==null?void 0:l.totalSize)||0,cachedAt:(l==null?void 0:l.createdAt)||0});continue}if(i.includes("/cache/static/")||s.has(i))continue;s.add(i);const o=i.match(/\/cache\/(media|layout|widget)\/(.+)/);if(o){const c=await this.cache.match(n);t.push({id:o[2],type:o[1],size:parseInt((c==null?void 0:c.headers.get("Content-Length"))||"0"),cachedAt:0})}}return t}async isChunked(e){const t=await this.getMetadata(e);return(t==null?void 0:t.chunked)===!0}async getChunk(e,t){return this.cache||await this.init(),await this.cache.match(`${e}/chunk-${t}`)}}class $e{constructor(e=200){this.cache=new Map,this.maxBytes=e*1024*1024,this.currentBytes=0,this.log=new N("BlobCache")}has(e){return this.cache.has(e)}async get(e,t){if(this.cache.has(e)){const n=this.cache.get(e);return n.lastAccess=Date.now(),this.log.debug(`HIT: ${e} (${M(n.size)})`),n.blob}this.log.debug(`MISS: ${e} - loading from Cache API`);const s=await t();for(;this.currentBytes+s.size>this.maxBytes&&this.cache.size>0;)this.evictLRU();if(this.currentBytes+s.size<=this.maxBytes){this.cache.set(e,{blob:s,lastAccess:Date.now(),size:s.size}),this.currentBytes+=s.size;const n=(this.currentBytes/this.maxBytes*100).toFixed(1);this.log.debug(`CACHED: ${e} (${M(s.size)}) - utilization: ${n}%`)}else this.log.debug(`Skipping memory cache (too large): ${e} (${M(s.size)} > ${M(this.maxBytes)})`);return s}evictLRU(){let e=null,t=null;for(const[s,n]of this.cache)(!e||n.lastAccess<e.lastAccess)&&(e=n,t=s);t&&(this.currentBytes-=e.size,this.cache.delete(t),this.log.debug(`EVICTED LRU: ${t} (${M(e.size)})`))}clear(){this.cache.clear(),this.currentBytes=0,this.log.info("Cleared all cached blobs")}getStats(){return{entries:this.cache.size,bytes:this.currentBytes,maxBytes:this.maxBytes,utilization:(this.currentBytes/this.maxBytes*100).toFixed(1)+"%"}}}class _e{constructor(e,t,s,{staticCache:n="xibo-static-v1"}={}){this.downloadManager=e,this.cacheManager=t,this.blobCache=s,this.staticCache=n,this.pendingFetches=new Map,this.log=new N("SW"),this.pendingChunkLoads=new Map}async routeFileRequest(e,t,s){const n=await this.cacheManager.fileExists(e);if(!n.exists)return{found:!1,handler:null,data:null};if(n.chunked){const a={metadata:n.metadata,cacheKey:e};return t==="HEAD"?{found:!0,handler:"head-chunked",data:a}:s?{found:!0,handler:"range-chunked",data:{...a,rangeHeader:s}}:{found:!0,handler:"full-chunked",data:a}}else{const i={cached:await this.cacheManager.get(e),cacheKey:e};return t==="HEAD"?{found:!0,handler:"head-whole",data:i}:s?{found:!0,handler:"range-whole",data:{...i,rangeHeader:s}}:{found:!0,handler:"full-whole",data:i}}}async handleRequest(e){var f;const t=new URL(e.request.url);if(this.log.info("handleRequest called for:",t.href),this.log.info("pathname:",t.pathname),t.pathname===b+"/"||t.pathname===b+"/index.html"||t.pathname===b+"/setup.html"){const g=await(await caches.open(this.staticCache)).match(e.request);return g?(this.log.info("Serving static file from cache:",t.pathname),g):(this.log.info("Fetching static file from network:",t.pathname),fetch(e.request))}if((t.pathname.includes("xmds.php")||t.pathname.includes("pwa/file"))&&(t.searchParams.get("fileType")==="bundle"||t.searchParams.get("fileType")==="fontCss"||t.searchParams.get("fileType")==="font")){const h=t.searchParams.get("file"),g=`${b}/cache/static/${h}`,x=await caches.open(this.staticCache),k=await x.match(g);if(k)return this.log.info("Serving widget resource from cache:",h),k.clone();if(this.pendingFetches.has(h))return this.log.info("Deduplicating widget resource fetch:",h),(await this.pendingFetches.get(h)).clone();this.log.info("Fetching widget resource from CMS:",h);const E=(async()=>{try{const p=await fetch(e.request);if(p.ok){this.log.info("Caching widget resource:",h,`(${p.headers.get("Content-Type")})`);const I=p.clone();return await x.put(g,I),p}else return this.log.warn("Widget resource not available (",p.status,"):",h,"- NOT caching"),p}catch(p){return this.log.error("Failed to fetch widget resource:",h,p),new Response("Failed to fetch widget resource",{status:502,statusText:"Bad Gateway",headers:{"Content-Type":"text/plain"}})}})();this.pendingFetches.set(h,E);try{return(await E).clone()}finally{this.pendingFetches.delete(h)}}if((t.pathname.includes("xmds.php")||t.pathname.includes("pwa/file"))&&t.searchParams.has("file")){const h=t.searchParams.get("file"),g=h.split(".")[0],x=t.searchParams.get("type"),k=x==="L"?"layout":"media";this.log.info("XMDS request:",h,"type:",x,"→",b+"/cache/"+k+"/"+g);const E=`${b}/cache/${k}/${g}`,p=await this.cacheManager.get(E);return p?new Response(p.clone().body,{headers:{"Content-Type":p.headers.get("Content-Type")||"video/mp4","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000","Accept-Ranges":"bytes"}}):(this.log.info("XMDS file not cached, passing through:",h),fetch(e.request))}if(t.pathname.startsWith(b+"/cache/static/")){const h=t.pathname.split("/").pop();this.log.info("Static resource request:",h);const x=await(await caches.open(this.staticCache)).match(`${b}/cache/static/${h}`);if(x)return this.log.info("Serving static resource from static cache:",h),x.clone();const k=await this.cacheManager.get(t.pathname);return k?(this.log.info("Serving static resource from media cache:",h),new Response(k.clone().body,{headers:{"Content-Type":k.headers.get("Content-Type")||"application/octet-stream","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})):(this.log.warn("Static resource not cached:",h),new Response("Resource not cached",{status:404}))}if(!t.pathname.startsWith(b+"/cache/"))return this.log.info("NOT a cache request, returning null:",t.pathname),null;if(this.log.info("IS a cache request, proceeding...",t.pathname),t.pathname.startsWith(b+"/cache/widget/")){this.log.info("Widget HTML request:",t.pathname);const h=await this.cacheManager.get(t.pathname);return h?new Response(h.clone().body,{headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}}):new Response("<!DOCTYPE html><html><body>Widget not found</body></html>",{status:404,headers:{"Content-Type":"text/html"}})}const s=t.pathname.replace(/\.json$/,""),n=e.request.method,a=e.request.headers.get("Range");this.log.debug("Request URL:",t.pathname),this.log.debug("Cache key:",s),a?this.log.info(n,s,`Range: ${a}`):this.log.info(n,s);const i=await this.routeFileRequest(s,n,a);if(i.found)switch(i.handler){case"head-whole":return this.handleHeadWhole((f=i.data.cached)==null?void 0:f.headers.get("Content-Length"));case"head-chunked":return this.handleHeadChunked(i.data.metadata,i.data.cacheKey);case"range-whole":return this.handleRangeRequest(i.data.cached,i.data.rangeHeader,i.data.cacheKey);case"range-chunked":return this.handleChunkedRangeRequest(i.data.cacheKey,i.data.rangeHeader,i.data.metadata);case"full-whole":return this.handleFullWhole(i.data.cached,i.data.cacheKey);case"full-chunked":return this.handleFullChunked(i.data.cacheKey,i.data.metadata);default:return this.log.error("Unknown handler:",i.handler),new Response("Internal error: unknown handler",{status:500})}const o=s.split("/"),c=o[o.length-2],l=o[o.length-1];let d=null;for(const[,h]of this.downloadManager.queue.active.entries())if(h.fileInfo.type===c&&String(h.fileInfo.id)===l){d=h;break}if(d){this.log.info("Download in progress, waiting:",s);try{await d.wait();const h=await this.routeFileRequest(s,n,a);if(h.found)switch(this.log.info("Download complete, serving via",h.handler),h.handler){case"full-whole":return this.handleFullWhole(h.data.cached,h.data.cacheKey);case"full-chunked":return this.handleFullChunked(h.data.cacheKey,h.data.metadata);default:return this.handleRequest(e)}}catch(h){return this.log.error("Download failed:",s,h),new Response("Download failed: "+h.message,{status:500})}}return this.log.info("Not found:",s),new Response("Not found",{status:404})}handleHeadWhole(e){return this.log.info("HEAD response: File exists (whole file)"),new Response(null,{status:200,headers:{"Content-Length":e?e.toString():"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleHeadChunked(e,t){return await this.cacheManager.getChunk(t,0)?(this.log.info("HEAD response: File exists (chunked)"),new Response(null,{status:200,headers:{"Content-Length":e.totalSize.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})):(this.log.info("HEAD response: Chunked file not yet playable (chunk 0 missing):",t),new Response(null,{status:404}))}handleFullWhole(e,t){const s=e.headers.get("Content-Length"),n=s?M(parseInt(s)):"unknown size";return this.log.info("Serving from cache:",t,`(${n})`),new Response(e.body,{headers:{"Content-Type":e.headers.get("Content-Type")||"application/octet-stream","Content-Length":s||"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})}async handleFullChunked(e,t){this.log.info("Chunked file GET without Range:",e,`- serving full file from ${t.numChunks} chunks`);const s=`bytes=0-${t.totalSize-1}`;return this.handleChunkedRangeRequest(e,s,t)}async handleRangeRequest(e,t,s){const n=await this.blobCache.get(s,async()=>await e.clone().blob()),a=n.size,{start:i,end:o}=se(t,a),c=n.slice(i,o+1);return this.log.debug(`Range: bytes ${i}-${o}/${a} (${M(c.size)} of ${M(a)})`),new Response(c,{status:206,statusText:"Partial Content",headers:{"Content-Type":e.headers.get("Content-Type")||"video/mp4","Content-Length":c.size.toString(),"Content-Range":`bytes ${i}-${o}/${a}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleChunkedRangeRequest(e,t,s){const{totalSize:n,chunkSize:a,numChunks:i,contentType:o}=s,{start:c,end:l}=se(t,n);let d=l;const f=t.replace(/bytes=/,"");if(f.indexOf("-")===f.length-1){const w=Math.floor(c/a),u=i-1;let m=!0;for(let y=w;y<=u;y++){const $=`${e}/chunk-${y}`;if(this.blobCache.has($))continue;if(!await this.cacheManager.getChunk(e,y)){m=!1;break}}if(m)this.log.info(`All chunks cached from ${w} to ${u}, serving full range (bytes ${c}-${d}/${n})`);else{const y=Math.min((w+1)*a-1,n-1);y<d&&(d=y,this.log.info(`Progressive streaming: capping bytes=${c}- to chunk ${w} (bytes ${c}-${d}/${n})`))}}const{startChunk:g,endChunk:x,count:k}=Ce(c,d,a);this.log.debug(`Chunked range: bytes ${c}-${d}/${n} (chunks ${g}-${x}, ${k} chunks)`);const E=w=>{const u=`${e}/chunk-${w}`;return this.blobCache.get(u,()=>{if(this.pendingChunkLoads.has(u))return this.pendingChunkLoads.get(u);const m=(async()=>{let y=await this.cacheManager.getChunk(e,w);if(y)return await y.blob();this.log.info(`Chunk ${w}/${i} not yet available for ${e}, signalling urgent...`);{const $=e.split("/"),_=$[$.length-1],T=$[$.length-2];this.downloadManager.queue.urgentChunk(T,_,w)}for(let $=0;$<60;$++)if(await new Promise(_=>setTimeout(_,1e3)),y=await this.cacheManager.getChunk(e,w),y)return this.log.info(`Chunk ${w}/${i} arrived for ${e} after ${$+1}s`),await y.blob();throw new Error(`Chunk ${w} not available for ${e} after 60s`)})();return this.pendingChunkLoads.set(u,m),m.finally(()=>this.pendingChunkLoads.delete(u)),m})},p=[];let I=!0;for(let w=g;w<=x;w++){const u=await this.cacheManager.getChunk(e,w);if(u){const m=`${e}/chunk-${w}`,y=await this.blobCache.get(m,async()=>await u.blob());p.push(y)}else{I=!1;break}}if(I&&p.length===k){const w=ne(p,c,d,a);return this.log.debug(`Serving chunked range: ${M(w.size)} from ${k} chunk(s)`),new Response(w,{status:206,statusText:"Partial Content",headers:{"Content-Type":o,"Content-Length":w.size.toString(),"Content-Range":`bytes ${c}-${d}/${n}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}this.log.info(`Streaming response for ${e} bytes ${c}-${d} (waiting for chunks)`);const P=d-c+1,q=new ReadableStream({async start(w){try{const u=[];for(let $=g;$<=x;$++){const _=await E($);u.push(_)}const y=await ne(u,c,d,a).arrayBuffer();w.enqueue(new Uint8Array(y)),w.close()}catch(u){this.log.error(`Stream error for ${e}: ${u.message}`),w.error(u)}}});return new Response(q,{status:206,statusText:"Partial Content",headers:{"Content-Type":o,"Content-Length":P.toString(),"Content-Range":`bytes ${c}-${d}/${n}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}}const F={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},ae=[];class xe{constructor(e,t=null){this.name=e,this.useGlobal=t===null,this.useGlobal||this.setLevel(t)}setLevel(e){this.useGlobal=!1,typeof e=="string"?this.level=F[e.toUpperCase()]??F.INFO:this.level=e}getEffectiveLevel(){return this.useGlobal?K.level:this.level}debug(...e){this.getEffectiveLevel()<=F.DEBUG&&console.log(`[${this.name}] DEBUG:`,...e),O("debug",this.name,e)}info(...e){this.getEffectiveLevel()<=F.INFO&&console.log(`[${this.name}]`,...e),O("info",this.name,e)}warn(...e){this.getEffectiveLevel()<=F.WARNING&&console.warn(`[${this.name}]`,...e),O("warning",this.name,e)}error(...e){this.getEffectiveLevel()<=F.ERROR&&console.error(`[${this.name}]`,...e),O("error",this.name,e)}log(e,...t){switch(e.toUpperCase()){case"DEBUG":return this.debug(...t);case"INFO":return this.info(...t);case"WARNING":case"WARN":return this.warn(...t);case"ERROR":return this.error(...t)}}}const K={level:F.WARNING,setGlobalLevel(r){typeof r=="string"?this.level=F[r.toUpperCase()]??F.INFO:this.level=r,console.log(`[Logger] Global log level set to: ${this.getLevelName(this.level)}`)},getLevelName(r){return Object.keys(F).find(e=>F[e]===r)||"UNKNOWN"}};if(typeof window<"u"){const e=new URLSearchParams(window.location.search).get("logLevel"),t=localStorage.getItem("xibo_log_level");e?K.setGlobalLevel(e):t?K.setGlobalLevel(t):K.setGlobalLevel("WARNING")}function V(r,e=null){return new xe(r,e)}function O(r,e,t){if(ae.length!==0)for(const s of ae)try{s({level:r,name:e,args:t})}catch{}}function ie(r,e){const t=new Uint8Array(r);let s="";for(let i=0;i<t.length;i++)s+=String.fromCharCode(t[i]);const n=btoa(s),a=[];for(let i=0;i<n.length;i+=64)a.push(n.substring(i,i+64));return`-----BEGIN ${e}-----
|
|
2
|
-
${a.join(`
|
|
3
|
-
`)}
|
|
4
|
-
-----END ${e}-----`}async function Re(){const r=await crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:1024,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),e=await crypto.subtle.exportKey("spki",r.publicKey),t=await crypto.subtle.exportKey("pkcs8",r.privateKey);return{publicKeyPem:ie(e,"PUBLIC KEY"),privateKeyPem:ie(t,"PRIVATE KEY")}}function ve(r){return!r||typeof r!="string"?!1:/^-----BEGIN (PUBLIC KEY|PRIVATE KEY)-----\n[A-Za-z0-9+/=\n]+\n-----END \1-----$/.test(r.trim())}var oe={};const U="xibo_config",re="xibo-hw-backup",ce=1;function Se(){const r=typeof process<"u"&&oe?oe:{},e={cmsAddress:r.CMS_ADDRESS||r.CMS_URL||"",cmsKey:r.CMS_KEY||"",displayName:r.DISPLAY_NAME||"",hardwareKey:r.HARDWARE_KEY||"",xmrChannel:r.XMR_CHANNEL||"",googleGeoApiKey:r.GOOGLE_GEO_API_KEY||""};return Object.values(e).some(s=>s!=="")?e:null}class Ae{constructor(){this.data=this.load(),this._fromEnv||this._restoreHardwareKeyFromBackup()}load(){const e=Se();if(e)return this._fromEnv=!0,e;if(typeof localStorage>"u")return{cmsAddress:"",cmsKey:"",displayName:"",hardwareKey:"",xmrChannel:""};const t=localStorage.getItem(U);if(t)try{const n=JSON.parse(t);return!n.hardwareKey||n.hardwareKey.length<10?(console.error("[Config] CRITICAL: Invalid/missing hardwareKey in localStorage!"),n.hardwareKey=this.generateStableHardwareKey(),localStorage.setItem(U,JSON.stringify(n)),this._backupHardwareKey(n.hardwareKey)):console.log("[Config] ✓ Loaded existing hardwareKey:",n.hardwareKey),n}catch(n){console.error("[Config] Failed to parse config from localStorage:",n)}console.log("[Config] No config in localStorage - first time setup");const s={cmsAddress:"",cmsKey:"",displayName:"",hardwareKey:this.generateStableHardwareKey(),xmrChannel:this.generateXmrChannel()};return localStorage.setItem(U,JSON.stringify(s)),this._backupHardwareKey(s.hardwareKey),console.log("[Config] ✓ Saved new config to localStorage"),console.log("[Config] Hardware key will persist across reloads:",s.hardwareKey),s}_backupKeys(e){try{const t=indexedDB.open(re,ce);t.onupgradeneeded=()=>{const s=t.result;s.objectStoreNames.contains("keys")||s.createObjectStore("keys")},t.onsuccess=()=>{const s=t.result,n=s.transaction("keys","readwrite"),a=n.objectStore("keys");for(const[i,o]of Object.entries(e))a.put(o,i);n.oncomplete=()=>{console.log("[Config] Keys backed up to IndexedDB:",Object.keys(e).join(", ")),s.close()}}}catch{}}_backupHardwareKey(e){this._backupKeys({hardwareKey:e})}async _restoreHardwareKeyFromBackup(){if(!(typeof indexedDB>"u"))try{const e=await new Promise((a,i)=>{const o=indexedDB.open(re,ce);o.onupgradeneeded=()=>{const c=o.result;c.objectStoreNames.contains("keys")||c.createObjectStore("keys")},o.onsuccess=()=>a(o.result),o.onerror=()=>i(o.error)}),s=e.transaction("keys","readonly").objectStore("keys"),n=await new Promise(a=>{const i=s.get("hardwareKey");i.onsuccess=()=>a(i.result),i.onerror=()=>a(null)});e.close(),n&&n!==this.data.hardwareKey?(console.log("[Config] Restoring hardware key from IndexedDB backup:",n),console.log("[Config] (was:",this.data.hardwareKey,")"),this.data.hardwareKey=n,this.save()):!n&&this.data.hardwareKey&&this._backupHardwareKey(this.data.hardwareKey)}catch{}}save(){typeof localStorage<"u"&&localStorage.setItem(U,JSON.stringify(this.data))}isConfigured(){return!!(this.data.cmsAddress&&this.data.cmsKey&&this.data.displayName)}generateStableHardwareKey(){if(typeof crypto<"u"&&crypto.randomUUID){const n="pwa-"+crypto.randomUUID().replace(/-/g,"").substring(0,28);return console.log("[Config] Generated new UUID-based hardware key:",n),n}const t="pwa-"+Array.from({length:28},()=>Math.floor(Math.random()*16).toString(16)).join("");return console.log("[Config] Generated new random hardware key:",t),t}getCanvasFingerprint(){try{const e=document.createElement("canvas"),t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("Xibo Player",2,15),e.toDataURL()):"no-canvas"}catch{return"canvas-error"}}generateHardwareKey(){return this.generateStableHardwareKey()}generateXmrChannel(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}async ensureXmrKeyPair(){if(this.data.xmrPubKey&&ve(this.data.xmrPubKey))return;console.log("[Config] Generating RSA key pair for XMR registration...");const{publicKeyPem:e,privateKeyPem:t}=await Re();this.data.xmrPubKey=e,this.data.xmrPrivKey=t,this.save(),typeof indexedDB<"u"&&this._backupKeys({xmrPubKey:e,xmrPrivKey:t}),console.log("[Config] RSA key pair generated and saved")}hash(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);t=t>>>0;let s="";for(let n=0;n<4;n++){let a=t+n*1234567;for(let i=0;i<e.length;i++)a^=e.charCodeAt(i)+n,a+=(a<<1)+(a<<4)+(a<<7)+(a<<8)+(a<<24);a=a>>>0,s+=a.toString(16).padStart(8,"0")}return s.substring(0,32)}get cmsAddress(){return this.data.cmsAddress}set cmsAddress(e){this.data.cmsAddress=e,this.save()}get cmsKey(){return this.data.cmsKey}set cmsKey(e){this.data.cmsKey=e,this.save()}get displayName(){return this.data.displayName}set displayName(e){this.data.displayName=e,this.save()}get hardwareKey(){return this.data.hardwareKey||(console.error("[Config] CRITICAL: hardwareKey missing! Generating emergency key."),this.data.hardwareKey=this.generateStableHardwareKey(),this.save()),this.data.hardwareKey}get xmrChannel(){return this.data.xmrChannel}get xmrPubKey(){return this.data.xmrPubKey||""}get xmrPrivKey(){return this.data.xmrPrivKey||""}get googleGeoApiKey(){return this.data.googleGeoApiKey||""}set googleGeoApiKey(e){this.data.googleGeoApiKey=e,this.save()}}new Ae;V("FetchRetry");V("CmsApi");const C=V("Download"),Ee=6,ue=50*1024*1024,Te=3,Me=100*1024*1024,j=3,Fe=500,De=2,he=6e5,Ie=15e3;function Le(r){var n,a;const t=(a=(n=(r.path||r.code||"").split(".").pop())==null?void 0:n.split("?")[0])==null?void 0:a.toLowerCase();return{mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",css:"text/css",js:"application/javascript",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",xml:"application/xml",xlf:"application/xml"}[t]||"application/octet-stream"}const A={normal:0,layout:1,high:2,urgent:3},D=Symbol("BARRIER");function z(r){try{const e=r.match(/X-Amz-Expires=(\d+)/);return e?parseInt(e[1],10):1/0}catch{return 1/0}}function de(r,e=30){const t=z(r);return t===1/0?!1:Date.now()/1e3>=t-e}function G(r){if(!r.startsWith("http"))return r;const e=typeof self<"u"?self.location:void 0;if(!e||e.hostname!=="localhost"||e.port!=="8765")return r;const t=new URL(r),s=t.origin;return`/file-proxy?cms=${encodeURIComponent(s)}&url=${encodeURIComponent(t.pathname+t.search)}`}class Q{constructor(e,t={}){this.fileInfo=e,this.chunkIndex=t.chunkIndex??null,this.rangeStart=t.rangeStart??null,this.rangeEnd=t.rangeEnd??null,this.state="pending",this.blob=null,this._parentFile=null,this._priority=A.normal}getUrl(){const e=this.fileInfo.path;if(de(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return G(e)}async start(){this.state="downloading";const e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`);for(let t=1;t<=j;t++){const s=new AbortController,n=setTimeout(()=>s.abort(),he);try{const a=this.getUrl(),i={signal:s.signal};Object.keys(e).length>0&&(i.headers=e);const o=await fetch(a,i);if(!o.ok&&o.status!==206)throw new Error(`Fetch failed: ${o.status}`);return this.blob=await o.blob(),this.state="complete",this.blob}catch(a){const i=s.signal.aborted?`Timeout after ${he/1e3}s`:a.message;if(t<j){const o=Fe*t,c=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";C.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${c} attempt ${t}/${j} failed: ${i}. Retrying in ${o/1e3}s...`),await new Promise(l=>setTimeout(l,o))}else throw this.state="failed",s.signal.aborted?new Error(i):a}finally{clearTimeout(n)}}}}class fe{constructor(e,t={}){this.fileInfo=e,this.options=t,this.state="pending",this.tasks=[],this.completedChunks=0,this.totalChunks=0,this.totalBytes=0,this.downloadedBytes=0,this.onChunkDownloaded=null,this.skipChunks=e.skipChunks||new Set,this._contentType="application/octet-stream",this._chunkBlobs=new Map,this._runningCount=0,this._resolve=null,this._reject=null,this._promise=new Promise((s,n)=>{this._resolve=s,this._reject=n}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(de(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return G(e)}wait(){return this._promise}async prepare(e){try{this.state="preparing";const{id:t,type:s,size:n}=this.fileInfo;if(C.info("[FileDownload] Starting:",`${s}/${t}`),this.totalBytes=n&&n>0?parseInt(n):0,this._contentType=Le(this.fileInfo),this.totalBytes===0){const i=this.getUrl(),o=new AbortController,c=setTimeout(()=>o.abort(),Ie);try{const l=await fetch(i,{method:"HEAD",signal:o.signal});l.ok&&(this.totalBytes=parseInt(l.headers.get("Content-Length")||"0"),this._contentType=l.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(c)}}C.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const a=this.options.chunkSize||ue;if(this.totalBytes>Me){const i=[];for(let f=0;f<this.totalBytes;f+=a)i.push({start:f,end:Math.min(f+a-1,this.totalBytes-1),index:i.length});this.totalChunks=i.length;const o=i.filter(f=>!this.skipChunks.has(f.index)),c=i.length-o.length;for(const f of i)this.skipChunks.has(f.index)&&(this.downloadedBytes+=f.end-f.start+1);if(o.length===0){C.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}c>0&&C.info(`[FileDownload] Resuming: ${c} chunks cached, ${o.length} to download`);const l=c>0;if(l){const f=o.sort((h,g)=>h.index-g.index);for(const h of f){const g=new Q(this.fileInfo,{chunkIndex:h.index,rangeStart:h.start,rangeEnd:h.end});g._parentFile=this,g._priority=A.normal,this.tasks.push(g)}}else for(const f of o){const h=new Q(this.fileInfo,{chunkIndex:f.index,rangeStart:f.start,rangeEnd:f.end});h._parentFile=this,h._priority=f.index===0||f.index===i.length-1?A.high:A.normal,this.tasks.push(h)}const d=this.tasks.filter(f=>f._priority>=A.high).length;C.info(`[FileDownload] ${s}/${t}: ${this.tasks.length} chunks`+(d>0?` (${d} priority)`:"")+(l?" (resume)":""))}else{this.totalChunks=1;const i=new Q(this.fileInfo,{});i._parentFile=this,this.tasks.push(i)}e.enqueueChunkTasks(this.tasks),this.state="downloading"}catch(t){C.error("[FileDownload] Prepare failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}async onTaskComplete(e){if(this.completedChunks++,this.downloadedBytes+=e.blob.size,e.chunkIndex!=null&&this._chunkBlobs.set(e.chunkIndex,e.blob),this.options.onProgress&&this.options.onProgress(this.downloadedBytes,this.totalBytes),this.onChunkDownloaded&&e.chunkIndex!=null)try{await this.onChunkDownloaded(e.chunkIndex,e.blob,this.totalChunks)}catch(t){C.warn("[FileDownload] onChunkDownloaded callback error:",t)}if(this.completedChunks===this.tasks.length&&this.state!=="complete"){this.state="complete";const{type:t,id:s}=this.fileInfo;if(e.chunkIndex==null)C.info("[FileDownload] Complete:",`${t}/${s}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)C.info("[FileDownload] Complete:",`${t}/${s}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const n=[];for(let i=0;i<this.totalChunks;i++){const o=this._chunkBlobs.get(i);o&&n.push(o)}const a=new Blob(n,{type:this._contentType});C.info("[FileDownload] Complete:",`${t}/${s}`,`(${a.size} bytes, reassembled)`),this._resolve(a)}this._chunkBlobs.clear()}}onTaskFailed(e,t){var s;if(!(this.state==="complete"||this.state==="failed")){if((s=t.message)!=null&&s.includes("URL expired")){const n=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";C.warn(`[FileDownload] URL expired, dropping${n}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(a=>a!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state="complete",this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}C.error("[FileDownload] Failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}}class X{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const t=J.stableKey(e);if(this.queue.active.has(t)){const n=this.queue.active.get(t);if(e.path&&e.path!==n.fileInfo.path){const a=z(n.fileInfo.path);z(e.path)>a&&(n.fileInfo.path=e.path)}return n}const s=new fe(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(t,s),this._filesToPrepare.push(s),s}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let t=0,s=0;const n=()=>{for(;t<this._maxPreparing&&s<this._filesToPrepare.length;){const a=this._filesToPrepare[s++];t++,a.prepare(this).finally(()=>{t--,s>=this._filesToPrepare.length&&t===0?e():n()})}};this._filesToPrepare.length===0?e():n()})}_sortWithBarriers(){var i;const e=[],t=[],s=[],n=[];for(const o of this._tasks)if(o.chunkIndex==null)e.push(o);else if(o.chunkIndex===0)t.push(o);else{const c=((i=o._parentFile)==null?void 0:i.totalChunks)||0;c>1&&o.chunkIndex===c-1?s.push(o):n.push(o)}e.sort((o,c)=>{var l,d;return(((l=o._parentFile)==null?void 0:l.totalBytes)||0)-(((d=c._parentFile)==null?void 0:d.totalBytes)||0)}),n.sort((o,c)=>o.chunkIndex-c.chunkIndex);const a=[...e,...t,...s];return n.length>0&&a.push(D,...n),a}}class J{constructor(e={}){this.concurrency=e.concurrency||Ee,this.chunkSize=e.chunkSize||ue,this.maxChunksPerFile=e.chunksPerFile||Te,this.calculateMD5=e.calculateMD5,this.onProgress=e.onProgress,this.queue=[],this.active=new Map,this._activeTasks=[],this.running=0,this._prepareQueue=[],this._preparingCount=0,this._maxPreparing=2,this.paused=!1}static stableKey(e){return`${e.type}/${e.id}`}enqueue(e){const t=J.stableKey(e);if(this.active.has(t)){const n=this.active.get(t);if(e.path&&e.path!==n.fileInfo.path){const a=z(n.fileInfo.path);z(e.path)>a&&(C.info("[DownloadQueue] Refreshing URL for",t),n.fileInfo.path=e.path)}return n}const s=new fe(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(t,s),C.info("[DownloadQueue] Enqueued:",t),this._schedulePrepare(s),s}_schedulePrepare(e){this._prepareQueue.push(e),this._processPrepareQueue()}_processPrepareQueue(){for(;this._preparingCount<this._maxPreparing&&this._prepareQueue.length>0;){const e=this._prepareQueue.shift();this._preparingCount++,e.prepare(this).finally(()=>{this._preparingCount--,this._processPrepareQueue()})}}enqueueChunkTasks(e){for(const t of e)this.queue.push(t);this._sortQueue(),C.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let t=0,s=0;for(const n of e)n===D?(this.queue.push(D),s++):(this.queue.push(n),t++);C.info(`[DownloadQueue] Ordered queue: ${t} tasks, ${s} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,t)=>t._priority-e._priority)}prioritize(e,t){const s=`${e}/${t}`,n=this.active.get(s);if(!n)return C.info("[DownloadQueue] Not found:",s),!1;let a=0;for(const i of this.queue)i._parentFile===n&&i._priority<A.high&&(i._priority=A.high,a++);return this._sortQueue(),C.info("[DownloadQueue] Prioritized:",s,`(${a} tasks boosted)`),!0}prioritizeLayoutFiles(e,t=A.high){var a,i;const s=new Set(e.map(String));let n=0;for(const o of this.queue)s.has(String((a=o._parentFile)==null?void 0:a.fileInfo.id))&&o._priority<t&&(o._priority=t,n++);for(const o of this._activeTasks)s.has(String((i=o._parentFile)==null?void 0:i.fileInfo.id))&&o._priority<t&&(o._priority=t);this._sortQueue(),C.info("[DownloadQueue] Layout files prioritized:",s.size,"files,",n,"tasks boosted to",t)}urgentChunk(e,t,s){const n=`${e}/${t}`,a=this.active.get(n);if(!a)return C.info("[DownloadQueue] urgentChunk: file not active:",n,"chunk",s),!1;if(this._activeTasks.some(l=>l._parentFile===a&&l.chunkIndex===s&&l.state==="downloading")){const l=this._activeTasks.find(d=>d._parentFile===a&&d.chunkIndex===s);return l&&l._priority<A.urgent?(l._priority=A.urgent,C.info(`[DownloadQueue] URGENT: ${n} chunk ${s} (already in-flight, limiting slots)`),!0):(C.info("[DownloadQueue] urgentChunk: already urgent:",n,"chunk",s),!1)}const o=this.queue.findIndex(l=>l!==D&&l._parentFile===a&&l.chunkIndex===s);if(o===-1)return C.info("[DownloadQueue] urgentChunk: chunk not in queue:",n,"chunk",s),!1;const c=this.queue.splice(o,1)[0];return c._priority=A.urgent,this.queue.unshift(c),C.info(`[DownloadQueue] URGENT: ${n} chunk ${s} (moved to front)`),this.processQueue(),!0}processQueue(){var n;if(this.paused)return;const e=this.queue.some(a=>a!==D&&a._priority>=A.urgent)||((n=this._activeTasks)==null?void 0:n.some(a=>a._priority>=A.urgent&&a.state==="downloading")),t=e?De:this.concurrency,s=e?A.urgent:0;for(;this.running<t&&this.queue.length>0;){const a=this.queue[0];if(a===D){if(this.running>0)break;this.queue.shift();continue}if(a._priority<s||!this._canStartTask(a)){let i=!1;for(let o=1;o<this.queue.length&&this.queue[o]!==D;o++){const c=this.queue[o];if(c._priority>=s&&this._canStartTask(c)){this.queue.splice(o,1),this._startTask(c),i=!0;break}}if(!i)break;continue}this.queue.shift(),this._startTask(a)}this.queue.length===0&&this.running===0&&C.info("[DownloadQueue] All downloads complete")}_canStartTask(e){return e._parentFile._runningCount<this.maxChunksPerFile}_startTask(e){this.running++,e._parentFile._runningCount++,this._activeTasks.push(e);const t=`${e.fileInfo.type}/${e.fileInfo.id}`,s=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";C.info(`[DownloadQueue] Starting: ${t}${s} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(n=>n!==e),C.info(`[DownloadQueue] Fetched: ${t}${s} (${this.running} active, ${this.queue.length} pending)`),this.processQueue(),e._parentFile.onTaskComplete(e))).catch(n=>{this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(a=>a!==e),this.processQueue(),e._parentFile.onTaskFailed(e,n)})}awaitAllPrepared(){return new Promise(e=>{const t=()=>{this._preparingCount===0&&this._prepareQueue.length===0?e():setTimeout(t,50)};t()})}removeCompleted(e){const t=this.active.get(e);t&&(t.state==="complete"||t.state==="failed")&&(this.queue=this.queue.filter(s=>s===D||s._parentFile!==t),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){const e={};for(const[t,s]of this.active.entries())e[t]={downloaded:s.downloadedBytes,total:s.totalBytes,percent:s.totalBytes>0?(s.downloadedBytes/s.totalBytes*100).toFixed(1):0,state:s.state};return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0}}function Y(r,e){const t=new Set,s=r.matchAll(/<media[^>]+fileId="(\d+)"/g);for(const i of s)t.add(i[1]);const n=r.matchAll(/<media\s+([^>]+)>/g);for(const i of n){const o=i[1];if(!o.includes("fileId=")){const c=o.match(/\bid="(\d+)"/);c&&t.add(c[1])}}const a=r.matchAll(/<layout[^>]+background="(\d+)"/g);for(const i of a)t.add(i[1]);return e&&e.debug(`extractMediaIdsFromXlf: found ${t.size} IDs: ${[...t].join(", ")} (XLF ${r.length} bytes)`),t}const le={js:"application/javascript",css:"text/css",otf:"font/otf",ttf:"font/ttf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",svg:"image/svg+xml"};class Pe{constructor(e,t,s,n){this.downloadManager=e,this.cacheManager=t,this.blobCache=s,this.config={cacheName:"xibo-media-v1",staticCache:"xibo-static-v1",...n},this.log=new N("SW Message"),this.pendingChunkStorage=new Map}async handleMessage(e){const{type:t,data:s}=e.data;switch(t==="GET_DOWNLOAD_PROGRESS"?this.log.debug("Received:",t):this.log.info("Received:",t),t){case"PING":return this.log.info("PING received, broadcasting SW_READY"),(await self.clients.matchAll()).forEach(a=>{a.postMessage({type:"SW_READY"})}),{success:!0};case"DOWNLOAD_FILES":return await this.handleDownloadFiles(s);case"PRIORITIZE_DOWNLOAD":return this.handlePrioritizeDownload(s.fileType,s.fileId);case"CLEAR_CACHE":return await this.handleClearCache();case"GET_DOWNLOAD_PROGRESS":return await this.handleGetProgress();case"DELETE_FILES":return await this.handleDeleteFiles(s.files);case"PREWARM_VIDEO_CHUNKS":return await this.handlePrewarmVideoChunks(s.mediaIds);case"PRIORITIZE_LAYOUT_FILES":return this.downloadManager.prioritizeLayoutFiles(s.mediaIds),{success:!0};case"URGENT_CHUNK":return this.handleUrgentChunk(s.fileType,s.fileId,s.chunkIndex);case"GET_ALL_FILES":return await this.handleGetAllFiles();default:return this.log.warn("Unknown message type:",t),{success:!1,error:"Unknown message type"}}}async handleDeleteFiles(e){if(!e||!Array.isArray(e))return{success:!1,error:"No files provided"};let t=0;for(const s of e){const n=`${b}/cache/${s.type}/${s.id}`;await this.cacheManager.delete(n)?(this.log.info("Purged:",n),t++):this.log.debug("Not cached (skip purge):",n)}return this.log.info(`Purge complete: ${t}/${e.length} files deleted`),{success:!0,deleted:t,total:e.length}}async handlePrewarmVideoChunks(e){if(!e||!Array.isArray(e)||e.length===0)return{success:!1,error:"No mediaIds provided"};let t=0;for(const s of e){const n=`${b}/cache/media/${s}`,a=await this.cacheManager.getMetadata(n);if(a!=null&&a.chunked){const i=a.numChunks-1,o=[0];i>0&&o.push(i);for(const c of o){const l=`${n}/chunk-${c}`;await this.blobCache.get(l,async()=>{const d=await this.cacheManager.getChunk(n,c);return d?await d.blob():new Blob})}this.log.info(`Pre-warmed ${o.length} chunks for media ${s} (${a.numChunks} total)`),t++}else{const i=await this.cacheManager.get(n);i&&(await this.blobCache.get(n,async()=>await i.clone().blob()),this.log.info(`Pre-warmed whole file for media ${s}`),t++)}}return{success:!0,warmed:t,total:e.length}}handlePrioritizeDownload(e,t){this.log.info("Prioritize request:",`${e}/${t}`);const s=this.downloadManager.queue.prioritize(e,t);return this.downloadManager.queue.processQueue(),{success:!0,found:s}}handleUrgentChunk(e,t,s){return this.log.info("Urgent chunk request:",`${e}/${t}`,"chunk",s),{success:!0,acted:this.downloadManager.queue.urgentChunk(e,t,s)}}async handleDownloadFiles({layoutOrder:e,files:t,layoutDependants:s}){const n=this.downloadManager,a=n.queue;let i=0;const o=[],c=new Map,l=[],d=new Map;for(const u of t)u.type==="layout"?c.set(parseInt(u.id),u):u.type==="resource"||u.code==="fonts.css"||u.path&&(u.path.includes("bundle.min")||u.path.includes("fonts"))?l.push(u):d.set(String(u.id),u);this.log.info(`Download: ${e.length} layouts, ${d.size} media, ${l.length} resources`);const f=new Map,h=[];for(const u of e){const m=c.get(u);m!=null&&m.path&&h.push((async()=>{const y=`${b}/cache/layout/${u}`,$=await this.cacheManager.get(y);let _;if($)_=await $.clone().text();else{const T=await fetch(G(m.path));if(!T.ok){this.log.warn(`XLF fetch failed: ${u} (${T.status})`);return}const L=await T.blob();await this.cacheManager.put(y,L,"text/xml"),this.log.info(`Fetched + cached XLF ${u} (${L.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(u),fileType:"layout",size:L.size})),_=await L.text()}f.set(u,Y(_,this.log))})())}for(const[u,m]of c)e.includes(u)||h.push((async()=>{const y=`${b}/cache/layout/${u}`,$=await this.cacheManager.get(y);if(!$&&m.path){const _=await fetch(G(m.path));if(_.ok){const T=await _.blob();await this.cacheManager.put(y,T,"text/xml"),this.log.info(`Fetched + cached XLF ${u} (non-scheduled, ${T.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(u),fileType:"layout",size:T.size}));const S=await T.text();f.set(u,Y(S,this.log))}}else if($){const _=await $.clone().text();f.set(u,Y(_,this.log))}})());await Promise.allSettled(h),this.log.info(`Parsed ${f.size} XLFs`);const g=new X(a);for(const u of l)await this._enqueueFile(n,g,u,o)&&i++;const x=await g.build();x.length>0&&(x.push(D),a.enqueueOrderedTasks(x));const k=new Set,E=[...f.keys()].filter(u=>!e.includes(u)),p=new Map;for(const[u,m]of d)m.saveAs&&p.set(m.saveAs,u);const I=new Map;if(s)for(const[u,m]of Object.entries(s))I.set(parseInt(u,10),m);for(const u of e){const m=f.get(u);if(!m)continue;const y=new Set(m);for(const S of E){const R=f.get(S);if(R)for(const we of R)y.add(we)}const $=I.get(u)||[];for(const S of $){const R=p.get(S);R&&y.add(R)}const _=[];for(const S of y){if(k.has(S))continue;const R=d.get(S);R&&(_.push(R),k.add(S))}if(_.length===0)continue;this.log.info(`Layout ${u}: ${_.length} media`),_.sort((S,R)=>(S.size||0)-(R.size||0));const T=new X(a);for(const S of _)await this._enqueueFile(n,T,S,o)&&i++;const L=await T.build();L.length>0&&(L.push(D),a.enqueueOrderedTasks(L))}const P=[...d.keys()].filter(u=>!k.has(u));if(P.length>0){this.log.info(`${P.length} media not in any XLF: ${P.join(", ")}`);const u=new X(a);for(const y of P){const $=d.get(y);$&&await this._enqueueFile(n,u,$,o)&&i++}const m=await u.build();m.length>0&&a.enqueueOrderedTasks(m)}const q=a.running,w=a.queue.length;return this.log.info("Downloads active:",q,", queued:",w),{success:!0,enqueuedCount:i,activeCount:q,queuedCount:w}}async _enqueueFile(e,t,s,n){if(!s.path||s.path==="null"||s.path==="undefined")return this.log.debug("Skipping file with no path:",s.id),!1;const a=`${b}/cache/${s.type}/${s.id}`,i=await this.cacheManager.fileExists(a);if(i.exists)if(i.chunked&&i.metadata&&!i.metadata.complete){const{numChunks:d}=i.metadata,f=new Set;for(let h=0;h<d;h++)await this.cacheManager.getChunk(a,h)&&f.add(h);if(f.size===d)return this.log.info("All chunks present but metadata incomplete, marking complete:",a),i.metadata.complete=!0,await this.cacheManager.updateMetadata(a,i.metadata),!1;this.log.info(`Incomplete chunked download: ${f.size}/${d} chunks cached, resuming:`,a),s.skipChunks=f}else return this.log.debug("File already cached:",a,i.chunked?"(chunked)":"(whole file)"),await this.ensureStaticCacheEntry(s),!1;const o=`${s.type}/${s.id}`;if(e.getTask(o))return this.log.debug("File already downloading:",o,"- skipping duplicate"),!1;const l=t.addFile(s);if(l.state==="pending"){const d=this.cacheFileAfterDownload(l,s);return n.push(d),!0}return!1}async cacheFileAfterDownload(e,t){try{const s=`${b}/cache/${t.type}/${t.id}`,n=t.type==="layout"?"text/xml":t.type==="widget"?"text/html":"application/octet-stream",a=parseInt(t.size)||0;if(a>this.config.chunkStorageThreshold)return await this._progressiveCacheFile(e,t,s,n,a);const i=await e.wait();return await this.cacheManager.put(s,i,n),this.log.info("Cached after download:",s,`(${i.size} bytes)`),(await self.clients.matchAll()).forEach(c=>{c.postMessage({type:"FILE_CACHED",fileId:t.id,fileType:t.type,size:i.size})}),this._cacheStaticResource(t,i),this.downloadManager.queue.removeCompleted(`${t.type}/${t.id}`),i}catch(s){throw this.log.error("Failed to cache after download:",t.id,s),this.downloadManager.queue.removeCompleted(`${t.type}/${t.id}`),s}}async _progressiveCacheFile(e,t,s,n,a){const{chunkSize:i,cacheName:o}=this.config,c=await caches.open(o);let l=0,d=!1;const f=Math.ceil(a/i);this.log.info(`Progressive download: ${s} (${M(a)}, ~${f} chunks)`);const h={totalSize:a,chunkSize:i,numChunks:f,contentType:n,chunked:!0,complete:!1,createdAt:Date.now()};await c.put(`${s}/metadata`,new Response(JSON.stringify(h),{headers:{"Content-Type":"application/json"}})),this.cacheManager.metadataCache.set(s,h),this.log.info("Metadata stored, ready for progressive streaming:",s),e.onChunkDownloaded=async(k,E,p)=>{const I=new Response(E,{headers:{"Content-Type":n,"Content-Length":E.size,"X-Chunk-Index":k,"X-Total-Chunks":p}});if(await c.put(`${s}/chunk-${k}`,I),l++,(l%2===0||l===p)&&this.log.info(`Progressive: chunk ${l}/${p} cached for ${t.id}`),!d&&(k===0||k===p-1)){const P=k===0||await this.cacheManager.getChunk(s,0),q=k===p-1||await this.cacheManager.getChunk(s,p-1);P&&q&&(d=!0,(await self.clients.matchAll()).forEach(u=>{u.postMessage({type:"FILE_CACHED",fileId:t.id,fileType:t.type,size:a,progressive:!0,chunksReady:l,totalChunks:p})}),this.log.info("Chunk 0 + last chunk cached — client notified, early playback ready:",s))}p!==f&&(h.numChunks=p,await c.put(`${s}/metadata`,new Response(JSON.stringify(h),{headers:{"Content-Type":"application/json"}})))};const g=await e.wait();return l===0?(this.log.warn("Progressive callback never fired, falling back to putChunked:",s),g.size>0?await this.cacheManager.putChunked(s,g,n):await this.cacheManager.put(s,g,n),(await self.clients.matchAll()).forEach(E=>{E.postMessage({type:"FILE_CACHED",fileId:t.id,fileType:t.type,size:g.size||a})}),this.downloadManager.queue.removeCompleted(`${t.type}/${t.id}`),g):e._urlExpired?(this.log.warn(`URL expired mid-download, partial cache: ${s} (${l}/${f} chunks stored)`),this.downloadManager.queue.removeCompleted(`${t.type}/${t.id}`),new Blob([],{type:n})):(this.log.info(`Progressive download complete: ${s} (${l} chunks stored)`),h.complete=!0,await this.cacheManager.updateMetadata(s,h),(await self.clients.matchAll()).forEach(k=>{k.postMessage({type:"FILE_CACHED",fileId:t.id,fileType:t.type,size:a,complete:!0})}),this.pendingChunkStorage.delete(s),this.downloadManager.queue.removeCompleted(`${t.type}/${t.id}`),new Blob([],{type:n}))}_cacheStaticResource(e,t){const s=e.path?(()=>{try{return new URL(e.path).searchParams.get("file")}catch{return null}})():null;s&&(s.endsWith(".js")||s.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(s))&&(async()=>{try{const n=await caches.open(this.config.staticCache),a=`${b}/cache/static/${s}`,i=s.split(".").pop().toLowerCase(),o=le[i]||"application/octet-stream";await Promise.all([n.put(a,new Response(t.slice(0,t.size,t.type),{headers:{"Content-Type":o}})),this.cacheManager.put(a,t.slice(0,t.size,t.type),o)]),this.log.info("Also cached as static resource:",s,`(${o})`)}catch(n){this.log.warn("Failed to cache static resource:",s,n)}})()}async ensureStaticCacheEntry(e){const t=e.path?(()=>{try{return new URL(e.path).searchParams.get("file")}catch{return null}})():null;if(!t||!(t.endsWith(".js")||t.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(t)))return;const s=await caches.open(this.config.staticCache),n=`${b}/cache/static/${t}`;if(await s.match(n))return;const i=`${b}/cache/${e.type}/${e.id}`,o=await this.cacheManager.get(i);if(!o)return;const c=await o.blob(),l=t.split(".").pop().toLowerCase(),d=le[l]||"application/octet-stream",f=`${b}/cache/static/${t}`;await Promise.all([s.put(n,new Response(c.slice(0,c.size,c.type),{headers:{"Content-Type":d}})),this.cacheManager.put(f,c.slice(0,c.size,c.type),d)]),this.log.info("Backfilled static cache for:",t,`(${d}, ${c.size} bytes)`)}async handleGetAllFiles(){return{success:!0,files:await this.cacheManager.getAllFiles()}}async handleClearCache(){return this.log.info("Clearing cache"),await this.cacheManager.clear(),{success:!0}}async handleGetProgress(){return{success:!0,progress:this.downloadManager.getProgress()}}}const B="2026-02-23T22:39:17.452Z",Z="xibo-media-v1",H="xibo-static-v1",qe=[b+"/",b+"/index.html",b+"/setup.html"],v=new N("SW"),W=ke(v),ee=W.chunkSize,Be=W.threshold,Ne=W.blobCacheSize,ze=W.concurrency;v.info("Loading modular Service Worker:",B);const ge=new me({concurrency:ze,chunkSize:ee,chunksPerFile:2}),te=new be({cacheName:Z,chunkSize:ee}),pe=new $e(Ne),Oe=new _e(ge,te,pe,{staticCache:H}),Ue=new Pe(ge,te,pe,{cacheName:Z,staticCache:H,chunkSize:ee,chunkStorageThreshold:Be});async function Ke(r){const e=new URL(r.request.url),t=e.pathname.replace(b+"/ic",""),s=r.request.method;v.info("Interactive Control request:",s,t);let n=null;if(s==="POST"||s==="PUT")try{n=await r.request.text()}catch{}const a=await self.clients.matchAll({type:"window"});if(a.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const i=a[0];try{const o=await new Promise((c,l)=>{const d=new MessageChannel,f=setTimeout(()=>l(new Error("IC timeout")),5e3);d.port1.onmessage=h=>{clearTimeout(f),c(h.data)},i.postMessage({type:"INTERACTIVE_CONTROL",method:s,path:t,search:e.search,body:n},[d.port2])});return new Response(o.body||"",{status:o.status||200,headers:{"Content-Type":o.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(o){return v.error("IC handler error:",o),new Response(JSON.stringify({error:o.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",r=>{v.info("Installing... Version:",B),r.waitUntil(Promise.all([te.init(),caches.open(H).then(e=>(v.info("Caching static files"),e.addAll(qe)))]).then(async()=>{if(v.info("Cache initialized"),self.registration.active)try{const t=await(await caches.open("xibo-sw-version")).match("version");if(t){const s=await t.text();if(s===B){v.info("Same version already active, skipping activation to preserve streams");return}v.info("Version changed:",s,"→",B)}}catch{}return v.info("New version, activating immediately"),self.skipWaiting()}))});self.addEventListener("activate",r=>{v.info("Activating... Version:",B,"| @xiboplayer/cache:",ye),r.waitUntil(caches.keys().then(e=>Promise.all(e.filter(t=>t.startsWith("xibo-")&&t!==Z&&t!==H&&t!=="xibo-sw-version").map(t=>(v.info("Deleting old cache:",t),caches.delete(t))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(B)),v.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{v.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(t=>{t.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",r=>{const e=new URL(r.request.url);if(e.pathname.startsWith(b+"/cache/")||e.pathname.startsWith(b+"/ic/")||e.pathname.startsWith("/player/")&&(e.pathname.endsWith(".html")||e.pathname==="/player/")||e.pathname.includes("xmds.php")&&e.searchParams.has("file")&&r.request.method==="GET"){if(e.pathname.startsWith(b+"/ic/")){r.respondWith(Ke(r));return}r.respondWith(Oe.handleRequest(r))}});self.addEventListener("message",r=>{r.waitUntil(Ue.handleMessage(r).then(e=>{var t;(t=r.ports[0])==null||t.postMessage(e)}))});v.info("Modular Service Worker ready");
|
|
1
|
+
import{r as U,L as O,B as H,D as Z}from"./assets/widget-html-Cb84FvUB.js";import{VERSION as Q}from"./assets/index-pcbcUHVR.js";import"./assets/cms-api-Cqh1b8je.js";const y=(()=>{var h;return typeof self<"u"&&((h=self.registration)!=null&&h.scope)?new URL(self.registration.scope).pathname.replace(/\/$/,""):"/player/pwa"})();function x(h,t=1){if(h===0)return"0 Bytes";if(h<1024)return`${h} Bytes`;const e=h/1024;if(e<1024)return`${e.toFixed(t)} KB`;const a=e/1024;return a<1024?`${a.toFixed(t)} MB`:`${(a/1024).toFixed(t)} GB`}function G(h,t){const e=h.replace(/bytes=/,"").split("-"),a=parseInt(e[0],10),s=e[1]?parseInt(e[1],10):t-1;return{start:a,end:s}}function K(h,t,e){const a=Math.floor(h/e),s=Math.floor(t/e);return{startChunk:a,endChunk:s,count:s-a+1}}function j(h,t,e,a,s){if(h.length===1){const o=t%a,d=e-t+1;return h[0].slice(o,o+d)}const i=[],n=t%a,l=e%a;i.push(h[0].slice(n));for(let o=1;o<h.length-1;o++)i.push(h[o]);return h.length>1&&i.push(h[h.length-1].slice(0,l+1)),new Blob(i,{type:s})}class D{constructor(t){this.name=t,this.level=typeof self<"u"&&self.swLogLevel||"INFO"}debug(...t){this.level==="DEBUG"&&console.log(`[${this.name}] DEBUG:`,...t)}info(...t){(this.level==="DEBUG"||this.level==="INFO")&&console.log(`[${this.name}]`,...t)}warn(...t){console.warn(`[${this.name}]`,...t)}error(...t){console.error(`[${this.name}]`,...t)}}function ee(h){h||(h=new D("ChunkConfig"));const t=typeof navigator<"u"&&navigator.deviceMemory||null;let e=4;if(t)e=t,h.info("Detected device memory:",t,"GB");else if(typeof navigator<"u"){const l=navigator.userAgent.toLowerCase();l.includes("raspberry pi")||l.includes("armv6")?(e=.5,h.info("Detected Pi Zero (512 MB RAM estimated)")):l.includes("armv7")?(e=1,h.info("Detected ARM device (1 GB RAM estimated)")):h.info("Using default RAM estimate:",e,"GB")}let a,s,i,n;return e<=.5?(a=10*1024*1024,s=25,i=25*1024*1024,n=1,h.info("Low-memory config: 10 MB chunks, 25 MB cache, 1 concurrent download")):e<=1?(a=20*1024*1024,s=50,i=50*1024*1024,n=2,h.info("1GB-RAM config: 20 MB chunks, 50 MB cache, 2 concurrent downloads")):e<=2?(a=30*1024*1024,s=100,i=75*1024*1024,n=2,h.info("2GB-RAM config: 30 MB chunks, 100 MB cache, 2 concurrent downloads")):e<=4?(a=50*1024*1024,s=200,i=100*1024*1024,n=4,h.info("4GB-RAM config: 50 MB chunks, 200 MB cache, 4 concurrent downloads")):(a=100*1024*1024,s=500,i=200*1024*1024,n=6,h.info("High-RAM config: 100 MB chunks, 500 MB cache, 6 concurrent downloads")),{chunkSize:a,blobCacheSize:s,threshold:i,concurrency:n}}class te{constructor({cacheName:t="xibo-media-v1",chunkSize:e}={}){this.cache=null,this.cacheName=t,this.chunkSize=e,this.log=new D("Cache"),this.metadataCache=new Map}async init(){this.cache=await caches.open(this.cacheName)}async get(t){return this.cache||await this.init(),await this.cache.match(t,{ignoreSearch:!0,ignoreVary:!0})}async put(t,e,a){this.cache||await this.init();const s=new Response(e,{headers:{"Content-Type":a,"Content-Length":e.size,"Access-Control-Allow-Origin":"*","Accept-Ranges":"bytes"}});await this.cache.put(t,s)}async delete(t){this.cache||await this.init();const e=this.metadataCache.get(t);if(this.metadataCache.delete(t),e){const a=[this.cache.delete(`${t}/metadata`)];for(let s=0;s<e.numChunks;s++)a.push(this.cache.delete(`${t}/chunk-${s}`));return await Promise.all(a),!0}return await this.cache.delete(t)}async clear(){this.cache||await this.init();const t=await this.cache.keys();await Promise.all(t.map(e=>this.cache.delete(e))),this.metadataCache.clear(),this.log.info("Cleared",t.length,"cached files")}async fileExists(t){this.cache||await this.init();const e=this.metadataCache.get(t);if(e)return{exists:!0,chunked:!0,metadata:e};if(await this.get(t))return{exists:!0,chunked:!1,metadata:null};const s=await this.getMetadata(t);return s&&s.chunked?(this.metadataCache.set(t,s),{exists:!0,chunked:!0,metadata:s}):{exists:!1,chunked:!1,metadata:null}}async getFileSize(t){const e=await this.fileExists(t);if(!e.exists)return null;if(e.chunked)return e.metadata.totalSize;const a=await this.get(t),s=a==null?void 0:a.headers.get("Content-Length");return s?parseInt(s):null}async putChunked(t,e,a){this.cache||await this.init();const s=this.chunkSize,i=e.size,n=Math.ceil(i/s);this.log.info(`Storing as ${n} chunks: ${t} (${x(i)})`);const l={totalSize:i,chunkSize:s,numChunks:n,contentType:a,chunked:!0,complete:!1,createdAt:Date.now()},o=new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}});await this.cache.put(`${t}/metadata`,o),this.metadataCache.set(t,l);for(let d=0;d<n;d++){const u=d*s,f=Math.min(u+s,i),c=e.slice(u,f),$=new Response(c,{headers:{"Content-Type":a,"Content-Length":c.size,"X-Chunk-Index":d,"X-Total-Chunks":n}});await this.cache.put(`${t}/chunk-${d}`,$),((d+1)%5===0||d===n-1)&&this.log.info(`Stored chunk ${d+1}/${n} (${x(c.size)})`)}l.complete=!0,await this.cache.put(`${t}/metadata`,new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(t,l),this.log.info(`Chunked storage complete: ${t}`)}async getMetadata(t){const e=this.metadataCache.get(t);if(e)return e;this.cache||await this.init();const a=await this.cache.match(`${t}/metadata`);if(!a)return null;const s=await a.text(),i=JSON.parse(s);return this.metadataCache.set(t,i),i}async updateMetadata(t,e){this.cache||await this.init(),await this.cache.put(`${t}/metadata`,new Response(JSON.stringify(e),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(t,e)}async getAllFiles(){this.cache||await this.init();const t=await this.cache.keys(),e=[],a=new Set;for(const s of t){const n=new URL(s.url).pathname;if(n.includes("/chunk-")||n.endsWith("/metadata")){const o=n.replace(/\/(chunk-\d+|metadata)$/,"");if(a.has(o))continue;a.add(o);const d=await this.getMetadata(o),u=o.match(/\/cache\/(media|layout|widget)\/(.+)/);u&&e.push({id:u[2],type:u[1],size:(d==null?void 0:d.totalSize)||0,cachedAt:(d==null?void 0:d.createdAt)||0});continue}if(n.includes("/cache/static/")||a.has(n))continue;a.add(n);const l=n.match(/\/cache\/(media|layout|widget)\/(.+)/);if(l){const o=await this.cache.match(s);e.push({id:l[2],type:l[1],size:parseInt((o==null?void 0:o.headers.get("Content-Length"))||"0"),cachedAt:0})}}return e}async isChunked(t){const e=await this.getMetadata(t);return(e==null?void 0:e.chunked)===!0}async getChunk(t,e){return this.cache||await this.init(),await this.cache.match(`${t}/chunk-${e}`)}}class ae{constructor(t=200){this.cache=new Map,this.maxBytes=t*1024*1024,this.currentBytes=0,this.log=new D("BlobCache")}has(t){return this.cache.has(t)}async get(t,e){if(this.cache.has(t)){const s=this.cache.get(t);return s.lastAccess=Date.now(),this.log.debug(`HIT: ${t} (${x(s.size)})`),s.blob}this.log.debug(`MISS: ${t} - loading from Cache API`);const a=await e();for(;this.currentBytes+a.size>this.maxBytes&&this.cache.size>0;)this.evictLRU();if(this.currentBytes+a.size<=this.maxBytes){this.cache.set(t,{blob:a,lastAccess:Date.now(),size:a.size}),this.currentBytes+=a.size;const s=(this.currentBytes/this.maxBytes*100).toFixed(1);this.log.debug(`CACHED: ${t} (${x(a.size)}) - utilization: ${s}%`)}else this.log.debug(`Skipping memory cache (too large): ${t} (${x(a.size)} > ${x(this.maxBytes)})`);return a}evictLRU(){let t=null,e=null;for(const[a,s]of this.cache)(!t||s.lastAccess<t.lastAccess)&&(t=s,e=a);e&&(this.currentBytes-=t.size,this.cache.delete(e),this.log.debug(`EVICTED LRU: ${e} (${x(t.size)})`))}clear(){this.cache.clear(),this.currentBytes=0,this.log.info("Cleared all cached blobs")}getStats(){return{entries:this.cache.size,bytes:this.currentBytes,maxBytes:this.maxBytes,utilization:(this.currentBytes/this.maxBytes*100).toFixed(1)+"%"}}}class se{constructor(t,e,a,{staticCache:s="xibo-static-v1"}={}){this.downloadManager=t,this.cacheManager=e,this.blobCache=a,this.staticCache=s,this.pendingFetches=new Map,this.log=new D("SW"),this.pendingChunkLoads=new Map}async routeFileRequest(t,e,a){const s=await this.cacheManager.fileExists(t);if(!s.exists)return{found:!1,handler:null,data:null};if(s.chunked){const i={metadata:s.metadata,cacheKey:t};return e==="HEAD"?{found:!0,handler:"head-chunked",data:i}:a?{found:!0,handler:"range-chunked",data:{...i,rangeHeader:a}}:{found:!0,handler:"full-chunked",data:i}}else{const n={cached:await this.cacheManager.get(t),cacheKey:t};return e==="HEAD"?{found:!0,handler:"head-whole",data:n}:a?{found:!0,handler:"range-whole",data:{...n,rangeHeader:a}}:{found:!0,handler:"full-whole",data:n}}}async handleRequest(t){var f;const e=new URL(t.request.url);if(this.log.info("handleRequest called for:",e.href),this.log.info("pathname:",e.pathname),e.pathname===y+"/"||e.pathname===y+"/index.html"||e.pathname===y+"/setup.html"){const $=await(await caches.open(this.staticCache)).match(t.request);return $?(this.log.info("Serving static file from cache:",e.pathname),$):(this.log.info("Fetching static file from network:",e.pathname),fetch(t.request))}if((e.pathname.includes("xmds.php")||e.pathname.includes("pwa/file"))&&(e.searchParams.get("fileType")==="bundle"||e.searchParams.get("fileType")==="fontCss"||e.searchParams.get("fileType")==="font")){const c=e.searchParams.get("file"),$=`${y}/cache/static/${c}`,M=await caches.open(this.staticCache),C=await M.match($);if(C)return this.log.info("Serving widget resource from cache:",c),C.clone();if(this.pendingFetches.has(c))return this.log.info("Deduplicating widget resource fetch:",c),(await this.pendingFetches.get(c)).clone();this.log.info("Fetching widget resource from CMS:",c);const T=(async()=>{try{const g=await fetch(t.request);if(g.ok){this.log.info("Caching widget resource:",c,`(${g.headers.get("Content-Type")})`);const v=g.clone();return await M.put($,v),g}else return this.log.warn("Widget resource not available (",g.status,"):",c,"- NOT caching"),g}catch(g){return this.log.error("Failed to fetch widget resource:",c,g),new Response("Failed to fetch widget resource",{status:502,statusText:"Bad Gateway",headers:{"Content-Type":"text/plain"}})}})();this.pendingFetches.set(c,T);try{return(await T).clone()}finally{this.pendingFetches.delete(c)}}if((e.pathname.includes("xmds.php")||e.pathname.includes("pwa/file"))&&e.searchParams.has("file")){const c=e.searchParams.get("file"),$=c.split(".")[0],M=e.searchParams.get("type"),C=M==="L"?"layout":"media";this.log.info("XMDS request:",c,"type:",M,"→",y+"/cache/"+C+"/"+$);const T=`${y}/cache/${C}/${$}`,g=await this.cacheManager.get(T);return g?new Response(g.clone().body,{headers:{"Content-Type":g.headers.get("Content-Type")||"video/mp4","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000","Accept-Ranges":"bytes"}}):(this.log.info("XMDS file not cached, passing through:",c),fetch(t.request))}if(e.pathname.startsWith(y+"/cache/static/")){const c=e.pathname.split("/").pop();this.log.info("Static resource request:",c);const M=await(await caches.open(this.staticCache)).match(`${y}/cache/static/${c}`);if(M)return this.log.info("Serving static resource from static cache:",c),M.clone();const C=await this.cacheManager.get(e.pathname);return C?(this.log.info("Serving static resource from media cache:",c),new Response(C.clone().body,{headers:{"Content-Type":C.headers.get("Content-Type")||"application/octet-stream","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})):(this.log.warn("Static resource not cached:",c),new Response("Resource not cached",{status:404}))}if(!e.pathname.startsWith(y+"/cache/"))return this.log.info("NOT a cache request, returning null:",e.pathname),null;if(this.log.info("IS a cache request, proceeding...",e.pathname),e.pathname.startsWith(y+"/cache/widget/")){this.log.info("Widget HTML request:",e.pathname);const c=await this.cacheManager.get(e.pathname);return c?new Response(c.clone().body,{headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}}):new Response("<!DOCTYPE html><html><body>Widget not found</body></html>",{status:404,headers:{"Content-Type":"text/html"}})}const a=e.pathname.replace(/\.json$/,""),s=t.request.method,i=t.request.headers.get("Range");this.log.debug("Request URL:",e.pathname),this.log.debug("Cache key:",a),i?this.log.info(s,a,`Range: ${i}`):this.log.info(s,a);const n=await this.routeFileRequest(a,s,i);if(n.found)switch(n.handler){case"head-whole":return this.handleHeadWhole((f=n.data.cached)==null?void 0:f.headers.get("Content-Length"));case"head-chunked":return this.handleHeadChunked(n.data.metadata,n.data.cacheKey);case"range-whole":return this.handleRangeRequest(n.data.cached,n.data.rangeHeader,n.data.cacheKey);case"range-chunked":return this.handleChunkedRangeRequest(n.data.cacheKey,n.data.rangeHeader,n.data.metadata);case"full-whole":return this.handleFullWhole(n.data.cached,n.data.cacheKey);case"full-chunked":return this.handleFullChunked(n.data.cacheKey,n.data.metadata);default:return this.log.error("Unknown handler:",n.handler),new Response("Internal error: unknown handler",{status:500})}const l=a.split("/"),o=l[l.length-2],d=l[l.length-1];let u=null;for(const[,c]of this.downloadManager.queue.active.entries())if(c.fileInfo.type===o&&String(c.fileInfo.id)===d){u=c;break}if(u){this.log.info("Download in progress, waiting:",a);try{await u.wait();const c=await this.routeFileRequest(a,s,i);if(c.found)switch(this.log.info("Download complete, serving via",c.handler),c.handler){case"full-whole":return this.handleFullWhole(c.data.cached,c.data.cacheKey);case"full-chunked":return this.handleFullChunked(c.data.cacheKey,c.data.metadata);default:return this.handleRequest(t)}}catch(c){return this.log.error("Download failed:",a,c),new Response("Download failed: "+c.message,{status:500})}}return this.log.info("Not found:",a),new Response("Not found",{status:404})}handleHeadWhole(t){return this.log.info("HEAD response: File exists (whole file)"),new Response(null,{status:200,headers:{"Content-Length":t?t.toString():"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleHeadChunked(t,e){return await this.cacheManager.getChunk(e,0)?(this.log.info("HEAD response: File exists (chunked)"),new Response(null,{status:200,headers:{"Content-Length":t.totalSize.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})):(this.log.info("HEAD response: Chunked file not yet playable (chunk 0 missing):",e),new Response(null,{status:404}))}handleFullWhole(t,e){const a=t.headers.get("Content-Length"),s=a?x(parseInt(a)):"unknown size";return this.log.info("Serving from cache:",e,`(${s})`),new Response(t.body,{headers:{"Content-Type":t.headers.get("Content-Type")||"application/octet-stream","Content-Length":a||"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})}async handleFullChunked(t,e){this.log.info("Chunked file GET without Range:",t,`- serving full file from ${e.numChunks} chunks`);const a=`bytes=0-${e.totalSize-1}`;return this.handleChunkedRangeRequest(t,a,e)}async handleRangeRequest(t,e,a){const s=await this.blobCache.get(a,async()=>await t.clone().blob()),i=s.size,{start:n,end:l}=G(e,i),o=s.slice(n,l+1);return this.log.debug(`Range: bytes ${n}-${l}/${i} (${x(o.size)} of ${x(i)})`),new Response(o,{status:206,statusText:"Partial Content",headers:{"Content-Type":t.headers.get("Content-Type")||"video/mp4","Content-Length":o.size.toString(),"Content-Range":`bytes ${n}-${l}/${i}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleChunkedRangeRequest(t,e,a){const{totalSize:s,chunkSize:i,numChunks:n,contentType:l}=a,{start:o,end:d}=G(e,s);let u=d;const f=e.replace(/bytes=/,"");if(f.indexOf("-")===f.length-1){const p=Math.floor(o/i),r=n-1;let w=!0;for(let m=p;m<=r;m++){const k=`${t}/chunk-${m}`;if(this.blobCache.has(k))continue;if(!await this.cacheManager.getChunk(t,m)){w=!1;break}}if(w)this.log.info(`All chunks cached from ${p} to ${r}, serving full range (bytes ${o}-${u}/${s})`);else{const m=Math.min((p+1)*i-1,s-1);m<u&&(u=m,this.log.info(`Progressive streaming: capping bytes=${o}- to chunk ${p} (bytes ${o}-${u}/${s})`))}}const{startChunk:$,endChunk:M,count:C}=K(o,u,i);this.log.debug(`Chunked range: bytes ${o}-${u}/${s} (chunks ${$}-${M}, ${C} chunks)`);const T=p=>{const r=`${t}/chunk-${p}`;return this.blobCache.get(r,()=>{if(this.pendingChunkLoads.has(r))return this.pendingChunkLoads.get(r);const w=(async()=>{let m=await this.cacheManager.getChunk(t,p);if(m)return await m.blob();this.log.info(`Chunk ${p}/${n} not yet available for ${t}, signalling urgent...`);{const k=t.split("/"),b=k[k.length-1],E=k[k.length-2];this.downloadManager.queue.urgentChunk(E,b,p)}for(let k=0;k<60;k++)if(await new Promise(b=>setTimeout(b,1e3)),m=await this.cacheManager.getChunk(t,p),m)return this.log.info(`Chunk ${p}/${n} arrived for ${t} after ${k+1}s`),await m.blob();throw new Error(`Chunk ${p} not available for ${t} after 60s`)})();return this.pendingChunkLoads.set(r,w),w.finally(()=>this.pendingChunkLoads.delete(r)),w})},g=[];let v=!0;for(let p=$;p<=M;p++){const r=await this.cacheManager.getChunk(t,p);if(r){const w=`${t}/chunk-${p}`,m=await this.blobCache.get(w,async()=>await r.blob());g.push(m)}else{v=!1;break}}if(v&&g.length===C){const p=j(g,o,u,i);return this.log.debug(`Serving chunked range: ${x(p.size)} from ${C} chunk(s)`),new Response(p,{status:206,statusText:"Partial Content",headers:{"Content-Type":l,"Content-Length":p.size.toString(),"Content-Range":`bytes ${o}-${u}/${s}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}this.log.info(`Streaming response for ${t} bytes ${o}-${u} (waiting for chunks)`);const L=u-o+1,z=new ReadableStream({async start(p){try{const r=[];for(let k=$;k<=M;k++){const b=await T(k);r.push(b)}const m=await j(r,o,u,i).arrayBuffer();p.enqueue(new Uint8Array(m)),p.close()}catch(r){this.log.error(`Stream error for ${t}: ${r.message}`),p.error(r)}}});return new Response(z,{status:206,statusText:"Partial Content",headers:{"Content-Type":l,"Content-Length":L.toString(),"Content-Range":`bytes ${o}-${u}/${s}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}}function I(h,t){const e=new Set,a=h.matchAll(/<media[^>]+fileId="(\d+)"/g);for(const n of a)e.add(n[1]);const s=h.matchAll(/<media\s+([^>]+)>/g);for(const n of s){const l=n[1];if(!l.includes("fileId=")){const o=l.match(/\bid="(\d+)"/);o&&e.add(o[1])}}const i=h.matchAll(/<layout[^>]+background="(\d+)"/g);for(const n of i)e.add(n[1]);return t&&t.debug(`extractMediaIdsFromXlf: found ${e.size} IDs: ${[...e].join(", ")} (XLF ${h.length} bytes)`),e}const X={js:"application/javascript",css:"text/css",otf:"font/otf",ttf:"font/ttf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",svg:"image/svg+xml"};class ne{constructor(t,e,a,s){this.downloadManager=t,this.cacheManager=e,this.blobCache=a,this.config={cacheName:"xibo-media-v1",staticCache:"xibo-static-v1",...s},this.log=new D("SW Message"),this.pendingChunkStorage=new Map}async handleMessage(t){const{type:e,data:a}=t.data;switch(e==="GET_DOWNLOAD_PROGRESS"?this.log.debug("Received:",e):this.log.info("Received:",e),e){case"PING":return this.log.info("PING received, broadcasting SW_READY"),(await self.clients.matchAll()).forEach(i=>{i.postMessage({type:"SW_READY"})}),{success:!0};case"DOWNLOAD_FILES":return await this.handleDownloadFiles(a);case"PRIORITIZE_DOWNLOAD":return this.handlePrioritizeDownload(a.fileType,a.fileId);case"CLEAR_CACHE":return await this.handleClearCache();case"GET_DOWNLOAD_PROGRESS":return await this.handleGetProgress();case"DELETE_FILES":return await this.handleDeleteFiles(a.files);case"PREWARM_VIDEO_CHUNKS":return await this.handlePrewarmVideoChunks(a.mediaIds);case"PRIORITIZE_LAYOUT_FILES":return this.downloadManager.prioritizeLayoutFiles(a.mediaIds),{success:!0};case"URGENT_CHUNK":return this.handleUrgentChunk(a.fileType,a.fileId,a.chunkIndex);case"GET_ALL_FILES":return await this.handleGetAllFiles();default:return this.log.warn("Unknown message type:",e),{success:!1,error:"Unknown message type"}}}async handleDeleteFiles(t){if(!t||!Array.isArray(t))return{success:!1,error:"No files provided"};let e=0;for(const a of t){const s=`${y}/cache/${a.type}/${a.id}`;await this.cacheManager.delete(s)?(this.log.info("Purged:",s),e++):this.log.debug("Not cached (skip purge):",s)}return this.log.info(`Purge complete: ${e}/${t.length} files deleted`),{success:!0,deleted:e,total:t.length}}async handlePrewarmVideoChunks(t){if(!t||!Array.isArray(t)||t.length===0)return{success:!1,error:"No mediaIds provided"};let e=0;for(const a of t){const s=`${y}/cache/media/${a}`,i=await this.cacheManager.getMetadata(s);if(i!=null&&i.chunked){const n=i.numChunks-1,l=[0];n>0&&l.push(n);for(const o of l){const d=`${s}/chunk-${o}`;await this.blobCache.get(d,async()=>{const u=await this.cacheManager.getChunk(s,o);return u?await u.blob():new Blob})}this.log.info(`Pre-warmed ${l.length} chunks for media ${a} (${i.numChunks} total)`),e++}else{const n=await this.cacheManager.get(s);n&&(await this.blobCache.get(s,async()=>await n.clone().blob()),this.log.info(`Pre-warmed whole file for media ${a}`),e++)}}return{success:!0,warmed:e,total:t.length}}handlePrioritizeDownload(t,e){this.log.info("Prioritize request:",`${t}/${e}`);const a=this.downloadManager.queue.prioritize(t,e);return this.downloadManager.queue.processQueue(),{success:!0,found:a}}handleUrgentChunk(t,e,a){return this.log.info("Urgent chunk request:",`${t}/${e}`,"chunk",a),{success:!0,acted:this.downloadManager.queue.urgentChunk(t,e,a)}}async handleDownloadFiles({layoutOrder:t,files:e,layoutDependants:a}){const s=this.downloadManager,i=s.queue;let n=0;const l=[],o=new Map,d=[],u=new Map;for(const r of e)r.type==="layout"?o.set(parseInt(r.id),r):r.type==="resource"||r.code==="fonts.css"||r.path&&(r.path.includes("bundle.min")||r.path.includes("fonts"))?d.push(r):u.set(String(r.id),r);this.log.info(`Download: ${t.length} layouts, ${u.size} media, ${d.length} resources`);const f=new Map,c=[];for(const r of t){const w=o.get(r);w!=null&&w.path&&c.push((async()=>{const m=`${y}/cache/layout/${r}`,k=await this.cacheManager.get(m);let b;if(k)b=await k.clone().text();else{const E=await fetch(U(w.path));if(!E.ok){this.log.warn(`XLF fetch failed: ${r} (${E.status})`);return}const F=await E.blob();await this.cacheManager.put(m,F,"text/xml"),this.log.info(`Fetched + cached XLF ${r} (${F.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(r),fileType:"layout",size:F.size})),b=await F.text()}f.set(r,I(b,this.log))})())}for(const[r,w]of o)t.includes(r)||c.push((async()=>{const m=`${y}/cache/layout/${r}`,k=await this.cacheManager.get(m);if(!k&&w.path){const b=await fetch(U(w.path));if(b.ok){const E=await b.blob();await this.cacheManager.put(m,E,"text/xml"),this.log.info(`Fetched + cached XLF ${r} (non-scheduled, ${E.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(r),fileType:"layout",size:E.size}));const S=await E.text();f.set(r,I(S,this.log))}}else if(k){const b=await k.clone().text();f.set(r,I(b,this.log))}})());await Promise.allSettled(c),this.log.info(`Parsed ${f.size} XLFs`);const $=new O(i);for(const r of d)await this._enqueueFile(s,$,r,l)&&n++;const M=await $.build();M.length>0&&(M.push(H),i.enqueueOrderedTasks(M));const C=new Set,T=[...f.keys()].filter(r=>!t.includes(r)),g=new Map;for(const[r,w]of u)w.saveAs&&g.set(w.saveAs,r);const v=new Map;if(a)for(const[r,w]of Object.entries(a))v.set(parseInt(r,10),w);for(const r of t){const w=f.get(r);if(!w)continue;const m=new Set(w);for(const S of T){const R=f.get(S);if(R)for(const Y of R)m.add(Y)}const k=v.get(r)||[];for(const S of k){const R=g.get(S);R&&m.add(R)}const b=[];for(const S of m){if(C.has(S))continue;const R=u.get(S);R&&(b.push(R),C.add(S))}if(b.length===0)continue;this.log.info(`Layout ${r}: ${b.length} media`),b.sort((S,R)=>(S.size||0)-(R.size||0));const E=new O(i);for(const S of b)await this._enqueueFile(s,E,S,l)&&n++;const F=await E.build();F.length>0&&(F.push(H),i.enqueueOrderedTasks(F))}const L=[...u.keys()].filter(r=>!C.has(r));if(L.length>0){this.log.info(`${L.length} media not in any XLF: ${L.join(", ")}`);const r=new O(i);for(const m of L){const k=u.get(m);k&&await this._enqueueFile(s,r,k,l)&&n++}const w=await r.build();w.length>0&&i.enqueueOrderedTasks(w)}const z=i.running,p=i.queue.length;return this.log.info("Downloads active:",z,", queued:",p),{success:!0,enqueuedCount:n,activeCount:z,queuedCount:p}}async _enqueueFile(t,e,a,s){if(!a.path||a.path==="null"||a.path==="undefined")return this.log.debug("Skipping file with no path:",a.id),!1;const i=`${y}/cache/${a.type}/${a.id}`,n=await this.cacheManager.fileExists(i);if(n.exists)if(n.chunked&&n.metadata&&!n.metadata.complete){const{numChunks:u}=n.metadata,f=new Set;for(let c=0;c<u;c++)await this.cacheManager.getChunk(i,c)&&f.add(c);if(f.size===u)return this.log.info("All chunks present but metadata incomplete, marking complete:",i),n.metadata.complete=!0,await this.cacheManager.updateMetadata(i,n.metadata),!1;this.log.info(`Incomplete chunked download: ${f.size}/${u} chunks cached, resuming:`,i),a.skipChunks=f}else return this.log.debug("File already cached:",i,n.chunked?"(chunked)":"(whole file)"),await this.ensureStaticCacheEntry(a),!1;const l=`${a.type}/${a.id}`;if(t.getTask(l))return this.log.debug("File already downloading:",l,"- skipping duplicate"),!1;const d=e.addFile(a);if(d.state==="pending"){const u=this.cacheFileAfterDownload(d,a);return s.push(u),!0}return!1}async cacheFileAfterDownload(t,e){try{const a=`${y}/cache/${e.type}/${e.id}`,s=e.type==="layout"?"text/xml":e.type==="widget"?"text/html":"application/octet-stream",i=parseInt(e.size)||0;if(i>this.config.chunkStorageThreshold)return await this._progressiveCacheFile(t,e,a,s,i);const n=await t.wait();return await this.cacheManager.put(a,n,s),this.log.info("Cached after download:",a,`(${n.size} bytes)`),(await self.clients.matchAll()).forEach(o=>{o.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:n.size})}),this._cacheStaticResource(e,n),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),n}catch(a){throw this.log.error("Failed to cache after download:",e.id,a),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),a}}async _progressiveCacheFile(t,e,a,s,i){const{chunkSize:n,cacheName:l}=this.config,o=await caches.open(l);let d=0,u=!1;const f=Math.ceil(i/n);this.log.info(`Progressive download: ${a} (${x(i)}, ~${f} chunks)`);const c={totalSize:i,chunkSize:n,numChunks:f,contentType:s,chunked:!0,complete:!1,createdAt:Date.now()};await o.put(`${a}/metadata`,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})),this.cacheManager.metadataCache.set(a,c),this.log.info("Metadata stored, ready for progressive streaming:",a),t.onChunkDownloaded=async(C,T,g)=>{const v=new Response(T,{headers:{"Content-Type":s,"Content-Length":T.size,"X-Chunk-Index":C,"X-Total-Chunks":g}});if(await o.put(`${a}/chunk-${C}`,v),d++,(d%2===0||d===g)&&this.log.info(`Progressive: chunk ${d}/${g} cached for ${e.id}`),!u&&(C===0||C===g-1)){const L=C===0||await this.cacheManager.getChunk(a,0),z=C===g-1||await this.cacheManager.getChunk(a,g-1);L&&z&&(u=!0,(await self.clients.matchAll()).forEach(r=>{r.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:i,progressive:!0,chunksReady:d,totalChunks:g})}),this.log.info("Chunk 0 + last chunk cached — client notified, early playback ready:",a))}g!==f&&(c.numChunks=g,await o.put(`${a}/metadata`,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})))};const $=await t.wait();return d===0?(this.log.warn("Progressive callback never fired, falling back to putChunked:",a),$.size>0?await this.cacheManager.putChunked(a,$,s):await this.cacheManager.put(a,$,s),(await self.clients.matchAll()).forEach(T=>{T.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:$.size||i})}),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),$):t._urlExpired?(this.log.warn(`URL expired mid-download, partial cache: ${a} (${d}/${f} chunks stored)`),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),new Blob([],{type:s})):(this.log.info(`Progressive download complete: ${a} (${d} chunks stored)`),c.complete=!0,await this.cacheManager.updateMetadata(a,c),(await self.clients.matchAll()).forEach(C=>{C.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:i,complete:!0})}),this.pendingChunkStorage.delete(a),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),new Blob([],{type:s}))}_cacheStaticResource(t,e){const a=t.path?(()=>{try{return new URL(t.path).searchParams.get("file")}catch{return null}})():null;a&&(a.endsWith(".js")||a.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(a))&&(async()=>{try{const s=await caches.open(this.config.staticCache),i=`${y}/cache/static/${a}`,n=a.split(".").pop().toLowerCase(),l=X[n]||"application/octet-stream";await Promise.all([s.put(i,new Response(e.slice(0,e.size,e.type),{headers:{"Content-Type":l}})),this.cacheManager.put(i,e.slice(0,e.size,e.type),l)]),this.log.info("Also cached as static resource:",a,`(${l})`)}catch(s){this.log.warn("Failed to cache static resource:",a,s)}})()}async ensureStaticCacheEntry(t){const e=t.path?(()=>{try{return new URL(t.path).searchParams.get("file")}catch{return null}})():null;if(!e||!(e.endsWith(".js")||e.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(e)))return;const a=await caches.open(this.config.staticCache),s=`${y}/cache/static/${e}`;if(await a.match(s))return;const n=`${y}/cache/${t.type}/${t.id}`,l=await this.cacheManager.get(n);if(!l)return;const o=await l.blob(),d=e.split(".").pop().toLowerCase(),u=X[d]||"application/octet-stream",f=`${y}/cache/static/${e}`;await Promise.all([a.put(s,new Response(o.slice(0,o.size,o.type),{headers:{"Content-Type":u}})),this.cacheManager.put(f,o.slice(0,o.size,o.type),u)]),this.log.info("Backfilled static cache for:",e,`(${u}, ${o.size} bytes)`)}async handleGetAllFiles(){return{success:!0,files:await this.cacheManager.getAllFiles()}}async handleClearCache(){return this.log.info("Clearing cache"),await this.cacheManager.clear(),{success:!0}}async handleGetProgress(){return{success:!0,progress:this.downloadManager.getProgress()}}}const q="2026-02-24T14:19:08.357Z",N="xibo-media-v1",P="xibo-static-v1",ie=[y+"/",y+"/index.html",y+"/setup.html"],A=new D("SW"),B=ee(A),_=B.chunkSize,oe=B.threshold,ce=B.blobCacheSize,re=B.concurrency;A.info("Loading modular Service Worker:",q);const V=new Z({concurrency:re,chunkSize:_,chunksPerFile:2}),W=new te({cacheName:N,chunkSize:_}),J=new ae(ce),he=new se(V,W,J,{staticCache:P}),le=new ne(V,W,J,{cacheName:N,staticCache:P,chunkSize:_,chunkStorageThreshold:oe});async function ue(h){const t=new URL(h.request.url),e=t.pathname.replace(y+"/ic",""),a=h.request.method;A.info("Interactive Control request:",a,e);let s=null;if(a==="POST"||a==="PUT")try{s=await h.request.text()}catch{}const i=await self.clients.matchAll({type:"window"});if(i.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const n=i[0];try{const l=await new Promise((o,d)=>{const u=new MessageChannel,f=setTimeout(()=>d(new Error("IC timeout")),5e3);u.port1.onmessage=c=>{clearTimeout(f),o(c.data)},n.postMessage({type:"INTERACTIVE_CONTROL",method:a,path:e,search:t.search,body:s},[u.port2])});return new Response(l.body||"",{status:l.status||200,headers:{"Content-Type":l.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(l){return A.error("IC handler error:",l),new Response(JSON.stringify({error:l.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",h=>{A.info("Installing... Version:",q),h.waitUntil(Promise.all([W.init(),caches.open(P).then(t=>(A.info("Caching static files"),t.addAll(ie)))]).then(async()=>{if(A.info("Cache initialized"),self.registration.active)try{const e=await(await caches.open("xibo-sw-version")).match("version");if(e){const a=await e.text();if(a===q){A.info("Same version already active, skipping activation to preserve streams");return}A.info("Version changed:",a,"→",q)}}catch{}return A.info("New version, activating immediately"),self.skipWaiting()}))});self.addEventListener("activate",h=>{A.info("Activating... Version:",q,"| @xiboplayer/cache:",Q),h.waitUntil(caches.keys().then(t=>Promise.all(t.filter(e=>e.startsWith("xibo-")&&e!==N&&e!==P&&e!=="xibo-sw-version").map(e=>(A.info("Deleting old cache:",e),caches.delete(e))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(q)),A.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{A.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(e=>{e.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",h=>{const t=new URL(h.request.url);if(t.pathname.startsWith(y+"/cache/")||t.pathname.startsWith(y+"/ic/")||t.pathname.startsWith("/player/")&&(t.pathname.endsWith(".html")||t.pathname==="/player/")||t.pathname.includes("xmds.php")&&t.searchParams.has("file")&&h.request.method==="GET"){if(t.pathname.startsWith(y+"/ic/")){h.respondWith(ue(h));return}h.respondWith(he.handleRequest(h))}});self.addEventListener("message",h=>{h.waitUntil(le.handleMessage(h).then(t=>{var e;(e=h.ports[0])==null||e.postMessage(t)}))});A.info("Modular Service Worker ready");
|
|
5
2
|
//# sourceMappingURL=sw-pwa.js.map
|