@xiboplayer/pwa 0.6.12 → 0.7.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.
Files changed (54) hide show
  1. package/dist/assets/{chunk-config-BSfNUWQm.js → chunk-config-CpYnrCnz.js} +2 -2
  2. package/dist/assets/{chunk-config-BSfNUWQm.js.map → chunk-config-CpYnrCnz.js.map} +1 -1
  3. package/dist/assets/{index-O-mckgut.js → index-BLmNT21V.js} +4 -4
  4. package/dist/assets/index-BLmNT21V.js.map +1 -0
  5. package/dist/assets/index-BQElW3UF.js +2 -0
  6. package/dist/assets/{index-Ce8SH4GK.js.map → index-BQElW3UF.js.map} +1 -1
  7. package/dist/assets/index-BoLG4XL8.js +2 -0
  8. package/dist/assets/{index-BdPaMMuS.js.map → index-BoLG4XL8.js.map} +1 -1
  9. package/dist/assets/index-C2bD3Z5z.js +2 -0
  10. package/dist/assets/{index-BgdMU9Wc.js.map → index-C2bD3Z5z.js.map} +1 -1
  11. package/dist/assets/index-DP81_7Rp.js +13 -0
  12. package/dist/assets/{index-DjPsw-Gr.js.map → index-DP81_7Rp.js.map} +1 -1
  13. package/dist/assets/index-DkFelvR9.js +2 -0
  14. package/dist/assets/{index-Cyk88OM3.js.map → index-DkFelvR9.js.map} +1 -1
  15. package/dist/assets/index-QNL9DsGE.js +2 -0
  16. package/dist/assets/{index-DQPwwqPv.js.map → index-QNL9DsGE.js.map} +1 -1
  17. package/dist/assets/{index-CNV-DRzM.js → index-WSwWaMW7.js} +2 -2
  18. package/dist/assets/{index-CNV-DRzM.js.map → index-WSwWaMW7.js.map} +1 -1
  19. package/dist/assets/index-Z6yYXZYs.js +2 -0
  20. package/dist/assets/{index-CZapB-pf.js.map → index-Z6yYXZYs.js.map} +1 -1
  21. package/dist/assets/index-v7YXl8j9.js +2 -0
  22. package/dist/assets/{index-mP_O2eX3.js.map → index-v7YXl8j9.js.map} +1 -1
  23. package/dist/assets/main-C7-NPVem.js +736 -0
  24. package/dist/assets/main-C7-NPVem.js.map +1 -0
  25. package/dist/assets/protocol-detector-B1hfkHz0.js +16 -0
  26. package/dist/assets/protocol-detector-B1hfkHz0.js.map +1 -0
  27. package/dist/assets/setup-ppxoqsSk.js +2 -0
  28. package/dist/assets/{setup-DgfA_gJC.js.map → setup-ppxoqsSk.js.map} +1 -1
  29. package/dist/assets/sync-manager-Cov0Op4L.js +2 -0
  30. package/dist/assets/sync-manager-Cov0Op4L.js.map +1 -0
  31. package/dist/assets/widget-html-CsEe4aSF.js +2 -0
  32. package/dist/assets/widget-html-CsEe4aSF.js.map +1 -0
  33. package/dist/index.html +3 -3
  34. package/dist/setup.html +3 -3
  35. package/dist/sw-pwa.js +1 -1
  36. package/package.json +14 -14
  37. package/dist/assets/index-BdPaMMuS.js +0 -2
  38. package/dist/assets/index-BgdMU9Wc.js +0 -2
  39. package/dist/assets/index-CZapB-pf.js +0 -2
  40. package/dist/assets/index-Ce8SH4GK.js +0 -2
  41. package/dist/assets/index-Cyk88OM3.js +0 -2
  42. package/dist/assets/index-DQPwwqPv.js +0 -2
  43. package/dist/assets/index-DjPsw-Gr.js +0 -13
  44. package/dist/assets/index-O-mckgut.js.map +0 -1
  45. package/dist/assets/index-mP_O2eX3.js +0 -2
  46. package/dist/assets/main-DWaY10GP.js +0 -736
  47. package/dist/assets/main-DWaY10GP.js.map +0 -1
  48. package/dist/assets/protocol-detector-CFW2hHlm.js +0 -16
  49. package/dist/assets/protocol-detector-CFW2hHlm.js.map +0 -1
  50. package/dist/assets/setup-DgfA_gJC.js +0 -2
  51. package/dist/assets/sync-manager-Bg6-Bijq.js +0 -2
  52. package/dist/assets/sync-manager-Bg6-Bijq.js.map +0 -1
  53. package/dist/assets/widget-html-CVZPCszr.js +0 -2
  54. package/dist/assets/widget-html-CVZPCszr.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ import{createLogger as T,PLAYER_API as k}from"./index-BLmNT21V.js";const P=T("Cache"),B=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";class R{constructor(){this.dependants=new Map}getCacheKey(e,s,t=null){return`${B}/cache/${e}/${t||s}`}addDependant(e,s){const t=String(e);this.dependants.has(t)||this.dependants.set(t,new Set),this.dependants.get(t).add(String(s))}removeLayoutDependants(e){const s=String(e),t=[];for(const[n,r]of this.dependants)r.delete(s),r.size===0&&(this.dependants.delete(n),t.push(n));return t.length>0&&P.info(`${t.length} media files orphaned after layout ${e} removed:`,t),t}isMediaReferenced(e){const s=this.dependants.get(String(e));return s?s.size>0:!1}async clearAll(){this.dependants.clear()}}const N=new R,_=T("StoreClient");class O{async has(e,s){try{const t=await fetch(`/store/${e}/${s}`,{method:"HEAD"});if(t.ok)return!0;if(t.status===404)return!1;const n=new Error(`Store error: ${t.status}`);throw n.status=t.status,_.warn(`has(${e}/${s}): unexpected status ${t.status}`),n}catch(t){throw t.status||t.name==="AbortError"||t.name==="TimeoutError"||_.warn(`has(${e}/${s}): network error — ${t.message}`),t}}async get(e,s){var t;try{const n=await fetch(`/store/${e}/${s}`);if(!n.ok){if((t=n.body)==null||t.cancel(),n.status===404)return null;throw new Error(`Failed to get file: ${n.status}`)}return await n.blob()}catch(n){return _.error("get error:",n.message),null}}async put(e,s,t,n="application/octet-stream"){var r;try{const i=await fetch(`/store/${e}/${s}`,{method:"PUT",headers:{"Content-Type":n},body:t});return(r=i.body)==null||r.cancel(),i.ok}catch(i){return _.error("put error:",i.message),!1}}async remove(e){try{const t=await(await fetch("/store/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:e})})).json();return{deleted:t.deleted||0,total:t.total||e.length}}catch(s){return _.error("remove error:",s.message),{deleted:0,total:e.length}}}async list(){try{return(await(await fetch("/store/list")).json()).files||[]}catch(e){return _.error("list error:",e.message),[]}}}const b={media:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},layout:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},dataset:{maxRetries:4,retryDelayMs:0,retryDelays:[15e3,3e4,6e4,12e4],maxReenqueues:5,reenqueueDelayMs:6e4,skipHead:!0,cacheTtl:300},static:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0}};function v(d){return b[d]||b.media}const l=T("Download"),A=6,F=50*1024*1024,M=3,Q=100*1024*1024,z=2,D=6e5,L=15e3;function U(d){var n,r;const s=(r=(n=(d.path||d.code||"").split(".").pop())==null?void 0:n.split("?")[0])==null?void 0:r.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"}[s]||"application/octet-stream"}const f={normal:0,layout:1,high:2,urgent:3},w=Symbol("BARRIER");function C(d){try{const e=d.match(/X-Amz-Expires=(\d+)/);return e?parseInt(e[1],10):1/0}catch{return 1/0}}function S(d,e=30){const s=C(d);return s===1/0?!1:Date.now()/1e3>=s-e}class x{constructor(e,s={}){this.fileInfo=e,this.chunkIndex=s.chunkIndex??null,this.rangeStart=s.rangeStart??null,this.rangeEnd=s.rangeEnd??null,this.state="pending",this.blob=null,this._parentFile=null,this._priority=f.normal,this._typeConfig=v(e.type)}getUrl(){const e=this.fileInfo.path;if(S(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}async start(){var t;this.state="downloading";const e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`),this.chunkIndex!=null&&(e["X-Store-Chunk-Index"]=String(this.chunkIndex),this._parentFile&&(e["X-Store-Num-Chunks"]=String(this._parentFile.totalChunks),e["X-Store-Chunk-Size"]=String(this._parentFile.options.chunkSize||104857600))),this.fileInfo.md5&&(e["X-Store-MD5"]=this.fileInfo.md5),this.fileInfo.updateInterval&&(e["X-Cache-TTL"]=String(this.fileInfo.updateInterval)),this.fileInfo.cmsDownloadUrl&&(e["X-Cms-Download-Url"]=this.fileInfo.cmsDownloadUrl);const s=this._typeConfig.maxRetries;for(let n=1;n<=s;n++){const r=new AbortController,i=setTimeout(()=>r.abort(),D);try{const a=this.getUrl(),h={signal:r.signal};Object.keys(e).length>0&&(h.headers=e);const o=await fetch(a,h);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 h=r.signal.aborted?`Timeout after ${D/1e3}s`:a.message;if(n<s){const o=((t=this._typeConfig.retryDelays)==null?void 0:t[n-1])??this._typeConfig.retryDelayMs*n,u=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";l.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${u} attempt ${n}/${s} failed: ${h}. Retrying in ${o/1e3}s...`),await new Promise(p=>setTimeout(p,o))}else throw this.state="failed",r.signal.aborted?new Error(h):a}finally{clearTimeout(i)}}}}class E{constructor(e,s={}){this.fileInfo=e,this.options=s,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((t,n)=>{this._resolve=t,this._reject=n}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(S(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}wait(){return this._promise}async prepare(e){try{this.state="preparing";const{id:s,type:t,size:n}=this.fileInfo;l.info("[FileDownload] Starting:",`${t}/${s}`),this.totalBytes=n&&n>0?parseInt(n):0,this._contentType=U(this.fileInfo);const r=v(this.fileInfo.type).skipHead;if(this.totalBytes===0&&!r){const a=this.getUrl(),h=new AbortController,o=setTimeout(()=>h.abort(),L);try{const u=await fetch(a,{method:"HEAD",signal:h.signal});u.ok&&(this.totalBytes=parseInt(u.headers.get("Content-Length")||"0"),this._contentType=u.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(o)}}l.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const i=this.options.chunkSize||F;if(this.totalBytes>Q){const a=[];for(let c=0;c<this.totalBytes;c+=i)a.push({start:c,end:Math.min(c+i-1,this.totalBytes-1),index:a.length});this.totalChunks=a.length;const h=a.filter(c=>!this.skipChunks.has(c.index)),o=a.length-h.length;for(const c of a)this.skipChunks.has(c.index)&&(this.downloadedBytes+=c.end-c.start+1);if(h.length===0){l.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}o>0&&l.info(`[FileDownload] Resuming: ${o} chunks cached, ${h.length} to download`);const u=o>0;if(u){const c=h.sort((g,$)=>g.index-$.index);for(const g of c){const $=new x(this.fileInfo,{chunkIndex:g.index,rangeStart:g.start,rangeEnd:g.end});$._parentFile=this,$._priority=f.normal,this.tasks.push($)}}else for(const c of h){const g=new x(this.fileInfo,{chunkIndex:c.index,rangeStart:c.start,rangeEnd:c.end});g._parentFile=this,g._priority=c.index===0||c.index===a.length-1?f.high:f.normal,this.tasks.push(g)}const p=this.tasks.filter(c=>c._priority>=f.high).length;l.info(`[FileDownload] ${t}/${s}: ${this.tasks.length} chunks`+(p>0?` (${p} priority)`:"")+(u?" (resume)":""))}else{this.totalChunks=1;const a=new x(this.fileInfo,{});a._parentFile=this,this.tasks.push(a)}e.enqueueChunkTasks(this.tasks),this.state="downloading"}catch(s){l.error("[FileDownload] Prepare failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,s),this.state="failed",this._reject(s)}}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(s){l.warn("[FileDownload] onChunkDownloaded callback error:",s)}if(this.completedChunks===this.tasks.length&&this.state!=="complete"){this.state="complete";const{type:s,id:t}=this.fileInfo;if(e.chunkIndex==null)l.info("[FileDownload] Complete:",`${s}/${t}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)l.info("[FileDownload] Complete:",`${s}/${t}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const n=[];for(let i=0;i<this.totalChunks;i++){const a=this._chunkBlobs.get(i);a&&n.push(a)}const r=new Blob(n,{type:this._contentType});l.info("[FileDownload] Complete:",`${s}/${t}`,`(${r.size} bytes, reassembled)`),this._resolve(r)}this._chunkBlobs.clear()}}onTaskFailed(e,s){var t;if(!(this.state==="complete"||this.state==="failed")){if((t=s.message)!=null&&t.includes("URL expired")){const n=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.warn(`[FileDownload] URL expired, dropping${n}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(r=>r!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state="complete",this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}l.error("[FileDownload] Failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,s),this.state="failed",this._reject(s)}}}class K{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const s=q.stableKey(e);if(this.queue.active.has(s)){const n=this.queue.active.get(s);if(e.path&&e.path!==n.fileInfo.path){const r=C(n.fileInfo.path);C(e.path)>r&&(n.fileInfo.path=e.path)}return n}const t=new E(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(s,t),this._filesToPrepare.push(t),t}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let s=0,t=0;const n=()=>{for(;s<this._maxPreparing&&t<this._filesToPrepare.length;){const r=this._filesToPrepare[t++];s++,r.prepare(this).finally(()=>{s--,t>=this._filesToPrepare.length&&s===0?e():n()})}};this._filesToPrepare.length===0?e():n()})}_sortWithBarriers(){var i;const e=[],s=[],t=[],n=[];for(const a of this._tasks)if(a.chunkIndex==null)e.push(a);else if(a.chunkIndex===0)s.push(a);else{const h=((i=a._parentFile)==null?void 0:i.totalChunks)||0;h>1&&a.chunkIndex===h-1?t.push(a):n.push(a)}e.sort((a,h)=>{var o,u;return(((o=a._parentFile)==null?void 0:o.totalBytes)||0)-(((u=h._parentFile)==null?void 0:u.totalBytes)||0)}),n.sort((a,h)=>a.chunkIndex-h.chunkIndex);const r=[...e,...s,...t];return n.length>0&&r.push(w,...n),r}}class q{constructor(e={}){this.concurrency=e.concurrency||A,this.chunkSize=e.chunkSize||F,this.maxChunksPerFile=e.chunksPerFile||M,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,this._reenqueueTimers=new Set}static stableKey(e){return`${e.type}/${e.id}`}enqueue(e){const s=q.stableKey(e);if(this.active.has(s)){const n=this.active.get(s);if(e.path&&e.path!==n.fileInfo.path){const r=C(n.fileInfo.path);C(e.path)>r&&(l.info("[DownloadQueue] Refreshing URL for",s),n.fileInfo.path=e.path)}return n}const t=new E(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(s,t),l.info("[DownloadQueue] Enqueued:",s),this._schedulePrepare(t),t}_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 s of e)this.queue.push(s);this._sortQueue(),l.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let s=0,t=0;for(const n of e)n===w?(this.queue.push(w),t++):(this.queue.push(n),s++);l.info(`[DownloadQueue] Ordered queue: ${s} tasks, ${t} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,s)=>s._priority-e._priority)}prioritize(e,s){const t=`${e}/${s}`,n=this.active.get(t);if(!n)return l.info("[DownloadQueue] Not found:",t),!1;let r=0;for(const i of this.queue)i._parentFile===n&&i._priority<f.high&&(i._priority=f.high,r++);return this._sortQueue(),l.info("[DownloadQueue] Prioritized:",t,`(${r} tasks boosted)`),!0}prioritizeLayoutFiles(e,s=f.high){var r,i,a,h;const t=new Set(e.map(String));let n=0;for(const o of this.queue){const u=((r=o._parentFile)==null?void 0:r.fileInfo.saveAs)||String((i=o._parentFile)==null?void 0:i.fileInfo.id);t.has(u)&&o._priority<s&&(o._priority=s,n++)}for(const o of this._activeTasks){const u=((a=o._parentFile)==null?void 0:a.fileInfo.saveAs)||String((h=o._parentFile)==null?void 0:h.fileInfo.id);t.has(u)&&o._priority<s&&(o._priority=s)}this._sortQueue(),l.info("[DownloadQueue] Layout files prioritized:",t.size,"files,",n,"tasks boosted to",s)}urgentChunk(e,s,t){const n=`${e}/${s}`,r=this.active.get(n);if(!r)return l.info("[DownloadQueue] urgentChunk: file not active:",n,"chunk",t),!1;if(this._activeTasks.some(o=>o._parentFile===r&&o.chunkIndex===t&&o.state==="downloading")){const o=this._activeTasks.find(u=>u._parentFile===r&&u.chunkIndex===t);return o&&o._priority<f.urgent?(o._priority=f.urgent,l.info(`[DownloadQueue] URGENT: ${n} chunk ${t} (already in-flight, limiting slots)`),!0):(l.info("[DownloadQueue] urgentChunk: already urgent:",n,"chunk",t),!1)}const a=this.queue.findIndex(o=>o!==w&&o._parentFile===r&&o.chunkIndex===t);if(a===-1)return l.info("[DownloadQueue] urgentChunk: chunk not in queue:",n,"chunk",t),!1;const h=this.queue.splice(a,1)[0];return h._priority=f.urgent,this.queue.unshift(h),l.info(`[DownloadQueue] URGENT: ${n} chunk ${t} (moved to front)`),this.processQueue(),!0}processQueue(){var n;if(this.paused)return;const e=this.queue.some(r=>r!==w&&r._priority>=f.urgent)||((n=this._activeTasks)==null?void 0:n.some(r=>r._priority>=f.urgent&&r.state==="downloading")),s=e?z:this.concurrency,t=e?f.urgent:0;for(;this.running<s&&this.queue.length>0;){const r=this.queue[0];if(r===w){if(this.running>0)break;this.queue.shift();continue}if(r._priority<t||!this._canStartTask(r)){let i=!1;for(let a=1;a<this.queue.length&&this.queue[a]!==w;a++){const h=this.queue[a];if(h._priority>=t&&this._canStartTask(h)){this.queue.splice(a,1),this._startTask(h),i=!0;break}}if(!i)break;continue}this.queue.shift(),this._startTask(r)}this.queue.length===0&&this.running===0&&l.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 s=`${e.fileInfo.type}/${e.fileInfo.id}`,t=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.info(`[DownloadQueue] Starting: ${s}${t} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(n=>n!==e),l.info(`[DownloadQueue] Fetched: ${s}${t} (${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);const{maxReenqueues:r,reenqueueDelayMs:i}=e._typeConfig;if(r>0){if(e._reenqueueCount=(e._reenqueueCount||0)+1,e._reenqueueCount>r){l.error(`[DownloadQueue] ${s} exceeded ${r} re-enqueues, failing permanently`),this.processQueue(),e._parentFile.onTaskFailed(e,n);return}l.warn(`[DownloadQueue] ${s} failed all retries (attempt ${e._reenqueueCount}/${r}), scheduling re-enqueue in ${i/1e3}s`);const a=setTimeout(()=>{this._reenqueueTimers.delete(a),e.state="pending",e._parentFile.state="downloading",this.queue.push(e),l.info(`[DownloadQueue] ${s} re-enqueued for retry`),this.processQueue()},i);this._reenqueueTimers.add(a),this.processQueue();return}this.processQueue(),e._parentFile.onTaskFailed(e,n)})}awaitAllPrepared(){return new Promise(e=>{const s=()=>{this._preparingCount===0&&this._prepareQueue.length===0?e():setTimeout(s,50)};s()})}removeCompleted(e){const s=this.active.get(e);s&&(s.state==="complete"||s.state==="failed")&&(this.queue=this.queue.filter(t=>t===w||t._parentFile!==s),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){const e={};for(const[s,t]of this.active.entries())t.state==="complete"||t.state==="failed"||(e[s]={downloaded:t.downloadedBytes,total:t.totalBytes,percent:t.totalBytes>0?(t.downloadedBytes/t.totalBytes*100).toFixed(1):0,state:t.state});return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0;for(const e of this._reenqueueTimers)clearTimeout(e);this._reenqueueTimers.clear()}}class X{constructor(e={}){this.queue=new q(e)}enqueue(e){return this.queue.enqueue(e)}enqueueForLayout(e){return this.queue.enqueue(e)}getTask(e){return this.queue.getTask(e)}getProgress(){return this.queue.getProgress()}prioritizeLayoutFiles(e,s){this.queue.prioritizeLayoutFiles(e,s),this.queue.processQueue()}urgentChunk(e,s,t){return this.queue.urgentChunk(e,s,t)}clear(){this.queue.clear()}}const y=T("CacheAnalyzer");function m(d){if(d===0)return"0 B";if(!Number.isFinite(d))return"∞";const e=["B","KB","MB","GB","TB"],s=Math.floor(Math.log(d)/Math.log(1024));return`${(d/Math.pow(1024,s)).toFixed(s>0?1:0)} ${e[s]}`}class Y{constructor(e,{threshold:s=80}={}){this.cache=e,this.threshold=s}async analyze(e){const s=await this.cache.list(),t=await this._getStorageEstimate(),n=new Set(e.map(o=>String(o.id))),r=[],i=[];for(const o of s)if(n.has(String(o.id)))r.push(o);else if(o.type==="widget"){const u=String(o.id).split("/")[0];n.has(u)?r.push(o):i.push(o)}else o.type==="static"?r.push(o):i.push(o);i.sort((o,u)=>(o.cachedAt||0)-(u.cachedAt||0));const a=i.reduce((o,u)=>o+(u.size||0),0),h={timestamp:Date.now(),storage:{usage:t.usage,quota:t.quota,percent:t.quota>0?Math.round(t.usage/t.quota*100):0},files:{required:r.length,orphaned:i.length,total:s.length},orphaned:i.map(o=>({id:o.id,type:o.type,size:o.size||0,cachedAt:o.cachedAt||0})),orphanedSize:a,evicted:[],threshold:this.threshold};if(y.info(`Storage: ${m(t.usage)} / ${m(t.quota)} (${h.storage.percent}%)`),y.info(`Cache: ${r.length} required, ${i.length} orphaned (${m(a)} reclaimable)`),i.length>0)for(const o of i){const u=Date.now()-(o.cachedAt||0),p=Math.floor(u/864e5),c=Math.floor(u%864e5/36e5),g=p>0?`${p}d ago`:`${c}h ago`;y.info(` Orphaned: ${o.type}/${o.id} (${m(o.size||0)}, cached ${g})`)}if(h.storage.percent>this.threshold&&i.length>0){y.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);const o=t.usage-t.quota*this.threshold/100;h.evicted=await this._evict(i,o)}else y.info(`No eviction needed (threshold: ${this.threshold}%)`);return h}async _getStorageEstimate(){var e;try{if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate)){const{usage:s,quota:t}=await navigator.storage.estimate();return{usage:s||0,quota:t||1/0}}}catch(s){y.warn("Storage estimate unavailable:",s.message)}return{usage:0,quota:1/0}}async _evict(e,s){const t=[];let n=0;for(const r of e){if(n>=s)break;t.push(r),n+=r.size||0}if(t.length===0)return[];try{const r=t.map(i=>({type:i.type,id:i.id}));await this.cache.remove(r);for(const i of t)y.info(` Evicted: ${i.type}/${i.id} (${m(i.size||0)})`);y.info(`Evicted ${t.length} files, freed ${m(n)}`)}catch(r){return y.warn("Eviction failed:",r.message),[]}return t.map(r=>({id:r.id,type:r.type,size:r.size||0,cachedAt:r.cachedAt||0}))}}const I=T("Cache"),H=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";async function G(d,e,s,t){var u;const n=`${k}/widgets/${d}/${e}/${s}`,r=`<base href="${k}/media/file/">`;let i=t;t.includes("<base ")||(t.includes("<head>")?i=t.replace("<head>","<head>"+r):t.includes("<HEAD>")?i=t.replace("<HEAD>","<HEAD>"+r):i=r+t);const a="<style>img,video{object-position:center center}</style>";i.includes("object-position:center center")||(i.includes("</head>")?i=i.replace("</head>",a+"</head>"):i.includes("</HEAD>")&&(i=i.replace("</HEAD>",a+"</HEAD>"))),i=i.replace(/\[\[ViewPortWidth]]/g,"device-width"),i=i.replace(/https?:\/\/[^\s"')<]+\.m3u8\b/gi,p=>"/stream-proxy?url="+encodeURIComponent(p));const h=new RegExp(`https?://[^"'\\s)]+?(${k.replace(/\//g,"\\/")}/dependencies/[^"'\\s?)]+)(\\?[^"'\\s)]*)?`,"g");if(i=i.replace(h,(p,c)=>c),i=i.replace(/(<(?:script|link)\b[^>]*(?:src|href)=")(?!\/|https?:\/\/)(bundle\.min\.js|fonts\.css)(")/g,`$1${k}/dependencies/$2$3`),!i.includes("xiboICTargetId")){const p=`<script>var xiboICTargetId = '${s}';<\/script>`;i.includes(r)?i=i.replace(r,r+p):i.includes("<head>")?i=i.replace("<head>","<head>"+p):i=p+i}return i=i.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${H}/ic"`),I.info("Injected base tag in widget HTML"),(u=(await fetch(`/store${k}/widgets/${d}/${e}/${s}`,{method:"PUT",headers:{"Content-Type":"text/html; charset=utf-8"},body:i})).body)==null||u.cancel(),I.info(`Stored widget HTML at ${n} (${i.length} bytes)`),n}export{w as B,Y as C,X as D,b as F,K as L,O as S,R as a,E as b,G as c,N as d,v as g,S as i};
2
+ //# sourceMappingURL=widget-html-CsEe4aSF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"widget-html-CsEe4aSF.js","sources":["../../../cache/src/cache.js","../../../cache/src/store-client.js","../../../cache/src/file-types.js","../../../cache/src/download-manager.js","../../../cache/src/cache-analyzer.js","../../../cache/src/widget-html.js"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CacheManager - Dependant tracking and cache lifecycle\n *\n * After the storage unification, all downloads and file retrieval go through\n * the proxy's ContentStore (via StoreClient/DownloadClient). This class retains:\n * - Dependant tracking (which layouts reference which media)\n * - Cache key generation\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\n\n// Dynamic base path for multi-variant deployment (pwa, pwa-xmds, pwa-xlr)\nconst BASE = (typeof window !== 'undefined')\n ? window.location.pathname.replace(/\\/[^/]*$/, '').replace(/\\/$/, '') || '/player/pwa'\n : '/player/pwa';\n\nexport class CacheManager {\n constructor() {\n // Dependants: mediaId → Set<layoutId> — tracks which layouts use each media file\n this.dependants = new Map();\n }\n\n /**\n * Get cache key for a file\n * For media, uses the actual filename; for layouts, uses the ID\n */\n getCacheKey(type, id, filename = null) {\n const key = filename || id;\n return `${BASE}/cache/${type}/${key}`;\n }\n\n /**\n * Track that a media file is used by a layout (dependant)\n * @param {string|number} mediaId\n * @param {string|number} layoutId\n */\n addDependant(mediaId, layoutId) {\n const key = String(mediaId);\n if (!this.dependants.has(key)) {\n this.dependants.set(key, new Set());\n }\n this.dependants.get(key).add(String(layoutId));\n }\n\n /**\n * Remove a layout from all dependant sets (layout removed from schedule)\n * @param {string|number} layoutId\n * @returns {string[]} Media IDs that are now orphaned (no layouts reference them)\n */\n removeLayoutDependants(layoutId) {\n const lid = String(layoutId);\n const orphaned = [];\n\n for (const [mediaId, layouts] of this.dependants) {\n layouts.delete(lid);\n if (layouts.size === 0) {\n this.dependants.delete(mediaId);\n orphaned.push(mediaId);\n }\n }\n\n if (orphaned.length > 0) {\n log.info(`${orphaned.length} media files orphaned after layout ${layoutId} removed:`, orphaned);\n }\n return orphaned;\n }\n\n /**\n * Check if a media file is still referenced by any layout\n * @param {string|number} mediaId\n * @returns {boolean}\n */\n isMediaReferenced(mediaId) {\n const layouts = this.dependants.get(String(mediaId));\n return layouts ? layouts.size > 0 : false;\n }\n\n /**\n * Clear all cached files via proxy\n */\n async clearAll() {\n this.dependants.clear();\n }\n}\n\nexport const cacheManager = new CacheManager();\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * StoreClient — Pure REST client for ContentStore\n *\n * Communicates with the proxy's /store/* endpoints via fetch().\n * No Service Worker dependency — works immediately after construction.\n *\n * Usage:\n * const store = new StoreClient();\n * const exists = await store.has('media', '123');\n * const blob = await store.get('media', '123');\n * await store.put('widget', 'layout/1/region/2/media/3', htmlBlob, 'text/html');\n * await store.remove([{ type: 'media', id: '456' }]);\n * const files = await store.list();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('StoreClient');\n\nexport class StoreClient {\n /**\n * Check if a file exists in the store.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @returns {Promise<boolean>}\n */\n async has(type, id) {\n try {\n const response = await fetch(`/store/${type}/${id}`, { method: 'HEAD' });\n if (response.ok) return true;\n if (response.status === 404) return false;\n // Non-404 HTTP errors (500, 502, etc.) indicate proxy/store problems\n const err = new Error(`Store error: ${response.status}`);\n err.status = response.status;\n log.warn(`has(${type}/${id}): unexpected status ${response.status}`);\n throw err;\n } catch (error) {\n // Re-throw errors that are not simple network failures swallowed above\n // (includes HTTP errors we threw, AbortError, TypeError from fetch)\n if (error.status || error.name === 'AbortError' || error.name === 'TimeoutError') {\n throw error;\n }\n // Network errors (proxy unreachable) — log and re-throw so callers\n // can distinguish from \"not cached\" (which returns false)\n log.warn(`has(${type}/${id}): network error — ${error.message}`);\n throw error;\n }\n }\n\n /**\n * Get a file from the store as a Blob.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @returns {Promise<Blob|null>}\n */\n async get(type, id) {\n try {\n const response = await fetch(`/store/${type}/${id}`);\n if (!response.ok) {\n response.body?.cancel();\n if (response.status === 404) return null;\n throw new Error(`Failed to get file: ${response.status}`);\n }\n return await response.blob();\n } catch (error) {\n log.error('get error:', error.message);\n return null;\n }\n }\n\n /**\n * Store a file in the ContentStore.\n * @param {string} type - 'media', 'layout', 'widget', 'static'\n * @param {string} id - File ID or path\n * @param {Blob|ArrayBuffer|string} body - Content to store\n * @param {string} [contentType='application/octet-stream'] - MIME type\n * @returns {Promise<boolean>} true if stored successfully\n */\n async put(type, id, body, contentType = 'application/octet-stream') {\n try {\n const response = await fetch(`/store/${type}/${id}`, {\n method: 'PUT',\n headers: { 'Content-Type': contentType },\n body,\n });\n response.body?.cancel();\n return response.ok;\n } catch (error) {\n log.error('put error:', error.message);\n return false;\n }\n }\n\n /**\n * Delete files from the store.\n * @param {Array<{type: string, id: string}>} files - Files to delete\n * @returns {Promise<{deleted: number, total: number}>}\n */\n async remove(files) {\n try {\n const response = await fetch('/store/delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ files }),\n });\n const result = await response.json();\n return { deleted: result.deleted || 0, total: result.total || files.length };\n } catch (error) {\n log.error('remove error:', error.message);\n return { deleted: 0, total: files.length };\n }\n }\n\n /**\n * List all files in the store.\n * @returns {Promise<Array<{id: string, type: string, size: number}>>}\n */\n async list() {\n try {\n const response = await fetch('/store/list');\n const data = await response.json();\n return data.files || [];\n } catch (error) {\n log.error('list error:', error.message);\n return [];\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * FILE_TYPES — centralized download behavior per file type.\n *\n * Each type declares retry strategy, HEAD skip, and cache TTL.\n * Used by DownloadTask/FileDownload instead of ad-hoc isGetData checks.\n */\n\nexport const FILE_TYPES = {\n media: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n layout: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n dataset: { maxRetries: 4, retryDelayMs: 0,\n retryDelays: [15_000, 30_000, 60_000, 120_000],\n maxReenqueues: 5, reenqueueDelayMs: 60_000,\n skipHead: true, cacheTtl: 300 },\n static: { maxRetries: 3, retryDelayMs: 500, retryDelays: null,\n maxReenqueues: 0, reenqueueDelayMs: 0,\n skipHead: false, cacheTtl: Infinity },\n};\n\nexport function getFileTypeConfig(type) {\n return FILE_TYPES[type] || FILE_TYPES.media;\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * DownloadManager - Flat queue download orchestration\n *\n * Works in both browser and Service Worker contexts.\n * Handles download queue, concurrency control, parallel chunks, and MD5 verification.\n *\n * Architecture (flat queue):\n * - DownloadTask: Single HTTP fetch unit (one GET request — full file or one chunk)\n * - FileDownload: Orchestrator that creates DownloadTasks for a file (HEAD + chunks)\n * - DownloadQueue: Flat queue where every download unit competes equally for connection slots\n * - DownloadManager: Public facade\n *\n * BEFORE: Queue[File, File, File] → each File internally spawns N chunk fetches\n * AFTER: Queue[chunk, chunk, file, chunk, chunk, file, chunk] → flat, 1 fetch per slot\n *\n * This eliminates the two-layer concurrency problem where N files × M chunks per file\n * could exceed Chromium's 6-per-host connection limit, causing head-of-line blocking.\n *\n * Per-file chunk limit (maxChunksPerFile) prevents one large file from hogging all\n * connection slots, ensuring bandwidth is shared fairly and chunk 0 arrives fast.\n *\n * Usage:\n * const dm = new DownloadManager({ concurrency: 6, chunkSize: 50MB, chunksPerFile: 2 });\n * const file = dm.enqueue({ id, type, path, md5 });\n * const blob = await file.wait();\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { getFileTypeConfig } from './file-types.js';\n\nconst log = createLogger('Download');\nconst DEFAULT_CONCURRENCY = 6; // Max concurrent HTTP connections (matches Chromium per-host limit)\nconst DEFAULT_CHUNK_SIZE = 50 * 1024 * 1024; // 50MB chunks\nconst DEFAULT_MAX_CHUNKS_PER_FILE = 3; // Max parallel chunk downloads per file\nconst CHUNK_THRESHOLD = 100 * 1024 * 1024; // Files > 100MB get chunked\nconst URGENT_CONCURRENCY = 2; // Slots when urgent chunk is active (bandwidth focus)\nconst FETCH_TIMEOUT_MS = 600_000; // 10 minutes — 100MB chunk at ~2 Mbps\nconst HEAD_TIMEOUT_MS = 15_000; // 15 seconds for HEAD requests\n\n/**\n * Infer Content-Type from file path extension.\n * Used when we skip HEAD (size already known from RequiredFiles).\n */\nfunction inferContentType(fileInfo) {\n const path = fileInfo.path || fileInfo.code || '';\n const ext = path.split('.').pop()?.split('?')[0]?.toLowerCase();\n const types = {\n mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg',\n png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',\n gif: 'image/gif', svg: 'image/svg+xml', webp: 'image/webp',\n css: 'text/css', js: 'application/javascript',\n ttf: 'font/ttf', otf: 'font/otf', woff: 'font/woff', woff2: 'font/woff2',\n xml: 'application/xml', xlf: 'application/xml',\n };\n return types[ext] || 'application/octet-stream';\n}\n\n// Priority levels — higher number = starts first\nexport const PRIORITY = { normal: 0, layout: 1, high: 2, urgent: 3 };\n\n/**\n * BARRIER sentinel — hard gate in the download queue.\n *\n * When processQueue() encounters a BARRIER:\n * - If tasks are still in-flight above it → STOP (slots stay empty)\n * - If running === 0 → remove barrier, continue with tasks below\n *\n * Used by LayoutQueueBuilder to separate critical chunks (chunk-0, chunk-last)\n * from remaining bulk chunks. Ensures video playback can start before all\n * chunks finish downloading.\n */\nexport const BARRIER = Symbol('BARRIER');\n\n/**\n * Parse the X-Amz-Expires absolute timestamp from a signed URL.\n * Returns the expiry as a Unix timestamp (seconds), or Infinity if not found.\n */\nfunction getUrlExpiry(url) {\n try {\n const match = url.match(/X-Amz-Expires=(\\d+)/);\n return match ? parseInt(match[1], 10) : Infinity;\n } catch {\n return Infinity;\n }\n}\n\n/**\n * Check if a signed URL has expired (or will expire within a grace period).\n * @param {string} url - Signed URL with X-Amz-Expires parameter\n * @param {number} graceSeconds - Seconds before actual expiry to consider it expired (default: 30)\n * @returns {boolean}\n */\nexport function isUrlExpired(url, graceSeconds = 30) {\n const expiry = getUrlExpiry(url);\n if (expiry === Infinity) return false;\n return (Date.now() / 1000) >= (expiry - graceSeconds);\n}\n\n\n/**\n * DownloadTask - Single HTTP fetch unit\n *\n * Handles exactly one HTTP request: either a full small file GET or a single Range GET\n * for one chunk of a larger file. Includes retry logic with exponential backoff.\n */\nexport class DownloadTask {\n constructor(fileInfo, options = {}) {\n this.fileInfo = fileInfo;\n this.chunkIndex = options.chunkIndex ?? null;\n this.rangeStart = options.rangeStart ?? null;\n this.rangeEnd = options.rangeEnd ?? null;\n this.state = 'pending';\n this.blob = null;\n this._parentFile = null;\n this._priority = PRIORITY.normal;\n this._typeConfig = getFileTypeConfig(fileInfo.type);\n }\n\n getUrl() {\n const url = this.fileInfo.path;\n if (isUrlExpired(url)) {\n throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);\n }\n return url;\n }\n\n async start() {\n this.state = 'downloading';\n const headers = {};\n if (this.rangeStart != null) {\n headers['Range'] = `bytes=${this.rangeStart}-${this.rangeEnd}`;\n }\n // Pass chunk metadata and MD5 via custom headers for cache-through proxy\n if (this.chunkIndex != null) {\n headers['X-Store-Chunk-Index'] = String(this.chunkIndex);\n if (this._parentFile) {\n headers['X-Store-Num-Chunks'] = String(this._parentFile.totalChunks);\n headers['X-Store-Chunk-Size'] = String(this._parentFile.options.chunkSize || 104857600);\n }\n }\n if (this.fileInfo.md5) {\n headers['X-Store-MD5'] = this.fileInfo.md5;\n }\n if (this.fileInfo.updateInterval) {\n headers['X-Cache-TTL'] = String(this.fileInfo.updateInterval);\n }\n if (this.fileInfo.cmsDownloadUrl) {\n headers['X-Cms-Download-Url'] = this.fileInfo.cmsDownloadUrl;\n }\n\n const maxRetries = this._typeConfig.maxRetries;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);\n try {\n const url = this.getUrl();\n const fetchOpts = { signal: ac.signal };\n if (Object.keys(headers).length > 0) fetchOpts.headers = headers;\n const response = await fetch(url, fetchOpts);\n\n if (!response.ok && response.status !== 206) {\n throw new Error(`Fetch failed: ${response.status}`);\n }\n\n this.blob = await response.blob();\n this.state = 'complete';\n return this.blob;\n\n } catch (error) {\n const msg = ac.signal.aborted ? `Timeout after ${FETCH_TIMEOUT_MS / 1000}s` : error.message;\n if (attempt < maxRetries) {\n const delay = this._typeConfig.retryDelays?.[attempt - 1]\n ?? this._typeConfig.retryDelayMs * attempt;\n const chunkLabel = this.chunkIndex != null ? ` chunk ${this.chunkIndex}` : '';\n log.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${chunkLabel} attempt ${attempt}/${maxRetries} failed: ${msg}. Retrying in ${delay / 1000}s...`);\n await new Promise(resolve => setTimeout(resolve, delay));\n } else {\n this.state = 'failed';\n throw ac.signal.aborted ? new Error(msg) : error;\n }\n } finally {\n clearTimeout(timer);\n }\n }\n }\n}\n\n/**\n * FileDownload - Orchestrates downloading a single file\n *\n * Does the HEAD request to determine file size, then:\n * - Small file (≤ 100MB): creates 1 DownloadTask for the full file\n * - Large file (> 100MB): creates N DownloadTasks, one per chunk\n *\n * All tasks are enqueued into the flat DownloadQueue where they compete\n * equally for HTTP connection slots with tasks from other files.\n *\n * Provides wait() that resolves when ALL tasks for this file complete.\n * Supports progressive caching via onChunkDownloaded callback.\n */\nexport class FileDownload {\n constructor(fileInfo, options = {}) {\n this.fileInfo = fileInfo;\n this.options = options;\n this.state = 'pending';\n this.tasks = [];\n this.completedChunks = 0;\n this.totalChunks = 0;\n this.totalBytes = 0;\n this.downloadedBytes = 0;\n this.onChunkDownloaded = null;\n this.skipChunks = fileInfo.skipChunks || new Set();\n this._contentType = 'application/octet-stream';\n this._chunkBlobs = new Map();\n this._runningCount = 0; // Currently running tasks for this file\n this._resolve = null;\n this._reject = null;\n this._promise = new Promise((res, rej) => {\n this._resolve = res;\n this._reject = rej;\n });\n this._promise.catch(() => {});\n }\n\n getUrl() {\n const url = this.fileInfo.path;\n if (isUrlExpired(url)) {\n throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);\n }\n return url;\n }\n\n wait() {\n return this._promise;\n }\n\n /**\n * Determine file size and create DownloadTasks.\n * Uses RequiredFiles size when available (instant, no network).\n * Falls back to HEAD request only when size is unknown.\n */\n async prepare(queue) {\n try {\n this.state = 'preparing';\n const { id, type, size } = this.fileInfo;\n log.info('[FileDownload] Starting:', `${type}/${id}`);\n\n // Use declared size from RequiredFiles — no HEAD needed for queue building\n this.totalBytes = (size && size > 0) ? parseInt(size) : 0;\n this._contentType = inferContentType(this.fileInfo);\n\n // Skip HEAD for types that declare skipHead (e.g. datasets — dynamic API endpoints).\n // These generate responses server-side; HEAD triggers the full handler for nothing\n // and may fail if the CMS cache isn't warm yet. They're always small, never chunked.\n const skipHead = getFileTypeConfig(this.fileInfo.type).skipHead;\n\n if (this.totalBytes === 0 && !skipHead) {\n // No size declared — HEAD fallback (rare: only for files without CMS size)\n const url = this.getUrl();\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), HEAD_TIMEOUT_MS);\n try {\n const head = await fetch(url, { method: 'HEAD', signal: ac.signal });\n if (head.ok) {\n this.totalBytes = parseInt(head.headers.get('Content-Length') || '0');\n this._contentType = head.headers.get('Content-Type') || this._contentType;\n }\n } finally {\n clearTimeout(timer);\n }\n }\n\n log.info('[FileDownload] File size:', (this.totalBytes / 1024 / 1024).toFixed(1), 'MB');\n\n const chunkSize = this.options.chunkSize || DEFAULT_CHUNK_SIZE;\n\n if (this.totalBytes > CHUNK_THRESHOLD) {\n const ranges = [];\n for (let start = 0; start < this.totalBytes; start += chunkSize) {\n ranges.push({\n start,\n end: Math.min(start + chunkSize - 1, this.totalBytes - 1),\n index: ranges.length\n });\n }\n this.totalChunks = ranges.length;\n\n const needed = ranges.filter(r => !this.skipChunks.has(r.index));\n const skippedCount = ranges.length - needed.length;\n\n for (const r of ranges) {\n if (this.skipChunks.has(r.index)) {\n this.downloadedBytes += (r.end - r.start + 1);\n }\n }\n\n if (needed.length === 0) {\n log.info('[FileDownload] All chunks already cached, nothing to download');\n this.state = 'complete';\n this._resolve(new Blob([], { type: this._contentType }));\n return;\n }\n\n if (skippedCount > 0) {\n log.info(`[FileDownload] Resuming: ${skippedCount} chunks cached, ${needed.length} to download`);\n }\n\n const isResume = skippedCount > 0;\n\n if (isResume) {\n const sorted = needed.sort((a, b) => a.index - b.index);\n for (const r of sorted) {\n const task = new DownloadTask(this.fileInfo, {\n chunkIndex: r.index, rangeStart: r.start, rangeEnd: r.end\n });\n task._parentFile = this;\n task._priority = PRIORITY.normal;\n this.tasks.push(task);\n }\n } else {\n for (const r of needed) {\n const task = new DownloadTask(this.fileInfo, {\n chunkIndex: r.index, rangeStart: r.start, rangeEnd: r.end\n });\n task._parentFile = this;\n task._priority = (r.index === 0 || r.index === ranges.length - 1) ? PRIORITY.high : PRIORITY.normal;\n this.tasks.push(task);\n }\n }\n\n const highCount = this.tasks.filter(t => t._priority >= PRIORITY.high).length;\n log.info(`[FileDownload] ${type}/${id}: ${this.tasks.length} chunks` +\n (highCount > 0 ? ` (${highCount} priority)` : '') +\n (isResume ? ' (resume)' : ''));\n\n } else {\n this.totalChunks = 1;\n const task = new DownloadTask(this.fileInfo, {});\n task._parentFile = this;\n this.tasks.push(task);\n }\n\n queue.enqueueChunkTasks(this.tasks);\n this.state = 'downloading';\n\n } catch (error) {\n log.error('[FileDownload] Prepare failed:', `${this.fileInfo.type}/${this.fileInfo.id}`, error);\n this.state = 'failed';\n this._reject(error);\n }\n }\n\n async onTaskComplete(task) {\n this.completedChunks++;\n this.downloadedBytes += task.blob.size;\n\n if (task.chunkIndex != null) {\n this._chunkBlobs.set(task.chunkIndex, task.blob);\n }\n\n if (this.options.onProgress) {\n this.options.onProgress(this.downloadedBytes, this.totalBytes);\n }\n\n // Fire progressive chunk callback\n if (this.onChunkDownloaded && task.chunkIndex != null) {\n try {\n await this.onChunkDownloaded(task.chunkIndex, task.blob, this.totalChunks);\n } catch (e) {\n log.warn('[FileDownload] onChunkDownloaded callback error:', e);\n }\n }\n\n if (this.completedChunks === this.tasks.length && this.state !== 'complete') {\n this.state = 'complete';\n const { type, id } = this.fileInfo;\n\n if (task.chunkIndex == null) {\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(${task.blob.size} bytes)`);\n this._resolve(task.blob);\n } else if (this.onChunkDownloaded) {\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(progressive, ${this.totalChunks} chunks)`);\n this._resolve(new Blob([], { type: this._contentType }));\n } else {\n const ordered = [];\n for (let i = 0; i < this.totalChunks; i++) {\n const blob = this._chunkBlobs.get(i);\n if (blob) ordered.push(blob);\n }\n const assembled = new Blob(ordered, { type: this._contentType });\n log.info('[FileDownload] Complete:', `${type}/${id}`, `(${assembled.size} bytes, reassembled)`);\n this._resolve(assembled);\n }\n\n this._chunkBlobs.clear();\n }\n }\n\n onTaskFailed(task, error) {\n if (this.state === 'complete' || this.state === 'failed') return;\n\n // URL expiration is transient — drop this task, don't fail the file.\n // Already-downloaded chunks are safe in cache. Next collection cycle\n // provides fresh URLs and the resume logic (skipChunks) fills the gaps.\n if (error.message?.includes('URL expired')) {\n const chunkLabel = task.chunkIndex != null ? ` chunk ${task.chunkIndex}` : '';\n log.warn(`[FileDownload] URL expired, dropping${chunkLabel}:`, `${this.fileInfo.type}/${this.fileInfo.id}`);\n this.tasks = this.tasks.filter(t => t !== task);\n // If all remaining tasks completed, resolve as partial\n if (this.tasks.length === 0 || this.completedChunks >= this.tasks.length) {\n this.state = 'complete';\n this._urlExpired = true;\n this._resolve(new Blob([], { type: this._contentType }));\n }\n return;\n }\n\n log.error('[FileDownload] Failed:', `${this.fileInfo.type}/${this.fileInfo.id}`, error);\n this.state = 'failed';\n this._reject(error);\n }\n}\n\n/**\n * LayoutTaskBuilder — Smart builder that produces a sorted, barrier-embedded\n * task list for a single layout.\n *\n * Usage:\n * const builder = new LayoutTaskBuilder(queue);\n * builder.addFile(fileInfo);\n * const orderedTasks = await builder.build();\n * queue.enqueueOrderedTasks(orderedTasks);\n *\n * The builder runs HEAD requests (throttled), collects the resulting\n * DownloadTasks, sorts them optimally, and embeds BARRIERs between\n * critical chunks (chunk-0, chunk-last) and bulk chunks.\n *\n * Duck-typing: implements enqueueChunkTasks() so FileDownload.prepare()\n * works unchanged — it just collects tasks instead of processing them.\n */\nexport class LayoutTaskBuilder {\n constructor(queue) {\n this.queue = queue; // Main DownloadQueue (for dedup via active map)\n this._filesToPrepare = []; // FileDownloads needing HEAD requests\n this._tasks = []; // Collected DownloadTasks (from prepare callbacks)\n this._maxPreparing = 2; // HEAD request throttle\n }\n\n /**\n * Register a file. Uses queue.active for dedup/URL refresh.\n * Does NOT trigger prepare — that happens in build().\n */\n addFile(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.queue.active.has(key)) {\n const existing = this.queue.active.get(key);\n // URL refresh (same logic as queue.enqueue)\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.queue.chunkSize,\n calculateMD5: this.queue.calculateMD5,\n onProgress: this.queue.onProgress\n });\n\n this.queue.active.set(key, file);\n this._filesToPrepare.push(file);\n return file;\n }\n\n /**\n * Duck-type interface for FileDownload.prepare().\n * Collects tasks instead of processing them.\n */\n enqueueChunkTasks(tasks) {\n this._tasks.push(...tasks);\n }\n\n /**\n * Run all HEAD requests (throttled) and return sorted tasks with barriers.\n */\n async build() {\n await this._prepareAll();\n return this._sortWithBarriers();\n }\n\n async _prepareAll() {\n await new Promise((resolve) => {\n let running = 0;\n let idx = 0;\n const next = () => {\n while (running < this._maxPreparing && idx < this._filesToPrepare.length) {\n const file = this._filesToPrepare[idx++];\n running++;\n file.prepare(this).finally(() => {\n running--;\n if (idx >= this._filesToPrepare.length && running === 0) {\n resolve();\n } else {\n next();\n }\n });\n }\n };\n if (this._filesToPrepare.length === 0) resolve();\n else next();\n });\n }\n\n _sortWithBarriers() {\n const nonChunked = [];\n const chunk0s = [];\n const chunkLasts = [];\n const remaining = [];\n\n for (const t of this._tasks) {\n if (t.chunkIndex == null) {\n nonChunked.push(t);\n } else if (t.chunkIndex === 0) {\n chunk0s.push(t);\n } else {\n const total = t._parentFile?.totalChunks || 0;\n if (total > 1 && t.chunkIndex === total - 1) {\n chunkLasts.push(t);\n } else {\n remaining.push(t);\n }\n }\n }\n\n nonChunked.sort((a, b) => (a._parentFile?.totalBytes || 0) - (b._parentFile?.totalBytes || 0));\n remaining.sort((a, b) => a.chunkIndex - b.chunkIndex);\n\n // Build: small files + critical chunks → BARRIER → bulk chunks\n const result = [...nonChunked, ...chunk0s, ...chunkLasts];\n if (remaining.length > 0) {\n result.push(BARRIER, ...remaining);\n }\n return result;\n }\n}\n\n/**\n * DownloadQueue - Flat queue with per-file and global concurrency limits\n *\n * Global concurrency limit (e.g., 6) controls total HTTP connections.\n * Per-file chunk limit (e.g., 2) prevents one large file from hogging all\n * connections, ensuring bandwidth per chunk is high and chunk 0 arrives fast.\n * HEAD requests are throttled to avoid flooding browser connection pool.\n */\nexport class DownloadQueue {\n constructor(options = {}) {\n this.concurrency = options.concurrency || DEFAULT_CONCURRENCY;\n this.chunkSize = options.chunkSize || DEFAULT_CHUNK_SIZE;\n this.maxChunksPerFile = options.chunksPerFile || DEFAULT_MAX_CHUNKS_PER_FILE;\n this.calculateMD5 = options.calculateMD5;\n this.onProgress = options.onProgress;\n\n this.queue = []; // DownloadTask[] — flat queue of chunk/file tasks\n this.active = new Map(); // stableKey → FileDownload\n this._activeTasks = []; // DownloadTask[] — currently in-flight tasks\n this.running = 0;\n\n // HEAD request throttling: prevents prepare() from flooding browser connections\n this._prepareQueue = [];\n this._preparingCount = 0;\n this._maxPreparing = 2; // Max concurrent HEAD requests\n\n // When paused, processQueue() is a no-op (used during barrier setup)\n this.paused = false;\n\n // Track getData re-enqueue timers so clear() can cancel them\n this._reenqueueTimers = new Set();\n }\n\n static stableKey(fileInfo) {\n return `${fileInfo.type}/${fileInfo.id}`;\n }\n\n enqueue(fileInfo) {\n const key = DownloadQueue.stableKey(fileInfo);\n\n if (this.active.has(key)) {\n const existing = this.active.get(key);\n if (fileInfo.path && fileInfo.path !== existing.fileInfo.path) {\n const oldExpiry = getUrlExpiry(existing.fileInfo.path);\n const newExpiry = getUrlExpiry(fileInfo.path);\n if (newExpiry > oldExpiry) {\n log.info('[DownloadQueue] Refreshing URL for', key);\n existing.fileInfo.path = fileInfo.path;\n }\n }\n return existing;\n }\n\n const file = new FileDownload(fileInfo, {\n chunkSize: this.chunkSize,\n calculateMD5: this.calculateMD5,\n onProgress: this.onProgress\n });\n\n this.active.set(key, file);\n log.info('[DownloadQueue] Enqueued:', key);\n\n // Throttled prepare: HEAD requests are limited to avoid flooding connections\n this._schedulePrepare(file);\n\n return file;\n }\n\n /**\n * Schedule a FileDownload's prepare() with throttling.\n * Only N HEAD requests run concurrently to preserve connections for data transfers.\n */\n _schedulePrepare(file) {\n this._prepareQueue.push(file);\n this._processPrepareQueue();\n }\n\n _processPrepareQueue() {\n while (this._preparingCount < this._maxPreparing && this._prepareQueue.length > 0) {\n const file = this._prepareQueue.shift();\n this._preparingCount++;\n file.prepare(this).finally(() => {\n this._preparingCount--;\n this._processPrepareQueue();\n });\n }\n }\n\n enqueueChunkTasks(tasks) {\n for (const task of tasks) {\n this.queue.push(task);\n }\n this._sortQueue();\n\n log.info(`[DownloadQueue] ${tasks.length} tasks added (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /**\n * Enqueue a pre-ordered list of tasks (with optional BARRIER sentinels).\n * Preserves insertion order — no sorting. Position = priority.\n *\n * Used by LayoutQueueBuilder to push the entire download queue in layout\n * playback order with barriers separating critical chunks from bulk.\n *\n * @param {Array<DownloadTask|Symbol>} items - Tasks and BARRIERs in order\n */\n enqueueOrderedTasks(items) {\n let taskCount = 0;\n let barrierCount = 0;\n for (const item of items) {\n if (item === BARRIER) {\n this.queue.push(BARRIER);\n barrierCount++;\n } else {\n this.queue.push(item);\n taskCount++;\n }\n }\n\n log.info(`[DownloadQueue] Ordered queue: ${taskCount} tasks, ${barrierCount} barriers (${this.queue.length} pending, ${this.running} active)`);\n this.processQueue();\n }\n\n /** Sort queue by priority (highest first), stable within same priority. */\n _sortQueue() {\n this.queue.sort((a, b) => b._priority - a._priority);\n }\n\n prioritize(fileType, fileId) {\n const key = `${fileType}/${fileId}`;\n const file = this.active.get(key);\n\n if (!file) {\n log.info('[DownloadQueue] Not found:', key);\n return false;\n }\n\n let boosted = 0;\n for (const t of this.queue) {\n if (t._parentFile === file && t._priority < PRIORITY.high) {\n t._priority = PRIORITY.high;\n boosted++;\n }\n }\n this._sortQueue();\n\n log.info('[DownloadQueue] Prioritized:', key, `(${boosted} tasks boosted)`);\n return true;\n }\n\n /**\n * Boost priority for files needed by the current/next layout.\n * @param {Array} fileIds - Media IDs needed by the layout\n * @param {number} priority - Priority level (default: PRIORITY.high)\n */\n prioritizeLayoutFiles(fileIds, priority = PRIORITY.high) {\n const idSet = new Set(fileIds.map(String));\n\n let boosted = 0;\n for (const t of this.queue) {\n const matchValue = t._parentFile?.fileInfo.saveAs || String(t._parentFile?.fileInfo.id);\n if (idSet.has(matchValue) && t._priority < priority) {\n t._priority = priority;\n boosted++;\n }\n }\n for (const t of this._activeTasks) {\n const matchValue = t._parentFile?.fileInfo.saveAs || String(t._parentFile?.fileInfo.id);\n if (idSet.has(matchValue) && t._priority < priority) {\n t._priority = priority;\n }\n }\n this._sortQueue();\n\n log.info('[DownloadQueue] Layout files prioritized:', idSet.size, 'files,', boosted, 'tasks boosted to', priority);\n }\n\n /**\n * Emergency priority for a specific streaming chunk.\n * Called by the Service Worker when a video is stalled waiting for chunk N.\n * Sets urgent priority → queue re-sorts → processQueue() limits concurrency.\n */\n urgentChunk(fileType, fileId, chunkIndex) {\n const key = `${fileType}/${fileId}`;\n const file = this.active.get(key);\n\n if (!file) {\n log.info('[DownloadQueue] urgentChunk: file not active:', key, 'chunk', chunkIndex);\n return false;\n }\n\n // Already in-flight — nothing to do\n const isActive = this._activeTasks.some(\n t => t._parentFile === file && t.chunkIndex === chunkIndex && t.state === 'downloading'\n );\n if (isActive) {\n // Mark the in-flight task as urgent so processQueue() limits concurrency\n const activeTask = this._activeTasks.find(\n t => t._parentFile === file && t.chunkIndex === chunkIndex\n );\n if (activeTask && activeTask._priority < PRIORITY.urgent) {\n activeTask._priority = PRIORITY.urgent;\n log.info(`[DownloadQueue] URGENT: ${key} chunk ${chunkIndex} (already in-flight, limiting slots)`);\n // Don't call processQueue() — can't stop in-flight tasks, but next\n // processQueue() call (when any task completes) will see hasUrgent\n // and limit new starts to URGENT_CONCURRENCY.\n return true;\n }\n log.info('[DownloadQueue] urgentChunk: already urgent:', key, 'chunk', chunkIndex);\n return false;\n }\n\n // Find task in queue (may be past a barrier)\n const idx = this.queue.findIndex(\n t => t !== BARRIER && t._parentFile === file && t.chunkIndex === chunkIndex\n );\n\n if (idx === -1) {\n log.info('[DownloadQueue] urgentChunk: chunk not in queue:', key, 'chunk', chunkIndex);\n return false;\n }\n\n const task = this.queue.splice(idx, 1)[0];\n task._priority = PRIORITY.urgent;\n // Move to front of queue (past any barriers)\n this.queue.unshift(task);\n\n log.info(`[DownloadQueue] URGENT: ${key} chunk ${chunkIndex} (moved to front)`);\n this.processQueue();\n return true;\n }\n\n /**\n * Process queue — barrier-aware loop.\n *\n * Supports two modes:\n * 1. Priority-sorted (legacy): queue sorted by priority, urgent reduces concurrency\n * 2. Barrier-ordered: queue contains BARRIER sentinels that act as hard gates\n *\n * BARRIER behavior:\n * - When processQueue() hits a BARRIER and running > 0 → STOP (slots stay empty)\n * - When running === 0 → remove barrier, continue with tasks below\n * - Tasks are never reordered past a BARRIER (except urgentChunk which bypasses)\n *\n * Urgent mode: when any task has PRIORITY.urgent, concurrency drops to\n * URGENT_CONCURRENCY so the stalled chunk gets maximum bandwidth.\n */\n processQueue() {\n if (this.paused) return;\n\n // Determine effective concurrency and minimum priority to start\n const hasUrgent = this.queue.some(t => t !== BARRIER && t._priority >= PRIORITY.urgent) ||\n this._activeTasks?.some(t => t._priority >= PRIORITY.urgent && t.state === 'downloading');\n const maxSlots = hasUrgent ? URGENT_CONCURRENCY : this.concurrency;\n const minPriority = hasUrgent ? PRIORITY.urgent : 0; // Urgent = only urgent tasks run\n\n // Fill slots from front of queue\n while (this.running < maxSlots && this.queue.length > 0) {\n const next = this.queue[0];\n\n // Hit a BARRIER — hard gate\n if (next === BARRIER) {\n if (this.running > 0) {\n break; // In-flight tasks still running — slots stay empty\n }\n // All above-barrier tasks done → raise barrier, continue\n this.queue.shift();\n continue;\n }\n\n // Per-file limit: skip to next eligible task (but don't cross barrier)\n if (next._priority < minPriority || !this._canStartTask(next)) {\n let found = false;\n for (let i = 1; i < this.queue.length; i++) {\n if (this.queue[i] === BARRIER) break; // Don't look past barrier\n const task = this.queue[i];\n if (task._priority >= minPriority && this._canStartTask(task)) {\n this.queue.splice(i, 1);\n this._startTask(task);\n found = true;\n break;\n }\n }\n if (!found) break;\n continue;\n }\n\n this.queue.shift();\n this._startTask(next);\n }\n\n if (this.queue.length === 0 && this.running === 0) {\n log.info('[DownloadQueue] All downloads complete');\n }\n }\n\n /**\n * Per-file concurrency check. Priority sorting decides order,\n * this just prevents one file from hogging all connections.\n */\n _canStartTask(task) {\n return task._parentFile._runningCount < this.maxChunksPerFile;\n }\n\n _startTask(task) {\n this.running++;\n task._parentFile._runningCount++;\n this._activeTasks.push(task);\n const key = `${task.fileInfo.type}/${task.fileInfo.id}`;\n const chunkLabel = task.chunkIndex != null ? ` chunk ${task.chunkIndex}` : '';\n log.info(`[DownloadQueue] Starting: ${key}${chunkLabel} (${this.running}/${this.concurrency} active)`);\n\n task.start()\n .then(() => {\n this.running--;\n task._parentFile._runningCount--;\n this._activeTasks = this._activeTasks.filter(t => t !== task);\n log.info(`[DownloadQueue] Fetched: ${key}${chunkLabel} (${this.running} active, ${this.queue.length} pending)`);\n this.processQueue();\n return task._parentFile.onTaskComplete(task);\n })\n .catch(err => {\n this.running--;\n task._parentFile._runningCount--;\n this._activeTasks = this._activeTasks.filter(t => t !== task);\n\n // Re-enqueueable types (e.g. datasets): defer re-enqueue instead of permanent failure.\n // CMS \"cache not ready\" resolves when the XTR task runs (30-120s).\n const { maxReenqueues, reenqueueDelayMs } = task._typeConfig;\n if (maxReenqueues > 0) {\n task._reenqueueCount = (task._reenqueueCount || 0) + 1;\n if (task._reenqueueCount > maxReenqueues) {\n log.error(`[DownloadQueue] ${key} exceeded ${maxReenqueues} re-enqueues, failing permanently`);\n this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n return;\n }\n log.warn(`[DownloadQueue] ${key} failed all retries (attempt ${task._reenqueueCount}/${maxReenqueues}), scheduling re-enqueue in ${reenqueueDelayMs / 1000}s`);\n const timerId = setTimeout(() => {\n this._reenqueueTimers.delete(timerId);\n task.state = 'pending';\n task._parentFile.state = 'downloading';\n this.queue.push(task);\n log.info(`[DownloadQueue] ${key} re-enqueued for retry`);\n this.processQueue();\n }, reenqueueDelayMs);\n this._reenqueueTimers.add(timerId);\n this.processQueue();\n return;\n }\n\n this.processQueue();\n task._parentFile.onTaskFailed(task, err);\n });\n }\n\n /**\n * Wait for all queued prepare (HEAD) operations to finish.\n * Returns when the prepare queue is drained and all FileDownloads have\n * either created their tasks or failed.\n */\n awaitAllPrepared() {\n return new Promise((resolve) => {\n const check = () => {\n if (this._preparingCount === 0 && this._prepareQueue.length === 0) {\n resolve();\n } else {\n setTimeout(check, 50);\n }\n };\n check();\n });\n }\n\n removeCompleted(key) {\n const file = this.active.get(key);\n if (file && (file.state === 'complete' || file.state === 'failed')) {\n this.queue = this.queue.filter(t => t === BARRIER || t._parentFile !== file);\n this.active.delete(key);\n }\n }\n\n getTask(key) {\n return this.active.get(key) || null;\n }\n\n getProgress() {\n const progress = {};\n for (const [key, file] of this.active.entries()) {\n // Skip completed/failed — they stay in active until removeCompleted() runs\n if (file.state === 'complete' || file.state === 'failed') continue;\n progress[key] = {\n downloaded: file.downloadedBytes,\n total: file.totalBytes,\n percent: file.totalBytes > 0 ? (file.downloadedBytes / file.totalBytes * 100).toFixed(1) : 0,\n state: file.state\n };\n }\n return progress;\n }\n\n clear() {\n this.queue = [];\n this.active.clear();\n this.running = 0;\n this._prepareQueue = [];\n this._preparingCount = 0;\n // Cancel any pending getData re-enqueue timers\n for (const id of this._reenqueueTimers) clearTimeout(id);\n this._reenqueueTimers.clear();\n }\n}\n\n/**\n * DownloadManager - Main API\n */\nexport class DownloadManager {\n constructor(options = {}) {\n this.queue = new DownloadQueue(options);\n }\n\n enqueue(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n /**\n * Enqueue a file for layout-grouped downloading.\n * Layout grouping is now handled externally by LayoutTaskBuilder.\n * @param {Object} fileInfo - File info\n * @returns {FileDownload}\n */\n enqueueForLayout(fileInfo) {\n return this.queue.enqueue(fileInfo);\n }\n\n getTask(key) {\n return this.queue.getTask(key);\n }\n\n getProgress() {\n return this.queue.getProgress();\n }\n\n prioritizeLayoutFiles(fileIds, priority) {\n this.queue.prioritizeLayoutFiles(fileIds, priority);\n this.queue.processQueue();\n }\n\n urgentChunk(fileType, fileId, chunkIndex) {\n return this.queue.urgentChunk(fileType, fileId, chunkIndex);\n }\n\n clear() {\n this.queue.clear();\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CacheAnalyzer - Stale media detection and storage health monitoring\n *\n * Compares cached files against RequiredFiles from the CMS to identify\n * orphaned media that is no longer needed. Logs a summary every collection\n * cycle. Only evicts when storage pressure exceeds a configurable threshold.\n *\n * Works entirely through StoreClient (REST to proxy) — no IndexedDB,\n * no direct Cache API access.\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('CacheAnalyzer');\n\n/**\n * Format bytes into human-readable string (e.g. 1.2 GB, 350 MB)\n */\nfunction formatBytes(bytes) {\n if (bytes === 0) return '0 B';\n if (!Number.isFinite(bytes)) return '∞';\n const units = ['B', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(1024));\n const value = bytes / Math.pow(1024, i);\n return `${value.toFixed(i > 0 ? 1 : 0)} ${units[i]}`;\n}\n\nexport class CacheAnalyzer {\n /**\n * @param {import('./store-client.js').StoreClient} cache - StoreClient instance\n * @param {object} [options]\n * @param {number} [options.threshold=80] - Storage usage % above which eviction triggers\n */\n constructor(cache, { threshold = 80 } = {}) {\n this.cache = cache;\n this.threshold = threshold;\n }\n\n /**\n * Analyze cache health by comparing cached files against required files.\n *\n * @param {Array<{id: string, type: string}>} requiredFiles - Current RequiredFiles from CMS\n * @returns {Promise<object>} Analysis report\n */\n async analyze(requiredFiles) {\n const cachedFiles = await this.cache.list();\n const storage = await this._getStorageEstimate();\n\n // Build set of required file IDs (as strings for consistent comparison)\n const requiredIds = new Set(requiredFiles.map(f => String(f.id)));\n\n // Categorize cached files\n const required = [];\n const orphaned = [];\n\n for (const file of cachedFiles) {\n if (requiredIds.has(String(file.id))) {\n required.push(file);\n } else if (file.type === 'widget') {\n // Widget HTML IDs are \"layoutId/regionId/widgetId\" — check parent layout\n const parentLayoutId = String(file.id).split('/')[0];\n if (requiredIds.has(parentLayoutId)) {\n required.push(file);\n } else {\n orphaned.push(file);\n }\n } else if (file.type === 'static') {\n // Static files (bundle.min.js, fonts.css, fonts, images) are shared widget\n // dependencies — never orphan them, they're referenced from widget HTML\n required.push(file);\n } else {\n orphaned.push(file);\n }\n }\n\n // Sort orphaned by cachedAt ascending (oldest first — evict these first)\n orphaned.sort((a, b) => (a.cachedAt || 0) - (b.cachedAt || 0));\n\n const orphanedSize = orphaned.reduce((sum, f) => sum + (f.size || 0), 0);\n\n const report = {\n timestamp: Date.now(),\n storage: {\n usage: storage.usage,\n quota: storage.quota,\n percent: storage.quota > 0 ? Math.round((storage.usage / storage.quota) * 100) : 0,\n },\n files: {\n required: required.length,\n orphaned: orphaned.length,\n total: cachedFiles.length,\n },\n orphaned: orphaned.map(f => ({\n id: f.id,\n type: f.type,\n size: f.size || 0,\n cachedAt: f.cachedAt || 0,\n })),\n orphanedSize,\n evicted: [],\n threshold: this.threshold,\n };\n\n // Log summary\n log.info(`Storage: ${formatBytes(storage.usage)} / ${formatBytes(storage.quota)} (${report.storage.percent}%)`);\n log.info(`Cache: ${required.length} required, ${orphaned.length} orphaned (${formatBytes(orphanedSize)} reclaimable)`);\n\n if (orphaned.length > 0) {\n for (const f of orphaned) {\n const age = Date.now() - (f.cachedAt || 0);\n const days = Math.floor(age / 86400000);\n const hours = Math.floor((age % 86400000) / 3600000);\n const ageStr = days > 0 ? `${days}d ago` : `${hours}h ago`;\n log.info(` Orphaned: ${f.type}/${f.id} (${formatBytes(f.size || 0)}, cached ${ageStr})`);\n }\n }\n\n // Evict only when storage exceeds threshold\n if (report.storage.percent > this.threshold && orphaned.length > 0) {\n log.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);\n const targetBytes = storage.usage - (storage.quota * this.threshold / 100);\n report.evicted = await this._evict(orphaned, targetBytes);\n } else {\n log.info(`No eviction needed (threshold: ${this.threshold}%)`);\n }\n\n return report;\n }\n\n /**\n * Get storage estimate from the browser.\n * Falls back to { usage: 0, quota: Infinity } in environments without the API.\n */\n async _getStorageEstimate() {\n try {\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n const { usage, quota } = await navigator.storage.estimate();\n return { usage: usage || 0, quota: quota || Infinity };\n }\n } catch (e) {\n log.warn('Storage estimate unavailable:', e.message);\n }\n return { usage: 0, quota: Infinity };\n }\n\n /**\n * Evict orphaned files (oldest first) until targetBytes are freed.\n * Delegates deletion to StoreClient.remove() which routes to proxy.\n *\n * @param {Array} orphanedFiles - Files to evict, sorted oldest-first\n * @param {number} targetBytes - Bytes to free\n * @returns {Promise<Array>} Evicted file records\n */\n async _evict(orphanedFiles, targetBytes) {\n const toEvict = [];\n let plannedBytes = 0;\n\n for (const file of orphanedFiles) {\n if (plannedBytes >= targetBytes) break;\n toEvict.push(file);\n plannedBytes += file.size || 0;\n }\n\n if (toEvict.length === 0) return [];\n\n try {\n const filesToDelete = toEvict.map(f => ({ type: f.type, id: f.id }));\n await this.cache.remove(filesToDelete);\n\n for (const f of toEvict) {\n log.info(` Evicted: ${f.type}/${f.id} (${formatBytes(f.size || 0)})`);\n }\n log.info(`Evicted ${toEvict.length} files, freed ${formatBytes(plannedBytes)}`);\n } catch (err) {\n log.warn('Eviction failed:', err.message);\n return [];\n }\n\n return toEvict.map(f => ({\n id: f.id,\n type: f.type,\n size: f.size || 0,\n cachedAt: f.cachedAt || 0,\n }));\n }\n}\n\nexport { formatBytes };\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * Widget HTML processing — preprocesses widget HTML and stores via REST\n *\n * Handles:\n * - <base> tag injection for relative path resolution (CMS mirror paths)\n * - Interactive Control hostAddress rewriting\n * - CSS object-position fix for CMS template alignment\n *\n * URL rewriting is no longer needed — the CMS serves CSS with relative paths\n * (${PLAYER_API}/dependencies/font.otf), and the <base> tag resolves widget\n * media references via mirror routes. Zero translation, zero regex.\n *\n * Runs on the main thread (needs window.location for URL construction).\n * Stores content via PUT /store/... — no Cache API needed.\n */\n\nimport { createLogger, PLAYER_API } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\n\n// Dynamic base path for multi-variant deployment (pwa, pwa-xmds, pwa-xlr)\nconst BASE = (typeof window !== 'undefined')\n ? window.location.pathname.replace(/\\/[^/]*$/, '').replace(/\\/$/, '') || '/player/pwa'\n : '/player/pwa';\n\n/**\n * Store widget HTML in ContentStore for iframe loading.\n * Stored at mirror path ${PLAYER_API}/widgets/{L}/{R}/{M} — same URL the\n * CMS serves from, so iframes load directly from Express mirror routes.\n *\n * @param {string} layoutId - Layout ID\n * @param {string} regionId - Region ID\n * @param {string} mediaId - Media ID\n * @param {string} html - Widget HTML content\n * @returns {Promise<string>} Cache key URL (absolute path for iframe src)\n */\nexport async function cacheWidgetHtml(layoutId, regionId, mediaId, html) {\n const cacheKey = `${PLAYER_API}/widgets/${layoutId}/${regionId}/${mediaId}`;\n\n // Inject <base> tag — resolves relative media refs (e.g. \"42\") to mirror route\n const baseTag = `<base href=\"${PLAYER_API}/media/file/\">`;\n let modifiedHtml = html;\n\n // Insert base tag after <head> opening tag (skip if already present)\n if (!html.includes('<base ')) {\n if (html.includes('<head>')) {\n modifiedHtml = html.replace('<head>', '<head>' + baseTag);\n } else if (html.includes('<HEAD>')) {\n modifiedHtml = html.replace('<HEAD>', '<HEAD>' + baseTag);\n } else {\n modifiedHtml = baseTag + html;\n }\n }\n\n // Inject CSS default for object-position to suppress CMS template warning\n const cssFixTag = '<style>img,video{object-position:center center}</style>';\n if (!modifiedHtml.includes('object-position:center center')) {\n if (modifiedHtml.includes('</head>')) {\n modifiedHtml = modifiedHtml.replace('</head>', cssFixTag + '</head>');\n } else if (modifiedHtml.includes('</HEAD>')) {\n modifiedHtml = modifiedHtml.replace('</HEAD>', cssFixTag + '</HEAD>');\n }\n }\n\n // Replace CMS placeholders left for \"client-side SDK handling\"\n modifiedHtml = modifiedHtml.replace(/\\[\\[ViewPortWidth]]/g, 'device-width');\n\n // Route HLS streams through local proxy (adds CORS headers, rewrites segments)\n modifiedHtml = modifiedHtml.replace(\n /https?:\\/\\/[^\\s\"')<]+\\.m3u8\\b/gi,\n (url) => '/stream-proxy?url=' + encodeURIComponent(url)\n );\n\n // Rewrite dependency URLs to absolute local paths. CMS SOAP GetResource sends\n // bare filenames (e.g. src=\"bundle.min.js\") which resolve against <base> to the\n // wrong /media/file/ path. Normalize all dependency references to absolute paths.\n const depsPattern = new RegExp(\n `https?://[^\"'\\\\s)]+?(${PLAYER_API.replace(/\\//g, '\\\\/')}/dependencies/[^\"'\\\\s?)]+)(\\\\?[^\"'\\\\s)]*)?`,\n 'g'\n );\n modifiedHtml = modifiedHtml.replace(depsPattern, (_, path) => path);\n modifiedHtml = modifiedHtml.replace(\n /(<(?:script|link)\\b[^>]*(?:src|href)=\")(?!\\/|https?:\\/\\/)(bundle\\.min\\.js|fonts\\.css)(\")/g,\n `$1${PLAYER_API}/dependencies/$2$3`\n );\n\n // Inject xiboICTargetId — XIC library reads this global before its IIFE runs\n // to set _lib.targetId, which is included in every IC HTTP request as {id: ...}\n if (!modifiedHtml.includes('xiboICTargetId')) {\n const targetIdScript = `<script>var xiboICTargetId = '${mediaId}';</script>`;\n if (modifiedHtml.includes(baseTag)) {\n modifiedHtml = modifiedHtml.replace(baseTag, baseTag + targetIdScript);\n } else if (modifiedHtml.includes('<head>')) {\n modifiedHtml = modifiedHtml.replace('<head>', '<head>' + targetIdScript);\n } else {\n modifiedHtml = targetIdScript + modifiedHtml;\n }\n }\n\n // Rewrite Interactive Control hostAddress to SW-interceptable path\n modifiedHtml = modifiedHtml.replace(\n /hostAddress\\s*:\\s*[\"']https?:\\/\\/[^\"']+[\"']/g,\n `hostAddress: \"${BASE}/ic\"`\n );\n\n log.info('Injected base tag in widget HTML');\n\n // Store widget HTML — deps are already downloaded by the pipeline\n const putResp = await fetch(`/store${PLAYER_API}/widgets/${layoutId}/${regionId}/${mediaId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'text/html; charset=utf-8' },\n body: modifiedHtml,\n });\n putResp.body?.cancel();\n log.info(`Stored widget HTML at ${cacheKey} (${modifiedHtml.length} bytes)`);\n\n return cacheKey;\n}\n"],"names":["log","createLogger","BASE","CacheManager","type","id","filename","mediaId","layoutId","key","lid","orphaned","layouts","cacheManager","StoreClient","response","err","error","_a","body","contentType","files","result","FILE_TYPES","getFileTypeConfig","DEFAULT_CONCURRENCY","DEFAULT_CHUNK_SIZE","DEFAULT_MAX_CHUNKS_PER_FILE","CHUNK_THRESHOLD","URGENT_CONCURRENCY","FETCH_TIMEOUT_MS","HEAD_TIMEOUT_MS","inferContentType","fileInfo","ext","_b","PRIORITY","BARRIER","getUrlExpiry","url","match","isUrlExpired","graceSeconds","expiry","DownloadTask","options","headers","maxRetries","attempt","ac","timer","fetchOpts","msg","delay","chunkLabel","resolve","FileDownload","res","rej","queue","size","skipHead","head","chunkSize","ranges","start","needed","r","skippedCount","isResume","sorted","a","b","task","highCount","t","e","ordered","blob","assembled","LayoutTaskBuilder","DownloadQueue","existing","oldExpiry","file","tasks","running","idx","next","nonChunked","chunk0s","chunkLasts","remaining","total","items","taskCount","barrierCount","item","fileType","fileId","boosted","fileIds","priority","idSet","matchValue","_c","_d","chunkIndex","activeTask","hasUrgent","maxSlots","minPriority","found","i","maxReenqueues","reenqueueDelayMs","timerId","check","progress","DownloadManager","formatBytes","bytes","units","CacheAnalyzer","cache","threshold","requiredFiles","cachedFiles","storage","requiredIds","f","required","parentLayoutId","orphanedSize","sum","report","age","days","hours","ageStr","targetBytes","usage","quota","orphanedFiles","toEvict","plannedBytes","filesToDelete","cacheWidgetHtml","regionId","html","cacheKey","PLAYER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Aa,QAAQ,UAAWC,EAAY,SAAS,IAKxED,EAAeA,EAAa,QAAQ,uBAAwB,cAAc,EAG1EA,EAAeA,EAAa,QAC1B,kCACClH,GAAQ,qBAAuB,mBAAmBA,CAAG,CAC1D,EAKE,MAAMoH,EAAc,IAAI,OACtB,wBAAwBJ,EAAW,QAAQ,MAAO,KAAK,CAAC,6CACxD,GACJ,EASE,GARAE,EAAeA,EAAa,QAAQE,EAAa,CAACC,EAAGC,IAASA,CAAI,EAClEJ,EAAeA,EAAa,QAC1B,4FACA,KAAKF,CAAU,oBACnB,EAIM,CAACE,EAAa,SAAS,gBAAgB,EAAG,CAC5C,MAAMK,EAAiB,iCAAiCvJ,CAAO,eAC3DkJ,EAAa,SAASD,CAAO,EAC/BC,EAAeA,EAAa,QAAQD,EAASA,EAAUM,CAAc,EAC5DL,EAAa,SAAS,QAAQ,EACvCA,EAAeA,EAAa,QAAQ,SAAU,SAAWK,CAAc,EAEvEL,EAAeK,EAAiBL,CAEpC,CAGA,OAAAA,EAAeA,EAAa,QAC1B,+CACA,iBAAiBvJ,CAAI,MACzB,EAEEF,EAAI,KAAK,kCAAkC,GAQ3CkB,GALgB,MAAM,MAAM,SAASqI,CAAU,YAAY/I,CAAQ,IAAI4I,CAAQ,IAAI7I,CAAO,GAAI,CAC5F,OAAQ,MACR,QAAS,CAAE,eAAgB,0BAA0B,EACrD,KAAMkJ,CACV,CAAG,GACO,OAAR,MAAAvI,EAAc,SACdlB,EAAI,KAAK,yBAAyBsJ,CAAQ,KAAKG,EAAa,MAAM,SAAS,EAEpEH,CACT"}
package/dist/index.html CHANGED
@@ -94,10 +94,10 @@
94
94
  height: 100%;
95
95
  }
96
96
  </style>
97
- <script type="module" crossorigin src="./assets/main-DWaY10GP.js"></script>
97
+ <script type="module" crossorigin src="./assets/main-C7-NPVem.js"></script>
98
98
  <link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
99
- <link rel="modulepreload" crossorigin href="./assets/index-O-mckgut.js">
100
- <link rel="modulepreload" crossorigin href="./assets/widget-html-CVZPCszr.js">
99
+ <link rel="modulepreload" crossorigin href="./assets/index-BLmNT21V.js">
100
+ <link rel="modulepreload" crossorigin href="./assets/widget-html-CsEe4aSF.js">
101
101
  </head>
102
102
  <body>
103
103
  <!-- Status overlay -->
package/dist/setup.html CHANGED
@@ -287,10 +287,10 @@
287
287
  color: #444;
288
288
  }
