@xiboplayer/pwa 0.5.4 → 0.5.5
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/README.md +42 -0
- package/dist/assets/{cms-api-B3gEu-pj.js → cms-api-Df_4fWKB.js} +2 -2
- package/dist/assets/{cms-api-B3gEu-pj.js.map → cms-api-Df_4fWKB.js.map} +1 -1
- package/dist/assets/{index-BJfE9Kwo.js → index-BI2Wgrnr.js} +2 -2
- package/dist/assets/{index-BJfE9Kwo.js.map → index-BI2Wgrnr.js.map} +1 -1
- package/dist/assets/index-BtefBXN1.js +2 -0
- package/dist/assets/{index-CQyGlAYj.js.map → index-BtefBXN1.js.map} +1 -1
- package/dist/assets/index-C6HTCgOh.js +2 -0
- package/dist/assets/{index-CzDf1qpA.js.map → index-C6HTCgOh.js.map} +1 -1
- package/dist/assets/{index-CXNhzvrm.js → index-CO_3HB3b.js} +2 -2
- package/dist/assets/{index-CXNhzvrm.js.map → index-CO_3HB3b.js.map} +1 -1
- package/dist/assets/{index-DxBxL_GE.js → index-CSP8cHo2.js} +2 -2
- package/dist/assets/{index-DxBxL_GE.js.map → index-CSP8cHo2.js.map} +1 -1
- package/dist/assets/index-CXUhpySp.js +2 -0
- package/dist/assets/{index-B0GfHN6H.js.map → index-CXUhpySp.js.map} +1 -1
- package/dist/assets/index-DjVtpboH.js +2 -0
- package/dist/assets/{index-Y1vt-BGr.js.map → index-DjVtpboH.js.map} +1 -1
- package/dist/assets/{index-CUXQMBpU.js → index-DozRpAD9.js} +2 -2
- package/dist/assets/{index-CUXQMBpU.js.map → index-DozRpAD9.js.map} +1 -1
- package/dist/assets/index-O5-FLIor.js +2 -0
- package/dist/assets/{index-CExOPp2u.js.map → index-O5-FLIor.js.map} +1 -1
- package/dist/assets/main-4E7jVmyh.js +715 -0
- package/dist/assets/main-4E7jVmyh.js.map +1 -0
- package/dist/assets/{setup-DgQcE5P_.js → setup-D2LzAr3z.js} +2 -2
- package/dist/assets/{setup-DgQcE5P_.js.map → setup-D2LzAr3z.js.map} +1 -1
- package/dist/assets/{sync-manager-DBfiw5Ey.js → sync-manager-Cibvio-3.js} +2 -2
- package/dist/assets/{sync-manager-DBfiw5Ey.js.map → sync-manager-Cibvio-3.js.map} +1 -1
- package/dist/assets/widget-html-BzYo0-WO.js +5 -0
- package/dist/assets/widget-html-BzYo0-WO.js.map +1 -0
- package/dist/assets/{xmds-client-CX0t7Oes.js → xmds-client-uoul_PDG.js} +2 -2
- package/dist/assets/{xmds-client-CX0t7Oes.js.map → xmds-client-uoul_PDG.js.map} +1 -1
- package/dist/index.html +3 -3
- package/dist/setup.html +3 -3
- package/dist/sw-pwa.js +1 -1
- package/package.json +1 -1
- package/dist/assets/index-B0GfHN6H.js +0 -2
- package/dist/assets/index-CExOPp2u.js +0 -2
- package/dist/assets/index-CQyGlAYj.js +0 -2
- package/dist/assets/index-CzDf1qpA.js +0 -2
- package/dist/assets/index-Y1vt-BGr.js +0 -2
- package/dist/assets/main-ByDZRbW8.js +0 -715
- package/dist/assets/main-ByDZRbW8.js.map +0 -1
- package/dist/assets/widget-html-B_acad6q.js +0 -2
- package/dist/assets/widget-html-B_acad6q.js.map +0 -1
package/dist/sw-pwa.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as U,L as O,B as H,D as Z}from"./assets/widget-html-B_acad6q.js";import{VERSION as Q}from"./assets/index-CQyGlAYj.js";import"./assets/cms-api-B3gEu-pj.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-25T00:50:32.509Z",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");
|
|
1
|
+
import{r as U,L as O,B as H,D as Z}from"./assets/widget-html-BzYo0-WO.js";import{VERSION as Q}from"./assets/index-BtefBXN1.js";import"./assets/cms-api-Df_4fWKB.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-25T02:40:59.542Z",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");
|
|
2
2
|
//# sourceMappingURL=sw-pwa.js.map
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{I as i,O as p,S as l,c as u,p as m,s as S}from"./main-ByDZRbW8.js";import"./modulepreload-polyfill-B5Qt9EMX.js";import"./cms-api-B3gEu-pj.js";import"./widget-html-B_acad6q.js";const e="0.5.4",r={version:e},t=r.version;export{i as InterruptScheduler,p as OverlayScheduler,l as ScheduleManager,t as VERSION,u as calculateTimeline,m as parseLayoutDuration,S as scheduleManager};
|
|
2
|
-
//# sourceMappingURL=index-B0GfHN6H.js.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{D as y,P as m}from"./main-ByDZRbW8.js";import"./cms-api-B3gEu-pj.js";import{E as i}from"./widget-html-B_acad6q.js";import"./modulepreload-polyfill-B5Qt9EMX.js";const r="0.5.4",a={version:r};class c extends i{constructor(){super(),this.currentLayoutId=null,this.currentScheduleId=null,this.displayName="",this.hardwareKey="",this.playerType="pwa",this.displayStatus="idle",this.screenWidth=0,this.screenHeight=0,this.lastCollectionTime=null,this.lastHeartbeat=null,this.isRegistered=!1}set(t,e){if(this[t]===e)return;const s=this[t];this[t]=e,this.emit("change",t,e,s)}toJSON(){return{currentLayoutId:this.currentLayoutId,currentScheduleId:this.currentScheduleId,displayName:this.displayName,hardwareKey:this.hardwareKey,playerType:this.playerType,displayStatus:this.displayStatus,screenWidth:this.screenWidth,screenHeight:this.screenHeight,lastCollectionTime:this.lastCollectionTime,lastHeartbeat:this.lastHeartbeat,isRegistered:this.isRegistered}}}const d=a.version;export{y as DataConnectorManager,m as PlayerCore,c as PlayerState,d as VERSION};
|
|
2
|
-
//# sourceMappingURL=index-CExOPp2u.js.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{C as c,b as i,a as t,D as l,F as d,L as g,d as h,c as p,i as x}from"./widget-html-B_acad6q.js";import"./cms-api-B3gEu-pj.js";const a="0.5.4",e={version:a},o=e.version;export{c as CacheAnalyzer,i as CacheManager,t as CacheProxy,l as DownloadManager,d as FileDownload,g as LayoutTaskBuilder,o as VERSION,h as cacheManager,p as cacheWidgetHtml,x as isUrlExpired};
|
|
2
|
-
//# sourceMappingURL=index-CQyGlAYj.js.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{L as p,a as m,R as L}from"./main-ByDZRbW8.js";import"./modulepreload-polyfill-B5Qt9EMX.js";import"./cms-api-B3gEu-pj.js";import"./widget-html-B_acad6q.js";const o="0.5.4",r={version:o},a=r.version;export{p as LayoutPool,m as LayoutTranslator,L as RendererLite,a as VERSION};
|
|
2
|
-
//# sourceMappingURL=index-CzDf1qpA.js.map
|