289
289
  </style>
290
- <script type="module" crossorigin src="./assets/setup-DgfA_gJC.js"></script>
290
+ <script type="module" crossorigin src="./assets/setup-ppxoqsSk.js"></script>
291
291
  <link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
292
- <link rel="modulepreload" crossorigin href="./assets/index-O-mckgut.js">
293
- <link rel="modulepreload" crossorigin href="./assets/protocol-detector-CFW2hHlm.js">
292
+ <link rel="modulepreload" crossorigin href="./assets/index-BLmNT21V.js">
293
+ <link rel="modulepreload" crossorigin href="./assets/protocol-detector-B1hfkHz0.js">
294
294
  </head>
295
295
  <body>
296
296
  <div class="container">
package/dist/sw-pwa.js CHANGED
@@ -1,2 +1,2 @@
1
- import{D as C}from"./assets/widget-html-CVZPCszr.js";import{VERSION as S}from"./assets/index-CZapB-pf.js";import{c as v,R,M as T,B as i}from"./assets/chunk-config-BSfNUWQm.js";import{createLogger as E}from"./assets/index-O-mckgut.js";const o="2026-03-13T17:04:17.096Z",s=E("SW"),c=v(s),d=c.chunkSize,N=c.threshold,O=c.concurrency;s.info("Loading modular Service Worker:",o);const u=new C({concurrency:O,chunkSize:d,chunksPerFile:2}),A=new R(u),W=new T(u,{chunkSize:d,chunkStorageThreshold:N});async function I(e){const t=new URL(e.request.url),n=t.pathname.replace(i+"/ic",""),a=e.request.method;s.info("Interactive Control request:",a,n);let l=null;if(a==="POST"||a==="PUT")try{l=await e.request.text()}catch{}const h=await self.clients.matchAll({type:"window"});if(h.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const f=h[0];try{const r=await new Promise((m,g)=>{const p=new MessageChannel,w=setTimeout(()=>g(new Error("IC timeout")),5e3);p.port1.onmessage=y=>{clearTimeout(w),m(y.data)},f.postMessage({type:"INTERACTIVE_CONTROL",method:a,path:n,search:t.search,body:l},[p.port2])});return new Response(r.body||"",{status:r.status||200,headers:{"Content-Type":r.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(r){return s.error("IC handler error:",r),new Response(JSON.stringify({error:r.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",e=>{s.info("Installing... Version:",o),e.waitUntil((async()=>{if(self.registration.active)try{const n=await(await caches.open("xibo-sw-version")).match("version");if(n){const a=await n.text();if(a===o){s.info("Same version already active, skipping activation to preserve streams");return}s.info("Version changed:",a,"→",o)}}catch{}return s.info("New version, activating immediately"),self.skipWaiting()})())});self.addEventListener("activate",e=>{s.info("Activating... Version:",o,"| @xiboplayer/cache:",S),e.waitUntil(caches.keys().then(t=>Promise.all(t.filter(n=>n.startsWith("xibo-")&&n!=="xibo-sw-version").map(n=>(s.info("Deleting legacy cache:",n),caches.delete(n))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(o)),s.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{s.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(n=>{n.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",e=>{const t=new URL(e.request.url);if(t.pathname.startsWith(i+"/ic/")||t.pathname.startsWith("/player/")&&(t.pathname.endsWith(".html")||t.pathname==="/player/")||t.pathname.includes("xmds.php")&&t.searchParams.has("file")&&e.request.method==="GET"){if(t.pathname.startsWith(i+"/ic/")){e.respondWith(I(e));return}e.respondWith(A.handleRequest(e))}});self.addEventListener("message",e=>{e.waitUntil(W.handleMessage(e).then(t=>{var n;(n=e.ports[0])==null||n.postMessage(t)}))});s.info("Modular Service Worker ready");
1
+ import{D as C}from"./assets/widget-html-CsEe4aSF.js";import{VERSION as S}from"./assets/index-Z6yYXZYs.js";import{c as v,R,M as T,B as i}from"./assets/chunk-config-CpYnrCnz.js";import{createLogger as E}from"./assets/index-BLmNT21V.js";const o="2026-03-17T06:04:47.736Z",s=E("SW"),c=v(s),d=c.chunkSize,N=c.threshold,O=c.concurrency;s.info("Loading modular Service Worker:",o);const u=new C({concurrency:O,chunkSize:d,chunksPerFile:2}),A=new R(u),W=new T(u,{chunkSize:d,chunkStorageThreshold:N});async function I(e){const t=new URL(e.request.url),n=t.pathname.replace(i+"/ic",""),a=e.request.method;s.info("Interactive Control request:",a,n);let l=null;if(a==="POST"||a==="PUT")try{l=await e.request.text()}catch{}const h=await self.clients.matchAll({type:"window"});if(h.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const f=h[0];try{const r=await new Promise((m,g)=>{const p=new MessageChannel,w=setTimeout(()=>g(new Error("IC timeout")),5e3);p.port1.onmessage=y=>{clearTimeout(w),m(y.data)},f.postMessage({type:"INTERACTIVE_CONTROL",method:a,path:n,search:t.search,body:l},[p.port2])});return new Response(r.body||"",{status:r.status||200,headers:{"Content-Type":r.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(r){return s.error("IC handler error:",r),new Response(JSON.stringify({error:r.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",e=>{s.info("Installing... Version:",o),e.waitUntil((async()=>{if(self.registration.active)try{const n=await(await caches.open("xibo-sw-version")).match("version");if(n){const a=await n.text();if(a===o){s.info("Same version already active, skipping activation to preserve streams");return}s.info("Version changed:",a,"→",o)}}catch{}return s.info("New version, activating immediately"),self.skipWaiting()})())});self.addEventListener("activate",e=>{s.info("Activating... Version:",o,"| @xiboplayer/cache:",S),e.waitUntil(caches.keys().then(t=>Promise.all(t.filter(n=>n.startsWith("xibo-")&&n!=="xibo-sw-version").map(n=>(s.info("Deleting legacy cache:",n),caches.delete(n))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(o)),s.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{s.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(n=>{n.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",e=>{const t=new URL(e.request.url);if(t.pathname.startsWith(i+"/ic/")||t.pathname.startsWith("/player/")&&(t.pathname.endsWith(".html")||t.pathname==="/player/")||t.pathname.includes("xmds.php")&&t.searchParams.has("file")&&e.request.method==="GET"){if(t.pathname.startsWith(i+"/ic/")){e.respondWith(I(e));return}e.respondWith(A.handleRequest(e))}});self.addEventListener("message",e=>{e.waitUntil(W.handleMessage(e).then(t=>{var n;(n=e.ports[0])==null||n.postMessage(t)}))});s.info("Modular Service Worker ready");
2
2
  //# sourceMappingURL=sw-pwa.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiboplayer/pwa",
3
- "version": "0.6.12",
3
+ "version": "0.7.0",
4
4
  "description": "Lightweight PWA Xibo Player with RendererLite",
5
5
  "type": "module",
6
6
  "files": [
@@ -8,20 +8,20 @@
8
8
  ],
9
9
  "dependencies": {
10
10
  "html2canvas": "^1.4.1",
11
- "nanoevents": "^9.0.0",
11
+ "nanoevents": "^9.1.0",
12
12
  "xml2js": "^0.6.2",
13
- "@xiboplayer/crypto": "0.6.12",
14
- "@xiboplayer/renderer": "0.6.12",
15
- "@xiboplayer/schedule": "0.6.12",
16
- "@xiboplayer/cache": "0.6.12",
17
- "@xiboplayer/stats": "0.6.12",
18
- "@xiboplayer/settings": "0.6.12",
19
- "@xiboplayer/sw": "0.6.12",
20
- "@xiboplayer/sync": "0.6.12",
21
- "@xiboplayer/utils": "0.6.12",
22
- "@xiboplayer/xmds": "0.6.12",
23
- "@xiboplayer/core": "0.6.12",
24
- "@xiboplayer/xmr": "0.6.12"
13
+ "@xiboplayer/cache": "0.7.0",
14
+ "@xiboplayer/core": "0.7.0",
15
+ "@xiboplayer/crypto": "0.7.0",
16
+ "@xiboplayer/renderer": "0.7.0",
17
+ "@xiboplayer/schedule": "0.7.0",
18
+ "@xiboplayer/settings": "0.7.0",
19
+ "@xiboplayer/sw": "0.7.0",
20
+ "@xiboplayer/stats": "0.7.0",
21
+ "@xiboplayer/sync": "0.7.0",
22
+ "@xiboplayer/utils": "0.7.0",
23
+ "@xiboplayer/xmr": "0.7.0",
24
+ "@xiboplayer/xmds": "0.7.0"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/node": "^22.10.5",
@@ -1,2 +0,0 @@
1
- import{D as y,P as m}from"./main-DWaY10GP.js";import{EventEmitter as i}from"./index-O-mckgut.js";import"./modulepreload-polyfill-B5Qt9EMX.js";import"./widget-html-CVZPCszr.js";const r="0.6.12",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-BdPaMMuS.js.map
@@ -1,2 +0,0 @@
1
- import{I as n,O as i,S as l,b as p,c as d,p as S,s as h}from"./main-DWaY10GP.js";import"./modulepreload-polyfill-B5Qt9EMX.js";import"./index-O-mckgut.js";import"./widget-html-CVZPCszr.js";const e="0.6.12",r={version:e},t=r.version;export{n as InterruptScheduler,i as OverlayScheduler,l as ScheduleManager,t as VERSION,p as buildScheduleQueue,d as calculateTimeline,S as parseLayoutDuration,h as scheduleManager};
2
- //# sourceMappingURL=index-BgdMU9Wc.js.map
@@ -1,2 +0,0 @@
1
- import{B as i,C as t,a as c,D as l,F as g,b as d,L as p,S as C,d as E,c as h,g as F,i as R}from"./widget-html-CVZPCszr.js";import"./index-O-mckgut.js";const a="0.6.12",e={version:a},o=e.version;export{i as BARRIER,t as CacheAnalyzer,c as CacheManager,l as DownloadManager,g as FILE_TYPES,d as FileDownload,p as LayoutTaskBuilder,C as StoreClient,o as VERSION,E as cacheManager,h as cacheWidgetHtml,F as getFileTypeConfig,R as isUrlExpired};
2
- //# sourceMappingURL=index-CZapB-pf.js.map
@@ -1,2 +0,0 @@
1
- import{L as p,a as m,R as L}from"./main-DWaY10GP.js";import"./modulepreload-polyfill-B5Qt9EMX.js";import"./index-O-mckgut.js";import"./widget-html-CVZPCszr.js";const o="0.6.12",r={version:o},a=r.version;export{p as LayoutPool,m as LayoutTranslator,L as RendererLite,a as VERSION};
2
- //# sourceMappingURL=index-Ce8SH4GK.js.map
@@ -1,2 +0,0 @@
1
- import{createLogger as c}from"./index-O-mckgut.js";const a="0.6.12",l={version:a};class h{constructor(e){this.channel=e,this.url=null,this.cmsKey=null,this.socket=null,this.isConnected=!1,this.isConnectionWanted=!1,this.lastMessageAt=0,this._interval=null,this._listeners=new Map}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),()=>{var o;return(o=this._listeners.get(e))==null?void 0:o.delete(r)}}emit(e,...r){const o=this._listeners.get(e);if(o)for(const s of o)try{s(...r)}catch(i){console.error(`XmrClient: listener error for '${e}':`,i)}}async init(){this._interval||(this._interval=setInterval(()=>{this.isConnectionWanted&&!this.isActive()&&this.start(this.url||"DISABLED",this.cmsKey||"n/a")},6e4))}async start(e,r){if(this.url=e,this.cmsKey=r,this.isConnectionWanted=!0,this.socket){try{this.socket.close()}catch{}this.socket=null,this.isConnected=!1}try{this.socket=new WebSocket(e)}catch{this.emit("error","Failed to connect");return}this.socket.addEventListener("open",()=>{this.socket.send(JSON.stringify({type:"init",key:this.cmsKey,channel:this.channel})),this.isConnected=!0,this.lastMessageAt=Date.now(),this.emit("connected")}),this.socket.addEventListener("close",()=>{this.isConnected=!1,this.emit("disconnected")}),this.socket.addEventListener("error",()=>{this.emit("error","error")}),this.socket.addEventListener("message",o=>{if(this.lastMessageAt=Date.now(),o.data!=="H")try{const s=JSON.parse(o.data);if(!s.action)return;if(s.createdDt&&s.ttl){const i=Date.parse(s.createdDt);if(!isNaN(i)&&i+parseInt(s.ttl)*1e3<Date.now())return}this.emit(s.action,s)}catch(s){console.error("XmrClient: failed to parse message:",s)}})}async stop(){this.isConnectionWanted=!1,this._interval&&(clearInterval(this._interval),this._interval=null),this.socket&&(this.socket.close(),this.socket=null,this.isConnected=!1)}async send(e,r){if(!this.socket||!this.isConnected)throw new Error("Not connected");this.socket.send(JSON.stringify({action:e,...r}))}isActive(){return this.isConnected&&Date.now()-this.lastMessageAt<15*60*1e3}}const t=c("XMR");class y{constructor(e,r){this.config=e,this.player=r,this.xmr=null,this.connected=!1}async start(e,r){try{if(!this.xmr){t.info("Initializing connection to:",e);const o=this.config.xmrChannel||`player-${this.config.hardwareKey}`;this.xmr=new h(o),this.setupEventHandlers(),await this.xmr.init()}return await this.xmr.start(e,r),this.connected=!0,t.info("Connected successfully"),!0}catch(o){return t.warn("Failed to start:",o.message),t.info("Framework will retry automatically every 60s"),!1}}setupEventHandlers(){this.xmr&&(this.xmr.on("connected",()=>{var e,r;t.info("WebSocket connected"),this.connected=!0,(r=(e=this.player).emit)==null||r.call(e,"xmr-status",{connected:!0})}),this.xmr.on("disconnected",()=>{var e,r;t.warn("WebSocket disconnected (framework will reconnect)"),this.connected=!1,(r=(e=this.player).emit)==null||r.call(e,"xmr-status",{connected:!1})}),this.xmr.on("error",e=>{t.error("WebSocket error:",e)}),this.xmr.on("collectNow",async()=>{t.info("Received collectNow command from CMS");try{await this.player.collect(),t.debug("collectNow completed successfully")}catch(e){t.error("collectNow failed:",e)}}),this.xmr.on("screenShot",async()=>{t.info("Received screenShot command from CMS");try{await this.player.captureScreenshot(),t.debug("screenShot completed successfully")}catch(e){t.error("screenShot failed:",e)}}),this.xmr.on("licenceCheck",()=>{t.debug("Received licenceCheck (no-op for Linux client)")}),this.xmr.on("changeLayout",async e=>{const r=typeof e=="object"&&e.layoutId||e,o=typeof e=="object"&&parseInt(e.duration)||0,s=typeof e=="object"&&e.changeMode||"replace";t.info("Received changeLayout command:",r,o?`duration=${o}s`:"",s!=="replace"?`mode=${s}`:"");try{typeof e=="object"&&e.downloadRequired===!0&&(t.info("changeLayout: downloadRequired — triggering collection first"),await this.player.collect()),await this.player.changeLayout(r,{duration:o,changeMode:s}),t.debug("changeLayout completed successfully")}catch(i){t.error("changeLayout failed:",i)}}),this.xmr.on("overlayLayout",async e=>{const r=typeof e=="object"&&e.layoutId||e,o=typeof e=="object"&&parseInt(e.duration)||0;t.info("Received overlayLayout command:",r,o?`duration=${o}s`:"");try{typeof e=="object"&&e.downloadRequired===!0&&(t.info("overlayLayout: downloadRequired — triggering collection first"),await this.player.collect()),await this.player.overlayLayout(r,{duration:o}),t.debug("overlayLayout completed successfully")}catch(s){t.error("overlayLayout failed:",s)}}),this.xmr.on("revertToSchedule",async()=>{t.info("Received revertToSchedule command");try{await this.player.revertToSchedule(),t.debug("revertToSchedule completed successfully")}catch(e){t.error("revertToSchedule failed:",e)}}),this.xmr.on("purgeAll",async()=>{t.info("Received purgeAll command");try{await this.player.purgeAll(),t.debug("purgeAll completed successfully")}catch(e){t.error("purgeAll failed:",e)}}),this.xmr.on("commandAction",async e=>{const r=(e==null?void 0:e.commandCode)||e;t.info("Received commandAction command:",r);try{const o=this.player.displayCommands||(e==null?void 0:e.commands);await this.player.executeCommand(r,o),t.debug("commandAction completed successfully")}catch(o){t.error("commandAction failed:",o)}}),this.xmr.on("triggerWebhook",async e=>{t.info("Received triggerWebhook command:",e);try{this.player.triggerWebhook((e==null?void 0:e.triggerCode)||e),t.debug("triggerWebhook completed successfully")}catch(r){t.error("triggerWebhook failed:",r)}}),this.xmr.on("dataUpdate",async()=>{t.info("Received dataUpdate command");try{this.player.refreshDataConnectors(),t.debug("dataUpdate completed successfully")}catch(e){t.error("dataUpdate failed:",e)}}),this.xmr.on("rekeyAction",async()=>{t.info("Received rekeyAction command - rotating RSA key pair");try{this.config.data.xmrPubKey="",this.config.data.xmrPrivKey="",await this.config.ensureXmrKeyPair(),await this.player.collect(),t.info("RSA key pair rotated successfully")}catch(e){t.error("Key rotation failed:",e)}}),this.xmr.on("screenshot",async()=>{t.info("Received screenshot command from CMS");try{await this.player.captureScreenshot()}catch(e){t.error("screenshot failed:",e)}}),this.xmr.on("criteriaUpdate",async e=>{t.info("Received criteriaUpdate command:",e);try{await this.player.collect(),t.debug("criteriaUpdate completed successfully")}catch(r){t.error("criteriaUpdate failed:",r)}}),this.xmr.on("currentGeoLocation",async e=>{t.info("Received currentGeoLocation command:",e);try{e&&e.latitude!=null&&e.longitude!=null?this.player.reportGeoLocation?(this.player.reportGeoLocation(e),t.debug("currentGeoLocation: coordinates applied")):t.warn("Geo location reporting not implemented in player"):this.player.requestGeoLocation?(await this.player.requestGeoLocation(),t.debug("currentGeoLocation: browser location requested")):t.warn("Geo location request not implemented in player")}catch(r){t.error("currentGeoLocation failed:",r)}}))}async stop(){if(this.xmr)try{await this.xmr.stop(),this.connected=!1,this.xmr=null,t.info("Stopped")}catch(e){t.error("Error stopping:",e)}}isConnected(){return this.connected}async send(e,r){if(!this.connected||!this.xmr)return t.warn("Cannot send - not connected"),!1;try{return await this.xmr.send(e,r),!0}catch(o){return t.error("Error sending:",o),!1}}}const m=l.version;export{m as VERSION,y as XmrWrapper};
2
- //# sourceMappingURL=index-Cyk88OM3.js.map
@@ -1,2 +0,0 @@
1
- import{C as a,P as i,R as p,X as C,a as c,p as l}from"./protocol-detector-CFW2hHlm.js";import"./index-O-mckgut.js";const s="0.6.12",e={version:s},t=e.version;export{a as CMS_CLIENT_METHODS,i as ProtocolDetector,p as RestClient,t as VERSION,C as XmdsClient,c as assertCmsClient,l as parseScheduleResponse};
2
- //# sourceMappingURL=index-DQPwwqPv.js.map
@@ -1,13 +0,0 @@
1
- import{createLogger as D}from"./index-O-mckgut.js";const x="0.6.12",_={version:x},d=D("@xiboplayer/stats"),w="xibo-player-stats",F=1,b="stats";class I{constructor(e){this.db=null,this._dbName=e?`${w}-${e}`:w,this.inProgressStats=new Map}async init(){if(this.db){d.debug("Stats collector already initialized");return}return new Promise((e,t)=>{if(typeof indexedDB>"u"){const r=new Error("IndexedDB not available");d.error("IndexedDB not available - stats will not be persisted"),t(r);return}const s=indexedDB.open(this._dbName,F);s.onerror=()=>{const r=new Error(`Failed to open IndexedDB: ${s.error}`);d.error("Failed to open stats database:",s.error),t(r)},s.onsuccess=()=>{this.db=s.result,d.info("Stats database initialized"),e()},s.onupgradeneeded=r=>{const n=r.target.result;n.objectStoreNames.contains(b)||(n.createObjectStore(b,{keyPath:"id",autoIncrement:!0}).createIndex("submitted","submitted",{unique:!1}),d.info("Stats store created"))}})}async startLayout(e,t,s){if(!this.db){d.warn("Stats database not initialized");return}if((s==null?void 0:s.enableStat)===!1){d.debug(`Stats disabled for layout ${e} (enableStat=false)`);return}const r=`layout-${e}`;if(this.inProgressStats.has(r)){const o=this.inProgressStats.get(r);o.end=new Date,o.duration=Math.floor((o.end-o.start)/1e3),await this._saveStatSplit(o),this.inProgressStats.delete(r),d.debug(`Layout ${e} replay - ended previous cycle (${o.duration}s)`)}const n={type:"layout",layoutId:e,scheduleId:t,start:new Date,end:null,duration:0,count:1,submitted:0};this.inProgressStats.set(r,n),d.debug(`Started tracking layout ${e} (schedule ${t})`)}async endLayout(e,t){if(!this.db){d.warn("Stats database not initialized");return}const s=`layout-${e}`,r=this.inProgressStats.get(s);if(!r){d.debug(`Layout ${e} not found in progress (may have been ended by replay)`);return}r.end=new Date,r.duration=Math.floor((r.end-r.start)/1e3);try{await this._saveStatSplit(r),this.inProgressStats.delete(s),d.debug(`Ended tracking layout ${e} (${r.duration}s)`)}catch(n){throw d.error(`Failed to save layout stat ${e}:`,n),n}}async startWidget(e,t,s,r,n){if(!this.db){d.warn("Stats database not initialized");return}if((n==null?void 0:n.enableStat)===!1){d.debug(`Stats disabled for widget ${e} (enableStat=false)`);return}const o=`media-${e}-${t}`;if(this.inProgressStats.has(o)){const c=this.inProgressStats.get(o);c.end=new Date,c.duration=Math.floor((c.end-c.start)/1e3),await this._saveStatSplit(c),this.inProgressStats.delete(o),d.debug(`Widget ${e} replay - ended previous cycle (${c.duration}s)`)}const a={type:"media",mediaId:e,widgetId:r||null,layoutId:t,scheduleId:s,start:new Date,end:null,duration:0,count:1,submitted:0};this.inProgressStats.set(o,a),d.debug(`Started tracking widget ${e} in layout ${t}`)}async endWidget(e,t,s){if(!this.db){d.warn("Stats database not initialized");return}const r=`media-${e}-${t}`,n=this.inProgressStats.get(r);if(!n){d.debug(`Widget ${e} not found in progress (expected during layout transitions)`);return}n.end=new Date,n.duration=Math.floor((n.end-n.start)/1e3);try{await this._saveStatSplit(n),this.inProgressStats.delete(r),d.debug(`Ended tracking widget ${e} (${n.duration}s)`)}catch(o){throw d.error(`Failed to save widget stat ${e}:`,o),o}}async recordEvent(e,t,s,r){if(!this.db){d.warn("Stats database not initialized");return}const n=new Date,o={type:"event",tag:e,layoutId:t,widgetId:s,scheduleId:r,start:n,end:n,duration:0,count:1,submitted:0};try{await this._saveStat(o),d.debug(`Recorded event '${e}' for widget ${s} in layout ${t}`)}catch(a){throw d.error(`Failed to record event '${e}':`,a),a}}_queryByIndex(e,t,s,r){return new Promise((n,o)=>{const l=this.db.transaction([e],"readonly").objectStore(e).index(t).openCursor(s),u=[];l.onsuccess=y=>{const p=y.target.result;p&&u.length<r?(u.push(p.value),p.continue()):n(u)},l.onerror=()=>o(new Error(`Index query failed: ${l.error}`))})}_deleteByIds(e,t){return new Promise((s,r)=>{const n=this.db.transaction([e],"readwrite"),o=n.objectStore(e);let a=0;for(const c of t)if(c.id){const l=o.delete(c.id);l.onsuccess=()=>{a++},l.onerror=()=>{d.error(`Failed to delete ${c.id}:`,l.error)}}n.oncomplete=()=>s(a),n.onerror=()=>r(new Error(`Delete failed: ${n.error}`))})}async getStatsForSubmission(e=50){if(!this.db)return d.warn("Stats database not initialized"),[];const t=await this._queryByIndex(b,"submitted",IDBKeyRange.only(0),e);return d.debug(`Retrieved ${t.length} unsubmitted stats`),t}async clearSubmittedStats(e){if(!this.db||!(e!=null&&e.length))return;const t=await this._deleteByIds(b,e);d.debug(`Deleted ${t} submitted stats`)}async getAggregatedStatsForSubmission(e=50){const t=await this.getStatsForSubmission(e);if(t.length===0)return[];const s=new Map;for(const r of t){const n=r.start instanceof Date?r.start.toISOString().slice(0,13):new Date(r.start).toISOString().slice(0,13),o=`${r.type}|${r.layoutId}|${r.mediaId||""}|${r.widgetId||""}|${r.tag||""}|${r.scheduleId}|${n}`;if(s.has(o)){const a=s.get(o);a.count+=r.count||1,a.duration+=r.duration||0;const c=r.start instanceof Date?r.start:new Date(r.start),l=r.end instanceof Date?r.end:new Date(r.end||r.start);c<a.start&&(a.start=c),l>a.end&&(a.end=l),a._rawIds.push(r.id)}else s.set(o,{...r,start:r.start instanceof Date?r.start:new Date(r.start),end:r.end instanceof Date?r.end:new Date(r.end||r.start),count:r.count||1,_rawIds:[r.id]})}return Array.from(s.values())}async getAllStats(){return this.db?new Promise((e,t)=>{const n=this.db.transaction([b],"readonly").objectStore(b).getAll();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{d.error("Failed to get all stats:",n.error),t(new Error(`Failed to get all stats: ${n.error}`))}}):(d.warn("Stats database not initialized"),[])}async clearAllStats(){if(!this.db){d.warn("Stats database not initialized");return}return new Promise((e,t)=>{const n=this.db.transaction([b],"readwrite").objectStore(b).clear();n.onsuccess=()=>{d.debug("Cleared all stats"),this.inProgressStats.clear(),e()},n.onerror=()=>{d.error("Failed to clear all stats:",n.error),t(new Error(`Failed to clear stats: ${n.error}`))}})}async _saveStat(e){return new Promise((t,s)=>{const n=this.db.transaction([b],"readwrite").objectStore(b),o=n.add(e);o.onsuccess=()=>{t(o.result)},o.onerror=()=>{o.error.name==="QuotaExceededError"?(d.error("IndexedDB quota exceeded - cleaning old stats"),this._cleanOldStats().then(()=>{const a=n.add(e);a.onsuccess=()=>t(a.result),a.onerror=()=>s(a.error)}).catch(s)):s(o.error)}})}_splitAtHourBoundaries(e){const t=e.start,s=e.end;if(t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate()&&t.getHours()===s.getHours())return[e];const r=[];let n=new Date(t.getTime());for(;n<s;){const o=new Date(n.getTime());o.setMinutes(0,0,0),o.setHours(o.getHours()+1);const a=o<s?o:s,c=Math.floor((a-n)/1e3);r.push({...e,start:new Date(n.getTime()),end:new Date(a.getTime()),duration:c,count:1}),n=a}return r}async _saveStatSplit(e){const t=this._splitAtHourBoundaries(e);for(const s of t)await this._saveStat(s)}async _cleanOldStats(){if(this.db)return new Promise((e,t)=>{const r=this.db.transaction([b],"readwrite").objectStore(b),o=r.index("submitted").openCursor(1),a=[];o.onsuccess=c=>{const l=c.target.result;l&&a.length<100?(a.push(l.value.id),l.continue()):(a.forEach(u=>{r.delete(u)}),d.info(`Cleaned ${a.length} old stats due to quota`),e())},o.onerror=()=>{d.error("Failed to clean old stats:",o.error),t(o.error)}})}}function q(i){return!i||i.length===0?"<stats></stats>":`<stats>
2
- ${i.map(t=>{const s=$(t.start),r=$(t.end||t.start),n=[`type="${S(t.type)}"`,`fromdt="${S(s)}"`,`todt="${S(r)}"`,`scheduleid="${t.scheduleId}"`,`layoutid="${t.layoutId}"`];return t.type==="media"&&(t.mediaId&&n.push(`mediaid="${t.mediaId}"`),t.widgetId&&n.push(`widgetid="${t.widgetId}"`)),t.type==="event"&&(t.tag&&n.push(`tag="${S(t.tag)}"`),t.widgetId&&n.push(`widgetid="${t.widgetId}"`)),n.push(`count="${t.count}"`),n.push(`duration="${t.duration}"`),` <stat ${n.join(" ")} />`}).join(`
3
- `)}
4
- </stats>`}function $(i){i instanceof Date||(i=new Date(i));const e=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),s=String(i.getDate()).padStart(2,"0"),r=String(i.getHours()).padStart(2,"0"),n=String(i.getMinutes()).padStart(2,"0"),o=String(i.getSeconds()).padStart(2,"0");return`${e}-${t}-${s} ${r}:${n}:${o}`}function S(i){return typeof i!="string"?i:i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}const g=D("@xiboplayer/stats"),m="xibo-player-logs",P=1,h="logs";class B{constructor(e){this.db=null,this._dbName=e?`${m}-${e}`:m,this._reportedFaults=new Map}async init(){if(this.db){g.debug("Log reporter already initialized");return}return new Promise((e,t)=>{if(typeof indexedDB>"u"){const r=new Error("IndexedDB not available");g.error("IndexedDB not available - logs will not be persisted"),t(r);return}const s=indexedDB.open(this._dbName,P);s.onerror=()=>{const r=new Error(`Failed to open IndexedDB: ${s.error}`);g.error("Failed to open logs database:",s.error),t(r)},s.onsuccess=()=>{this.db=s.result,g.info("Logs database initialized"),e()},s.onupgradeneeded=r=>{const n=r.target.result;n.objectStoreNames.contains(h)||(n.createObjectStore(h,{keyPath:"id",autoIncrement:!0}).createIndex("submitted","submitted",{unique:!1}),g.info("Logs store created"))}})}async log(e,t,s="PLAYER",r=null){if(!this.db){console.warn("[LogReporter] Database not initialized, dropping log entry");return}["error","warning","audit","info","debug"].includes(e)||(e="info");const o={level:e,message:t,category:s,timestamp:new Date,submitted:0};r&&(r.alertType&&(o.alertType=r.alertType),r.eventType&&(o.eventType=r.eventType));try{await this._saveLog(o)}catch(a){throw console.error("[LogReporter] Failed to save log entry:",a),a}}async reportFault(e,t,s=3e5){const r=this._reportedFaults.get(e);r&&Date.now()-r<s||(this._reportedFaults.set(e,Date.now()),await this.log("error",t,"event",{alertType:"Player Fault",eventType:e}),g.info(`Fault reported: ${e} - ${t}`))}async getFaultsForSubmission(e=10){return this.db?new Promise((t,s)=>{const a=this.db.transaction([h],"readonly").objectStore(h).index("submitted").openCursor(IDBKeyRange.only(0)),c=[];a.onsuccess=l=>{const u=l.target.result;u&&c.length<e?(u.value.alertType==="Player Fault"&&c.push(u.value),u.continue()):t(c)},a.onerror=()=>{g.error("Failed to retrieve faults:",a.error),s(new Error(`Failed to retrieve faults: ${a.error}`))}}):[]}async error(e,t="PLAYER"){return this.log("error",e,t)}async audit(e,t="PLAYER"){return this.log("audit",e,t)}async info(e,t="PLAYER"){return this.log("info",e,t)}async debug(e,t="PLAYER"){return this.log("debug",e,t)}_queryByIndex(e,t,s,r){return new Promise((n,o)=>{const l=this.db.transaction([e],"readonly").objectStore(e).index(t).openCursor(s),u=[];l.onsuccess=y=>{const p=y.target.result;p&&u.length<r?(u.push(p.value),p.continue()):n(u)},l.onerror=()=>o(new Error(`Index query failed: ${l.error}`))})}_deleteByIds(e,t){return new Promise((s,r)=>{const n=this.db.transaction([e],"readwrite"),o=n.objectStore(e);let a=0;for(const c of t)if(c.id){const l=o.delete(c.id);l.onsuccess=()=>{a++},l.onerror=()=>{g.error(`Failed to delete ${c.id}:`,l.error)}}n.oncomplete=()=>s(a),n.onerror=()=>r(new Error(`Delete failed: ${n.error}`))})}async getLogsForSubmission(e=50){if(!this.db)return g.warn("Logs database not initialized"),[];const t=await this._queryByIndex(h,"submitted",IDBKeyRange.only(0),e);return g.debug(`Retrieved ${t.length} unsubmitted logs (limit: ${e})`),t}async _countUnsubmitted(){return new Promise(e=>{try{const n=this.db.transaction([h],"readonly").objectStore(h).index("submitted").count(IDBKeyRange.only(0));n.onsuccess=()=>e(n.result),n.onerror=()=>e(0)}catch{e(0)}})}async clearSubmittedLogs(e){if(!this.db||!(e!=null&&e.length))return;const t=await this._deleteByIds(h,e);g.debug(`Deleted ${t} submitted logs`)}async getAllLogs(){return this.db?new Promise((e,t)=>{const n=this.db.transaction([h],"readonly").objectStore(h).getAll();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{g.error("Failed to get all logs:",n.error),t(new Error(`Failed to get all logs: ${n.error}`))}}):(g.warn("Logs database not initialized"),[])}async clearAllLogs(){if(!this.db){g.warn("Logs database not initialized");return}return new Promise((e,t)=>{const n=this.db.transaction([h],"readwrite").objectStore(h).clear();n.onsuccess=()=>{g.debug("Cleared all logs"),e()},n.onerror=()=>{g.error("Failed to clear all logs:",n.error),t(new Error(`Failed to clear logs: ${n.error}`))}})}async _saveLog(e){return new Promise((t,s)=>{const n=this.db.transaction([h],"readwrite").objectStore(h),o=n.add(e);o.onsuccess=()=>{t(o.result)},o.onerror=()=>{o.error.name==="QuotaExceededError"?(console.warn("[LogReporter] IndexedDB quota exceeded - cleaning old logs"),this._cleanOldLogs().then(()=>{const a=n.add(e);a.onsuccess=()=>t(a.result),a.onerror=()=>s(a.error)}).catch(s)):s(o.error)}})}async _cleanOldLogs(){if(this.db)return new Promise((e,t)=>{const r=this.db.transaction([h],"readwrite").objectStore(h),o=r.index("submitted").openCursor(1),a=[];o.onsuccess=c=>{const l=c.target.result;l&&a.length<100?(a.push(l.value.id),l.continue()):(a.forEach(u=>{r.delete(u)}),console.log(`[LogReporter] Cleaned ${a.length} old logs due to quota`),e())},o.onerror=()=>{console.error("[LogReporter] Failed to clean old logs:",o.error),t(o.error)}})}}function E(i){return!i||i.length===0?"<logs></logs>":`<logs>
5
- ${i.map(t=>{const s=v(t.timestamp),r=t.level==="error"||t.level==="audit"?t.level:"audit",n=[`date="${f(s)}"`,`category="${f(r)}"`];t.alertType&&n.push(`alertType="${f(t.alertType)}"`),t.eventType&&n.push(`eventType="${f(t.eventType)}"`);const o=f(t.thread||"main"),a=f(t.method||t.category||"PLAYER"),c=f(t.message),l=f(String(t.scheduleId||"0"));return` <log ${n.join(" ")}>
6
- <thread>${o}</thread>
7
- <method>${a}</method>
8
- <message>${c}</message>
9
- <scheduleID>${l}</scheduleID>
10
- </log>`}).join(`
11
- `)}
12
- </logs>`}function R(i){return!i||i.length===0?"[]":JSON.stringify(i.map(e=>({code:e.eventType||"UNKNOWN",reason:e.message||"",date:v(e.timestamp),layoutId:e.scheduleId||0})))}function v(i){i instanceof Date||(i=new Date(i));const e=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),s=String(i.getDate()).padStart(2,"0"),r=String(i.getHours()).padStart(2,"0"),n=String(i.getMinutes()).padStart(2,"0"),o=String(i.getSeconds()).padStart(2,"0");return`${e}-${t}-${s} ${r}:${n}:${o}`}function f(i){return typeof i!="string"?i:i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}const T=_.version;export{B as LogReporter,I as StatsCollector,T as VERSION,R as formatFaults,E as formatLogs,q as formatStats};
13
- //# sourceMappingURL=index-DjPsw-Gr.js.map