@xiboplayer/pwa 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -3
- package/dist/assets/cms-api-Cqh1b8je.js +5 -0
- package/dist/assets/cms-api-Cqh1b8je.js.map +1 -0
- package/dist/assets/html2canvas.esm-CBrSDip1.js +23 -0
- package/dist/assets/html2canvas.esm-CBrSDip1.js.map +1 -0
- package/dist/assets/index-B0OWmZE0.js +2 -0
- package/dist/assets/index-B0OWmZE0.js.map +1 -0
- package/dist/assets/index-BTXprUS4.js +2 -0
- package/dist/assets/index-BTXprUS4.js.map +1 -0
- package/dist/assets/index-BnvZsfuZ.js +13 -0
- package/dist/assets/index-BnvZsfuZ.js.map +1 -0
- package/dist/assets/index-D6Ae3Fn0.js +2 -0
- package/dist/assets/index-D6Ae3Fn0.js.map +1 -0
- package/dist/assets/index-DbujXivg.js +2 -0
- package/dist/assets/index-DbujXivg.js.map +1 -0
- package/dist/assets/index-DpqLcm3c.js +2 -0
- package/dist/assets/index-DpqLcm3c.js.map +1 -0
- package/dist/assets/index-EMv3lAGt.js +2 -0
- package/dist/assets/index-EMv3lAGt.js.map +1 -0
- package/dist/assets/index-ghvCSzf2.js +2 -0
- package/dist/assets/index-ghvCSzf2.js.map +1 -0
- package/dist/assets/index-kE0POfeq.js +2 -0
- package/dist/assets/index-kE0POfeq.js.map +1 -0
- package/dist/assets/main-BoQ7K6cl.js +649 -0
- package/dist/assets/main-BoQ7K6cl.js.map +1 -0
- package/dist/assets/modulepreload-polyfill-B5Qt9EMX.js +2 -0
- package/dist/assets/modulepreload-polyfill-B5Qt9EMX.js.map +1 -0
- package/dist/assets/pdf-BnPRJEQ6.js +13 -0
- package/dist/assets/pdf-BnPRJEQ6.js.map +1 -0
- package/dist/assets/setup-DteaE4RV.js +2 -0
- package/dist/assets/setup-DteaE4RV.js.map +1 -0
- package/dist/assets/sync-manager-WxSlmw-C.js +2 -0
- package/dist/assets/sync-manager-WxSlmw-C.js.map +1 -0
- package/dist/assets/widget-html-D8OwlTop.js +2 -0
- package/dist/assets/widget-html-D8OwlTop.js.map +1 -0
- package/dist/assets/xmds-client-BPdCcQeh.js +16 -0
- package/dist/assets/xmds-client-BPdCcQeh.js.map +1 -0
- package/dist/index.html +131 -0
- package/dist/pdf.worker.min.mjs +21 -0
- package/dist/setup.html +372 -0
- package/dist/sw-pwa.js +2 -0
- package/dist/sw-pwa.js.map +1 -0
- package/dist/sw.test.js +271 -0
- package/package.json +22 -7
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./modulepreload-polyfill-B5Qt9EMX.js";import{b as t,C}from"./cms-api-Cqh1b8je.js";import{R as b,X as B}from"./xmds-client-BPdCcQeh.js";const S=document.getElementById("setup-form"),u=document.getElementById("error"),c=document.getElementById("submit-btn"),h=document.getElementById("phase-setup"),w=document.getElementById("phase-waiting"),f=document.getElementById("countdown"),k=document.getElementById("waiting-display-name"),A=document.getElementById("btn-back"),x=document.getElementById("success-flash"),p=t.hardwareKey;document.getElementById("hw-key-display").textContent=p;document.getElementById("hw-key-waiting").textContent=p;let d=null,l=null,I=15,i=null;async function g(){if(i)return i;try{const e=new b(t);await e.registerDisplay(),console.log("[Setup] Using REST transport"),i=e}catch(e){console.log("[Setup] REST unavailable, using XMDS/SOAP:",e.message),i=new B(t)}return i}function E(e){h.classList.remove("active"),w.classList.remove("active"),e.classList.add("active")}function D(e){u.textContent=e,u.style.display="block"}function K(){u.style.display="none"}function m(){let e=I;f.textContent=e,clearInterval(l),l=setInterval(()=>{e--,f.textContent=Math.max(0,e),e<=0&&clearInterval(l)},1e3)}function y(){x.classList.add("active"),setTimeout(()=>{window.location.href="./index.html"},800)}async function P(){try{const n=await(await g()).registerDisplay();if(console.log("[Setup] Poll result:",n.code,n.message),n.code==="READY"){clearInterval(d),clearInterval(l),y();return}m()}catch(e){console.warn("[Setup] Poll failed:",e.message),m()}}function v(e){k.textContent=e,E(w),m(),d=setInterval(P,I*1e3)}function R(){clearInterval(d),clearInterval(l),d=null}async function z(e,n){const a=document.getElementById("api-client-id").value.trim(),o=document.getElementById("api-client-secret").value.trim();if(!a||!o)return!1;try{const s=new C({baseUrl:e,clientId:a,clientSecret:o});await s.authenticate();const r=await s.findDisplay(n);return r?r.licensed===1?(console.log("[Setup] Display already authorized"),!0):(await s.authorizeDisplay(r.displayId),console.log("[Setup] Display auto-authorized via API!"),t.apiClientId=a,t.apiClientSecret=o,!0):(console.log("[Setup] Display not found via API (may not be registered yet)"),!1)}catch(s){return console.warn("[Setup] Auto-authorize failed:",s.message),!1}}t.isConfigured()&&(document.getElementById("cms-address").value=t.cmsAddress,document.getElementById("cms-key").value=t.cmsKey,document.getElementById("display-name").value=t.displayName);t.apiClientId&&(document.getElementById("api-client-id").value=t.apiClientId,document.getElementById("api-client-secret").value=t.apiClientSecret||"");S.addEventListener("submit",async e=>{e.preventDefault(),K();const n=document.getElementById("cms-address").value.trim().replace(/\/$/,""),a=document.getElementById("cms-key").value.trim(),o=document.getElementById("display-name").value.trim();t.cmsAddress=n,t.cmsKey=a,t.displayName=o,L(t.hardwareKey);try{c.textContent="Connecting...",c.disabled=!0,i=null;const s=await g();if((await s.registerDisplay()).code==="READY")y();else{if(c.textContent="Authorizing...",await z(n,p)&&(await s.registerDisplay()).code==="READY"){y();return}v(o)}}catch(s){D(`Connection failed: ${s.message}`),c.textContent="Connect",c.disabled=!1}});A.addEventListener("click",()=>{R(),E(h),c.textContent="Connect",c.disabled=!1});async function L(e){try{const n=indexedDB.open("xibo-hw-backup",1);n.onupgradeneeded=()=>{const a=n.result;a.objectStoreNames.contains("keys")||a.createObjectStore("keys")},n.onsuccess=()=>{const a=n.result,o=a.transaction("keys","readwrite");o.objectStore("keys").put(e,"hardwareKey"),o.oncomplete=()=>a.close()}}catch(n){console.warn("[Setup] IndexedDB backup failed:",n)}}c.disabled=!1;c.textContent="Connect";t.isConfigured()&&(async()=>{try{(await(await g()).registerDisplay()).code==="READY"?window.location.href="./index.html":v(t.displayName)}catch{console.log("[Setup] Auto-check failed, showing form")}})();
|
|
2
|
+
//# sourceMappingURL=setup-DteaE4RV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"setup-DteaE4RV.js","sources":["../../setup.html?html-proxy&index=1.js"],"sourcesContent":["\n import { config, CmsApiClient } from '@xiboplayer/utils';\n import { RestClient, XmdsClient } from '@xiboplayer/xmds';\n\n // ── Elements ──\n const form = document.getElementById('setup-form');\n const errorEl = document.getElementById('error');\n const submitBtn = document.getElementById('submit-btn');\n const phaseSetup = document.getElementById('phase-setup');\n const phaseWaiting = document.getElementById('phase-waiting');\n const countdownEl = document.getElementById('countdown');\n const waitingNameEl = document.getElementById('waiting-display-name');\n const btnBack = document.getElementById('btn-back');\n const successFlash = document.getElementById('success-flash');\n\n // Show hardware key\n const hwKey = config.hardwareKey;\n document.getElementById('hw-key-display').textContent = hwKey;\n document.getElementById('hw-key-waiting').textContent = hwKey;\n\n // ── State ──\n let pollTimer = null;\n let countdownTimer = null;\n let pollSeconds = 15;\n\n // ── Transport: try REST first, fall back to SOAP ──\n let transport = null;\n async function getTransport() {\n if (transport) return transport;\n try {\n const rest = new RestClient(config);\n await rest.registerDisplay();\n console.log('[Setup] Using REST transport');\n transport = rest;\n } catch (e) {\n console.log('[Setup] REST unavailable, using XMDS/SOAP:', e.message);\n transport = new XmdsClient(config);\n }\n return transport;\n }\n\n // ── Helpers ──\n function showPhase(phase) {\n phaseSetup.classList.remove('active');\n phaseWaiting.classList.remove('active');\n phase.classList.add('active');\n }\n\n function showError(msg) {\n errorEl.textContent = msg;\n errorEl.style.display = 'block';\n }\n\n function hideError() {\n errorEl.style.display = 'none';\n }\n\n function startCountdown() {\n let remaining = pollSeconds;\n countdownEl.textContent = remaining;\n clearInterval(countdownTimer);\n countdownTimer = setInterval(() => {\n remaining--;\n countdownEl.textContent = Math.max(0, remaining);\n if (remaining <= 0) clearInterval(countdownTimer);\n }, 1000);\n }\n\n function showSuccess() {\n successFlash.classList.add('active');\n setTimeout(() => {\n window.location.href = './index.html';\n }, 800);\n }\n\n // ── Authorization Polling ──\n async function checkAuthorization() {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n console.log('[Setup] Poll result:', result.code, result.message);\n\n if (result.code === 'READY') {\n // Authorized!\n clearInterval(pollTimer);\n clearInterval(countdownTimer);\n showSuccess();\n return;\n }\n\n // Still waiting — restart countdown\n startCountdown();\n } catch (error) {\n console.warn('[Setup] Poll failed:', error.message);\n startCountdown();\n }\n }\n\n function startPolling(displayName) {\n waitingNameEl.textContent = displayName;\n showPhase(phaseWaiting);\n startCountdown();\n pollTimer = setInterval(checkAuthorization, pollSeconds * 1000);\n }\n\n function stopPolling() {\n clearInterval(pollTimer);\n clearInterval(countdownTimer);\n pollTimer = null;\n }\n\n // ── Auto-authorize via CMS API ──\n async function tryAutoAuthorize(cmsAddress, hardwareKey) {\n const clientId = document.getElementById('api-client-id').value.trim();\n const clientSecret = document.getElementById('api-client-secret').value.trim();\n if (!clientId || !clientSecret) return false;\n\n try {\n const api = new CmsApiClient({ baseUrl: cmsAddress, clientId, clientSecret });\n await api.authenticate();\n\n const display = await api.findDisplay(hardwareKey);\n if (!display) {\n console.log('[Setup] Display not found via API (may not be registered yet)');\n return false;\n }\n\n if (display.licensed === 1) {\n console.log('[Setup] Display already authorized');\n return true;\n }\n\n // Auto-authorize\n await api.authorizeDisplay(display.displayId);\n console.log('[Setup] Display auto-authorized via API!');\n\n // Save API credentials for future use\n config.apiClientId = clientId;\n config.apiClientSecret = clientSecret;\n\n return true;\n } catch (error) {\n console.warn('[Setup] Auto-authorize failed:', error.message);\n return false;\n }\n }\n\n // ── Pre-fill if already configured ──\n if (config.isConfigured()) {\n document.getElementById('cms-address').value = config.cmsAddress;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n }\n // Pre-fill API credentials if saved\n if (config.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.apiClientSecret || '';\n }\n\n // ── Form Submit ──\n form.addEventListener('submit', async (e) => {\n e.preventDefault();\n hideError();\n\n const cmsAddress = document.getElementById('cms-address').value.trim().replace(/\\/$/, '');\n const cmsKey = document.getElementById('cms-key').value.trim();\n const displayName = document.getElementById('display-name').value.trim();\n\n // Save config\n config.cmsAddress = cmsAddress;\n config.cmsKey = cmsKey;\n config.displayName = displayName;\n\n // Also backup hardware key to IndexedDB for stability\n backupHardwareKey(config.hardwareKey);\n\n // Test connection\n try {\n submitBtn.textContent = 'Connecting...';\n submitBtn.disabled = true;\n\n // Try REST first, fall back to SOAP\n transport = null; // reset transport for fresh detection\n const client = await getTransport();\n const result = await client.registerDisplay();\n\n if (result.code === 'READY') {\n showSuccess();\n } else {\n // Try auto-authorize via CMS API if credentials provided\n submitBtn.textContent = 'Authorizing...';\n const autoAuthed = await tryAutoAuthorize(cmsAddress, hwKey);\n\n if (autoAuthed) {\n // Verify registration\n const recheck = await client.registerDisplay();\n if (recheck.code === 'READY') {\n showSuccess();\n return;\n }\n }\n\n // Not authorized yet — switch to polling phase\n startPolling(displayName);\n }\n } catch (error) {\n showError(`Connection failed: ${error.message}`);\n submitBtn.textContent = 'Connect';\n submitBtn.disabled = false;\n }\n });\n\n // ── Back button ──\n btnBack.addEventListener('click', () => {\n stopPolling();\n showPhase(phaseSetup);\n submitBtn.textContent = 'Connect';\n submitBtn.disabled = false;\n });\n\n // ── IndexedDB hardware key backup ──\n async function backupHardwareKey(key) {\n try {\n const req = indexedDB.open('xibo-hw-backup', 1);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains('keys')) {\n db.createObjectStore('keys');\n }\n };\n req.onsuccess = () => {\n const db = req.result;\n const tx = db.transaction('keys', 'readwrite');\n tx.objectStore('keys').put(key, 'hardwareKey');\n tx.oncomplete = () => db.close();\n };\n } catch (e) {\n console.warn('[Setup] IndexedDB backup failed:', e);\n }\n }\n\n // ── Enable submit ──\n submitBtn.disabled = false;\n submitBtn.textContent = 'Connect';\n\n // ── Auto-resume polling if already registered but not authorized ──\n if (config.isConfigured()) {\n (async () => {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n if (result.code === 'READY') {\n window.location.href = './index.html';\n } else {\n // Not authorized — go straight to polling\n startPolling(config.displayName);\n }\n } catch (e) {\n // Connection failed, show form\n console.log('[Setup] Auto-check failed, showing form');\n }\n })();\n }\n "],"names":["form","errorEl","submitBtn","phaseSetup","phaseWaiting","countdownEl","waitingNameEl","btnBack","successFlash","hwKey","config","pollTimer","countdownTimer","pollSeconds","transport","getTransport","rest","RestClient","XmdsClient","showPhase","phase","showError","msg","hideError","startCountdown","remaining","showSuccess","checkAuthorization","result","error","startPolling","displayName","stopPolling","tryAutoAuthorize","cmsAddress","hardwareKey","clientId","clientSecret","api","CmsApiClient","display","cmsKey","backupHardwareKey","client","key","req","db","tx","e"],"mappings":"8IAKI,MAAMA,EAAO,SAAS,eAAe,YAAY,EAC3CC,EAAU,SAAS,eAAe,OAAO,EACzCC,EAAY,SAAS,eAAe,YAAY,EAChDC,EAAa,SAAS,eAAe,aAAa,EAClDC,EAAe,SAAS,eAAe,eAAe,EACtDC,EAAc,SAAS,eAAe,WAAW,EACjDC,EAAgB,SAAS,eAAe,sBAAsB,EAC9DC,EAAU,SAAS,eAAe,UAAU,EAC5CC,EAAe,SAAS,eAAe,eAAe,EAGtDC,EAAQC,EAAO,YACrB,SAAS,eAAe,gBAAgB,EAAE,YAAcD,EACxD,SAAS,eAAe,gBAAgB,EAAE,YAAcA,EAGxD,IAAIE,EAAY,KACZC,EAAiB,KACjBC,EAAc,GAGdC,EAAY,KAChB,eAAeC,GAAe,CAC5B,GAAID,EAAW,OAAOA,EACtB,GAAI,CACF,MAAME,EAAO,IAAIC,EAAWP,CAAM,EAClC,MAAMM,EAAK,gBAAe,EAC1B,QAAQ,IAAI,8BAA8B,EAC1CF,EAAYE,CACd,OAAS,EAAG,CACV,QA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Y,CAEV,QAAQ,IAAI,yCAAyC,CACvD,CACF,GAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const i="xibo-sync";class n{constructor(e){this.displayId=e.displayId,this.syncConfig=e.syncConfig,this.isLead=e.syncConfig.isLead,this.switchDelay=e.syncConfig.syncSwitchDelay||750,this.videoPauseDelay=e.syncConfig.syncVideoPauseDelay||100,this.onLayoutChange=e.onLayoutChange||(()=>{}),this.onLayoutShow=e.onLayoutShow||(()=>{}),this.onVideoStart=e.onVideoStart||(()=>{}),this.channel=null,this.followers=new Map,this._heartbeatTimer=null,this._cleanupTimer=null,this._readyResolve=null,this._pendingLayoutId=null,this._started=!1,this._tag=this.isLead?"[Sync:LEAD]":"[Sync:FOLLOW]"}start(){if(!this._started){if(this._started=!0,typeof BroadcastChannel>"u"){console.warn(this._tag,"BroadcastChannel not available — sync disabled");return}this.channel=new BroadcastChannel(i),this.channel.onmessage=e=>this._handleMessage(e.data),this._heartbeatTimer=setInterval(()=>this._sendHeartbeat(),5e3),this._sendHeartbeat(),this.isLead&&(this._cleanupTimer=setInterval(()=>this._cleanupStaleFollowers(),5e3)),console.log(this._tag,"Started. DisplayId:",this.displayId)}}stop(){this._started&&(this._started=!1,this._heartbeatTimer&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=null),this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null),this.channel&&(this.channel.close(),this.channel=null),this.followers.clear(),console.log(this._tag,"Stopped"))}async requestLayoutChange(e){if(!this.isLead){console.warn(this._tag,"requestLayoutChange called on follower — ignoring");return}e=String(e),this._pendingLayoutId=e;for(const[,s]of this.followers)s.ready=!1,s.readyLayoutId=null;const t=Date.now()+this.switchDelay;console.log(this._tag,`Requesting layout change: ${e} (show at ${new Date(t).toISOString()}, ${this.followers.size} followers)`),this._send({type:"layout-change",layoutId:e,showAt:t,displayId:this.displayId}),this.followers.size>0&&await this._waitForFollowersReady(e);const a=t-Date.now();a>0&&await new Promise(s=>setTimeout(s,a)),console.log(this._tag,`Sending layout-show: ${e}`),this._send({type:"layout-show",layoutId:e,displayId:this.displayId}),this.onLayoutShow(e),this._pendingLayoutId=null}async requestVideoStart(e,t){this.isLead&&(await new Promise(a=>setTimeout(a,this.videoPauseDelay)),this._send({type:"video-start",layoutId:String(e),regionId:t,displayId:this.displayId}),this.onVideoStart(String(e),t))}reportReady(e){e=String(e),console.log(this._tag,`Reporting ready for layout ${e}`),this._send({type:"layout-ready",layoutId:e,displayId:this.displayId})}_handleMessage(e){if(e.displayId!==this.displayId)switch(e.type){case"heartbeat":this._handleHeartbeat(e);break;case"layout-change":this.isLead||(console.log(this._tag,`Layout change requested: ${e.layoutId}`),this.onLayoutChange(e.layoutId,e.showAt));break;case"layout-ready":this.isLead&&this._handleFollowerReady(e);break;case"layout-show":this.isLead||(console.log(this._tag,`Layout show signal: ${e.layoutId}`),this.onLayoutShow(e.layoutId));break;case"video-start":this.isLead||(console.log(this._tag,`Video start signal: ${e.layoutId} region ${e.regionId}`),this.onVideoStart(e.layoutId,e.regionId));break;default:console.warn(this._tag,"Unknown message type:",e.type)}}_handleHeartbeat(e){const t=this.followers.get(e.displayId);t?t.lastSeen=Date.now():(this.followers.set(e.displayId,{lastSeen:Date.now(),ready:!1,readyLayoutId:null,role:e.role||"unknown"}),console.log(this._tag,`Follower joined: ${e.displayId} (${this.followers.size} total)`))}_handleFollowerReady(e){const t=this.followers.get(e.displayId);t?(t.ready=!0,t.readyLayoutId=e.layoutId,t.lastSeen=Date.now()):this.followers.set(e.displayId,{lastSeen:Date.now(),ready:!0,readyLayoutId:e.layoutId}),console.log(this._tag,`Follower ${e.displayId} ready for layout ${e.layoutId}`),this._pendingLayoutId===e.layoutId&&this._readyResolve&&this._allFollowersReady(e.layoutId)&&(console.log(this._tag,"All followers ready"),this._readyResolve(),this._readyResolve=null)}_allFollowersReady(e){for(const[,t]of this.followers)if(!(Date.now()-t.lastSeen>15e3)&&(!t.ready||t.readyLayoutId!==e))return!1;return!0}_waitForFollowersReady(e){return new Promise(t=>{if(this._allFollowersReady(e)){t();return}this._readyResolve=t,setTimeout(()=>{if(this._readyResolve===t){const a=[];for(const[s,o]of this.followers)(!o.ready||o.readyLayoutId!==e)&&a.push(s);console.warn(this._tag,`Ready timeout — proceeding without: ${a.join(", ")}`),this._readyResolve=null,t()}},1e4)})}_sendHeartbeat(){this._send({type:"heartbeat",displayId:this.displayId,role:this.isLead?"lead":"follower",timestamp:Date.now()})}_cleanupStaleFollowers(){const e=Date.now();for(const[t,a]of this.followers)e-a.lastSeen>15e3&&(console.log(this._tag,`Removing stale follower: ${t} (last seen ${Math.round((e-a.lastSeen)/1e3)}s ago)`),this.followers.delete(t))}_send(e){if(this.channel)try{this.channel.postMessage(e)}catch(t){console.error(this._tag,"Failed to send:",t)}}getStatus(){return{started:this._started,isLead:this.isLead,displayId:this.displayId,followers:this.followers.size,pendingLayoutId:this._pendingLayoutId,followerDetails:Array.from(this.followers.entries()).map(([e,t])=>({displayId:e,lastSeen:t.lastSeen,ready:t.ready,readyLayoutId:t.readyLayoutId,stale:Date.now()-t.lastSeen>15e3}))}}}export{n as SyncManager};
|
|
2
|
+
//# sourceMappingURL=sync-manager-WxSlmw-C.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sync-manager-WxSlmw-C.js","sources":["../../node_modules/.pnpm/@xiboplayer+sync@0.3.7/node_modules/@xiboplayer/sync/src/sync-manager.js"],"sourcesContent":["/**\n * SyncManager - Multi-display synchronization via BroadcastChannel\n *\n * Coordinates layout transitions across multiple browser tabs/windows\n * on the same machine (video wall, multi-monitor setups).\n *\n * Protocol:\n * Lead Follower(s)\n * ──── ──────────\n * layout-change(layoutId, showAt) → receives, loads layout\n * ← layout-ready(layoutId, displayId)\n * (waits for all followers ready)\n * layout-show(layoutId) → shows layout simultaneously\n *\n * Heartbeat:\n * All nodes broadcast heartbeat every 5s.\n * Lead tracks active followers. If a follower goes silent for 15s,\n * it's considered offline and excluded from ready-wait.\n *\n * @module @xiboplayer/sync\n */\n\n/**\n * @typedef {Object} SyncConfig\n * @property {string} syncGroup - \"lead\" or leader's LAN IP\n * @property {number} syncPublisherPort - TCP port (unused in browser, kept for compat)\n * @property {number} syncSwitchDelay - Delay in ms before showing new content\n * @property {number} syncVideoPauseDelay - Delay in ms before unpausing video\n * @property {boolean} isLead - Whether this display is the leader\n */\n\nconst CHANNEL_NAME = 'xibo-sync';\nconst HEARTBEAT_INTERVAL = 5000; // Send heartbeat every 5s\nconst FOLLOWER_TIMEOUT = 15000; // Consider follower offline after 15s silence\nconst READY_TIMEOUT = 10000; // Max wait for followers to be ready\n\nexport class SyncManager {\n /**\n * @param {Object} options\n * @param {string} options.displayId - This display's unique hardware key\n * @param {SyncConfig} options.syncConfig - Sync configuration from RegisterDisplay\n * @param {Function} [options.onLayoutChange] - Called when lead requests layout change\n * @param {Function} [options.onLayoutShow] - Called when lead gives show signal\n * @param {Function} [options.onVideoStart] - Called when lead gives video start signal\n */\n constructor(options) {\n this.displayId = options.displayId;\n this.syncConfig = options.syncConfig;\n this.isLead = options.syncConfig.isLead;\n this.switchDelay = options.syncConfig.syncSwitchDelay || 750;\n this.videoPauseDelay = options.syncConfig.syncVideoPauseDelay || 100;\n\n // Callbacks\n this.onLayoutChange = options.onLayoutChange || (() => {});\n this.onLayoutShow = options.onLayoutShow || (() => {});\n this.onVideoStart = options.onVideoStart || (() => {});\n\n // State\n this.channel = null;\n this.followers = new Map(); // displayId → { lastSeen, ready }\n this._heartbeatTimer = null;\n this._cleanupTimer = null;\n this._readyResolve = null; // Resolve function for current ready-wait\n this._pendingLayoutId = null; // Layout we're waiting for readiness on\n this._started = false;\n\n // Log prefix for clarity in multi-tab console\n this._tag = this.isLead ? '[Sync:LEAD]' : '[Sync:FOLLOW]';\n }\n\n /**\n * Start the sync manager (opens BroadcastChannel, begins heartbeats)\n */\n start() {\n if (this._started) return;\n this._started = true;\n\n if (typeof BroadcastChannel === 'undefined') {\n console.warn(this._tag, 'BroadcastChannel not available — sync disabled');\n return;\n }\n\n this.channel = new BroadcastChannel(CHANNEL_NAME);\n this.channel.onmessage = (event) => this._handleMessage(event.data);\n\n // Start heartbeat\n this._heartbeatTimer = setInterval(() => this._sendHeartbeat(), HEARTBEAT_INTERVAL);\n this._sendHeartbeat(); // Send initial heartbeat immediately\n\n // Lead: periodically clean up stale followers\n if (this.isLead) {\n this._cleanupTimer = setInterval(() => this._cleanupStaleFollowers(), HEARTBEAT_INTERVAL);\n }\n\n console.log(this._tag, 'Started. DisplayId:', this.displayId);\n }\n\n /**\n * Stop the sync manager\n */\n stop() {\n if (!this._started) return;\n this._started = false;\n\n if (this._heartbeatTimer) {\n clearInterval(this._heartbeatTimer);\n this._heartbeatTimer = null;\n }\n if (this._cleanupTimer) {\n clearInterval(this._cleanupTimer);\n this._cleanupTimer = null;\n }\n if (this.channel) {\n this.channel.close();\n this.channel = null;\n }\n\n this.followers.clear();\n console.log(this._tag, 'Stopped');\n }\n\n // ── Lead API ──────────────────────────────────────────────────────\n\n /**\n * [Lead only] Request all displays to change to a layout.\n * Waits for followers to report ready, then sends show signal.\n *\n * @param {string|number} layoutId - Layout to change to\n * @returns {Promise<void>} Resolves when show signal is sent\n */\n async requestLayoutChange(layoutId) {\n if (!this.isLead) {\n console.warn(this._tag, 'requestLayoutChange called on follower — ignoring');\n return;\n }\n\n layoutId = String(layoutId);\n this._pendingLayoutId = layoutId;\n\n // Mark all followers as not-ready for this layout\n for (const [, follower] of this.followers) {\n follower.ready = false;\n follower.readyLayoutId = null;\n }\n\n const showAt = Date.now() + this.switchDelay;\n\n console.log(this._tag, `Requesting layout change: ${layoutId} (show at ${new Date(showAt).toISOString()}, ${this.followers.size} followers)`);\n\n // Broadcast layout-change to all followers\n this._send({\n type: 'layout-change',\n layoutId,\n showAt,\n displayId: this.displayId,\n });\n\n // Wait for all active followers to report ready (or timeout)\n if (this.followers.size > 0) {\n await this._waitForFollowersReady(layoutId);\n }\n\n // Apply switch delay (remaining time from showAt)\n const remaining = showAt - Date.now();\n if (remaining > 0) {\n await new Promise(resolve => setTimeout(resolve, remaining));\n }\n\n // Send show signal\n console.log(this._tag, `Sending layout-show: ${layoutId}`);\n this._send({\n type: 'layout-show',\n layoutId,\n displayId: this.displayId,\n });\n\n // Also trigger on self (lead shows too)\n this.onLayoutShow(layoutId);\n\n this._pendingLayoutId = null;\n }\n\n /**\n * [Lead only] Signal followers to start video playback.\n *\n * @param {string|number} layoutId - Layout containing the video\n * @param {string} regionId - Region with the video widget\n */\n async requestVideoStart(layoutId, regionId) {\n if (!this.isLead) return;\n\n // Wait videoPauseDelay before unpausing\n await new Promise(resolve => setTimeout(resolve, this.videoPauseDelay));\n\n this._send({\n type: 'video-start',\n layoutId: String(layoutId),\n regionId,\n displayId: this.displayId,\n });\n\n // Also trigger on self\n this.onVideoStart(String(layoutId), regionId);\n }\n\n // ── Follower API ──────────────────────────────────────────────────\n\n /**\n * [Follower only] Report that layout is loaded and ready to show.\n * Called by platform layer after layout content is prepared.\n *\n * @param {string|number} layoutId - Layout that is ready\n */\n reportReady(layoutId) {\n layoutId = String(layoutId);\n\n console.log(this._tag, `Reporting ready for layout ${layoutId}`);\n\n this._send({\n type: 'layout-ready',\n layoutId,\n displayId: this.displayId,\n });\n }\n\n // ── Message handling ──────────────────────────────────────────────\n\n /** @private */\n _handleMessage(msg) {\n // Ignore our own messages\n if (msg.displayId === this.displayId) return;\n\n switch (msg.type) {\n case 'heartbeat':\n this._handleHeartbeat(msg);\n break;\n\n case 'layout-change':\n // Follower: lead is requesting a layout change\n if (!this.isLead) {\n console.log(this._tag, `Layout change requested: ${msg.layoutId}`);\n this.onLayoutChange(msg.layoutId, msg.showAt);\n }\n break;\n\n case 'layout-ready':\n // Lead: follower reports ready\n if (this.isLead) {\n this._handleFollowerReady(msg);\n }\n break;\n\n case 'layout-show':\n // Follower: lead says show now\n if (!this.isLead) {\n console.log(this._tag, `Layout show signal: ${msg.layoutId}`);\n this.onLayoutShow(msg.layoutId);\n }\n break;\n\n case 'video-start':\n // Follower: lead says start video\n if (!this.isLead) {\n console.log(this._tag, `Video start signal: ${msg.layoutId} region ${msg.regionId}`);\n this.onVideoStart(msg.layoutId, msg.regionId);\n }\n break;\n\n default:\n console.warn(this._tag, 'Unknown message type:', msg.type);\n }\n }\n\n /** @private */\n _handleHeartbeat(msg) {\n const existing = this.followers.get(msg.displayId);\n if (existing) {\n existing.lastSeen = Date.now();\n } else {\n // New follower discovered\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: false,\n readyLayoutId: null,\n role: msg.role || 'unknown',\n });\n console.log(this._tag, `Follower joined: ${msg.displayId} (${this.followers.size} total)`);\n }\n }\n\n /** @private */\n _handleFollowerReady(msg) {\n const follower = this.followers.get(msg.displayId);\n if (!follower) {\n // Late joiner — register them\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: true,\n readyLayoutId: msg.layoutId,\n });\n } else {\n follower.ready = true;\n follower.readyLayoutId = msg.layoutId;\n follower.lastSeen = Date.now();\n }\n\n console.log(this._tag, `Follower ${msg.displayId} ready for layout ${msg.layoutId}`);\n\n // Check if all followers are now ready\n if (this._pendingLayoutId === msg.layoutId && this._readyResolve) {\n if (this._allFollowersReady(msg.layoutId)) {\n console.log(this._tag, 'All followers ready');\n this._readyResolve();\n this._readyResolve = null;\n }\n }\n }\n\n /** @private */\n _allFollowersReady(layoutId) {\n for (const [, follower] of this.followers) {\n // Skip stale followers\n if (Date.now() - follower.lastSeen > FOLLOWER_TIMEOUT) continue;\n if (!follower.ready || follower.readyLayoutId !== layoutId) {\n return false;\n }\n }\n return true;\n }\n\n /** @private */\n _waitForFollowersReady(layoutId) {\n return new Promise((resolve) => {\n // Already all ready?\n if (this._allFollowersReady(layoutId)) {\n resolve();\n return;\n }\n\n this._readyResolve = resolve;\n\n // Timeout: don't wait forever for unresponsive followers\n setTimeout(() => {\n if (this._readyResolve === resolve) {\n const notReady = [];\n for (const [id, f] of this.followers) {\n if (!f.ready || f.readyLayoutId !== layoutId) {\n notReady.push(id);\n }\n }\n console.warn(this._tag, `Ready timeout — proceeding without: ${notReady.join(', ')}`);\n this._readyResolve = null;\n resolve();\n }\n }, READY_TIMEOUT);\n });\n }\n\n // ── Heartbeat & cleanup ───────────────────────────────────────────\n\n /** @private */\n _sendHeartbeat() {\n this._send({\n type: 'heartbeat',\n displayId: this.displayId,\n role: this.isLead ? 'lead' : 'follower',\n timestamp: Date.now(),\n });\n }\n\n /** @private */\n _cleanupStaleFollowers() {\n const now = Date.now();\n for (const [id, follower] of this.followers) {\n if (now - follower.lastSeen > FOLLOWER_TIMEOUT) {\n console.log(this._tag, `Removing stale follower: ${id} (last seen ${Math.round((now - follower.lastSeen) / 1000)}s ago)`);\n this.followers.delete(id);\n }\n }\n }\n\n /** @private */\n _send(msg) {\n if (!this.channel) return;\n try {\n this.channel.postMessage(msg);\n } catch (e) {\n console.error(this._tag, 'Failed to send:', e);\n }\n }\n\n // ── Status ────────────────────────────────────────────────────────\n\n /**\n * Get current sync status\n * @returns {Object}\n */\n getStatus() {\n return {\n started: this._started,\n isLead: this.isLead,\n displayId: this.displayId,\n followers: this.followers.size,\n pendingLayoutId: this._pendingLayoutId,\n followerDetails: Array.from(this.followers.entries()).map(([id, f]) => ({\n displayId: id,\n lastSeen: f.lastSeen,\n ready: f.ready,\n readyLayoutId: f.readyLayoutId,\n stale: Date.now() - f.lastSeen > FOLLOWER_TIMEOUT,\n })),\n };\n }\n}\n"],"names":["CHANNEL_NAME","SyncManager","options","event","layoutId","follower","showAt","remaining","resolve","regionId","msg","existing","notReady","id","f","now","e"],"mappings":"AA+BA,MAAMA,EAAe,YAKd,MAAMC,CAAY,CASvB,YAAYC,EAAS,CACnB,KAAK,UAAYA,EAAQ,UACzB,KAAK,WAAaA,EAAQ,WAC1B,KAAK,OAASA,EAAQ,WAAW,OACjC,KAAK,YAAcA,EAAQ,WAAW,iBAAmB,IACzD,KAAK,gBAAkBA,EAAQ,WAAW,qBAAuB,IAG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Q,YAAYA,CAAG,CAC9B,OAASM,EAAG,CACV,QAAQ,MAAM,KAAK,KAAM,kBAAmBA,CAAC,CAC/C,CACF,CAQA,WAAY,CACV,MAAO,CACL,QAAS,KAAK,SACd,OAAQ,KAAK,OACb,UAAW,KAAK,UAChB,UAAW,KAAK,UAAU,KAC1B,gBAAiB,KAAK,iBACtB,gBAAiB,MAAM,KAAK,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC,CAACH,EAAIC,CAAC,KAAO,CACtE,UAAWD,EACX,SAAUC,EAAE,SACZ,MAAOA,EAAE,MACT,cAAeA,EAAE,cACjB,MAAO,KAAK,IAAG,EAAKA,EAAE,SAAW,IACzC,EAAQ,CACR,CACE,CACF","x_google_ignoreList":[0]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{c as R}from"./cms-api-Cqh1b8je.js";class H{constructor(){this.events=new Map}on(e,t){this.events.has(e)||this.events.set(e,[]),this.events.get(e).push(t)}once(e,t){const s=(...i)=>{t(...i),this.off(e,s)};this.on(e,s)}off(e,t){if(!this.events.has(e))return;const s=this.events.get(e),i=s.indexOf(t);i!==-1&&s.splice(i,1)}emit(e,...t){if(!this.events.has(e))return;const s=this.events.get(e).slice();for(const i of s)i(...t)}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}const J=R("Cache"),ee="xibo-media-v1",te=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";class se{constructor(){this.dependants=new Map}getCacheKey(e,t,s=null){return`${te}/cache/${e}/${s||t}`}addDependant(e,t){const s=String(e);this.dependants.has(s)||this.dependants.set(s,new Set),this.dependants.get(s).add(String(t))}removeLayoutDependants(e){const t=String(e),s=[];for(const[i,n]of this.dependants)n.delete(t),n.size===0&&(this.dependants.delete(i),s.push(i));return s.length>0&&J.info(`${s.length} media files orphaned after layout ${e} removed:`,s),s}isMediaReferenced(e){const t=this.dependants.get(String(e));return t?t.size>0:!1}async clearAll(){await caches.delete(ee),this.dependants.clear()}}const pe=new se,c=R("CacheProxy"),Q=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";class O extends H{constructor(){super(),this.controller=null,this.fetchReady=!1,this.fetchReadyPromise=null,this.fetchReadyResolve=null}async init(){if(this.fetchReadyPromise=new Promise(e=>{this.fetchReadyResolve=e}),navigator.serviceWorker.addEventListener("message",e=>{var t;((t=e.data)==null?void 0:t.type)==="SW_READY"&&(c.info("Received SW_READY signal - fetch handler is ready"),this.fetchReady=!0,this.fetchReadyResolve())}),"serviceWorker"in navigator){const e=await navigator.serviceWorker.getRegistration();if(e&&e.active&&e.active.state==="activated"){c.info("Using active Service Worker (controller not required)"),this.controller=navigator.serviceWorker.controller||e.active,this.controller.postMessage({type:"PING"}),c.info("Service Worker backend initialized, waiting for fetch readiness...");return}if(await navigator.serviceWorker.ready,this.controller=navigator.serviceWorker.controller,!this.controller)throw new Error("Service Worker not controlling page");this.controller.postMessage({type:"PING"}),c.info("Service Worker backend initialized, waiting for fetch readiness...")}else throw new Error("Service Worker not supported")}async getFile(e,t){this.fetchReady||(c.debug(`Waiting for SW fetch handler to be ready before fetching ${e}/${t}...`),await this.fetchReadyPromise,c.debug("SW fetch handler ready, proceeding with fetch"));const s=`${Q}/cache/${e}/${t}`;c.debug(`getFile(${e}, ${t}) → fetching ${s}`),c.debug("About to call fetch()...");try{c.debug(`Calling fetch(${s})...`);const i=await fetch(s);if(c.debug("fetch returned, status:",i.status,i.statusText),!i.ok){if(c.debug(`Response not OK (${i.status}), returning null`),i.status===404)return null;throw new Error(`Failed to get file: ${i.status}`)}c.debug("Response OK, getting blob...");const n=await i.blob();return c.debug("Got blob, size:",n.size),n}catch(i){return c.error("getFile EXCEPTION:",i),c.error("Error name:",i.name),c.error("Error message:",i.message),null}}async hasFile(e,t){this.fetchReady||await this.fetchReadyPromise;const s=`${Q}/cache/${e}/${t}`;try{return(await fetch(s,{method:"HEAD"})).ok}catch{return!1}}async requestDownload(e){if(!this.controller)throw new Error("Service Worker not available");const t=Array.isArray(e)?{files:e}:e;return new Promise((s,i)=>{const n=new MessageChannel;n.port1.onmessage=r=>{const{success:o,error:h,enqueuedCount:a,activeCount:p,queuedCount:d}=r.data;o?(c.info("Download request acknowledged:",a,"files"),c.info("Queue state:",p,"active,",d,"queued"),s()):i(new Error(h||"Service Worker download failed"))},this.controller.postMessage({type:"DOWNLOAD_FILES",data:t},[n.port2])})}async prioritizeDownload(e,t){if(this.controller)return new Promise(s=>{const i=new MessageChannel;i.port1.onmessage=n=>s(n.data),this.controller.postMessage({type:"PRIORITIZE_DOWNLOAD",data:{fileType:e,fileId:t}},[i.port2])})}async isCached(e,t){return this.hasFile(e,t)}async prioritizeLayoutFiles(e){this.controller&&this.controller.postMessage({type:"PRIORITIZE_LAYOUT_FILES",data:{mediaIds:e}})}}class fe extends H{constructor(){super(),this.backend=null,this.backendType="service-worker"}async init(){var i,n;if(!("serviceWorker"in navigator))throw new Error("Service Worker not supported - PWA requires Service Worker");c.debug("Checking Service Worker state..."),c.debug("controller =",navigator.serviceWorker.controller);const e=await navigator.serviceWorker.getRegistration();if(c.debug("registration =",e),c.debug("active =",e==null?void 0:e.active),c.debug("installing =",e==null?void 0:e.installing),c.debug("waiting =",e==null?void 0:e.waiting),e&&e.active&&!e.installing&&!e.waiting){c.info("Active Service Worker found (no updates pending)"),c.debug("SW state =",e.active.state),navigator.serviceWorker.controller||(c.debug("Not controlling yet, waiting 200ms for claim..."),await new Promise(r=>setTimeout(r,200)),c.debug("After wait, controller =",navigator.serviceWorker.controller)),this.backend=new O,await this.backend.init(),c.info("Service Worker backend ready (fast path)");return}e&&(e.installing||e.waiting)&&(c.info("New Service Worker detected, waiting for it to activate..."),c.debug("installing =",(i=e.installing)==null?void 0:i.state),c.debug("waiting =",(n=e.waiting)==null?void 0:n.state)),c.info("No active Service Worker, waiting for registration...");const t=navigator.serviceWorker.ready,s=new Promise((r,o)=>setTimeout(()=>o(new Error("Service Worker ready timeout after 10s")),1e4));try{await Promise.race([t,s]),c.debug("Service Worker ready promise resolved")}catch(r){throw c.error("Service Worker wait failed:",r),new Error("Service Worker not ready - please reload page")}await new Promise(r=>setTimeout(r,100)),c.debug("After claim wait, controller =",navigator.serviceWorker.controller),this.backend=new O,await this.backend.init(),c.info("Service Worker backend ready (slow path)")}async getFile(e,t){if(!this.backend)throw new Error("CacheProxy not initialized");return await this.backend.getFile(e,t)}async hasFile(e,t){if(!this.backend)throw new Error("CacheProxy not initialized");return await this.backend.hasFile(e,t)}async requestDownload(e){if(!this.backend)throw new Error("CacheProxy not initialized");return await this.backend.requestDownload(e)}async prioritizeDownload(e,t){var s;if((s=this.backend)!=null&&s.prioritizeDownload)return await this.backend.prioritizeDownload(e,t)}async isCached(e,t){return this.hasFile(e,t)}async prioritizeLayoutFiles(e){var t;if((t=this.backend)!=null&&t.prioritizeLayoutFiles)return await this.backend.prioritizeLayoutFiles(e)}getBackendType(){return this.backendType}isUsingServiceWorker(){return this.backendType==="service-worker"}async getAllFiles(){if(!this.backend)throw new Error("CacheProxy not initialized");return new Promise(e=>{const t=new MessageChannel;t.port1.onmessage=s=>{const{success:i,files:n}=s.data;e(i?n:[])},navigator.serviceWorker.controller.postMessage({type:"GET_ALL_FILES"},[t.port2]),setTimeout(()=>e([]),5e3)})}async deleteFiles(e){if(!this.backend)throw new Error("CacheProxy not initialized");return new Promise((t,s)=>{const i=new MessageChannel;i.port1.onmessage=n=>{const{success:r,error:o,deleted:h,total:a}=n.data;r?t({deleted:h,total:a}):s(new Error(o||"Delete failed"))},navigator.serviceWorker.controller.postMessage({type:"DELETE_FILES",data:{files:e}},[i.port2]),setTimeout(()=>t({deleted:0,total:e.length}),5e3)})}async prewarmVideoChunks(e){var s;if(!e||e.length===0)return{warmed:0,total:0};const t=(s=navigator.serviceWorker)==null?void 0:s.controller;return t?new Promise(i=>{const n=new MessageChannel;n.port1.onmessage=r=>{const{success:o,warmed:h,total:a}=r.data;i(o?{warmed:h,total:a}:{warmed:0,total:e.length})},t.postMessage({type:"PREWARM_VIDEO_CHUNKS",data:{mediaIds:e}},[n.port2]),setTimeout(()=>i({warmed:0,total:e.length}),2e3)}):{warmed:0,total:e.length}}async getDownloadProgress(){if(!this.backend)throw new Error("CacheProxy not initialized");return new Promise(e=>{const t=new MessageChannel;t.port1.onmessage=s=>{const{success:i,progress:n}=s.data;e(i?n:{})},navigator.serviceWorker.controller.postMessage({type:"GET_DOWNLOAD_PROGRESS"},[t.port2]),setTimeout(()=>e({}),1e3)})}}const l=R("Download"),ie=6,j=50*1024*1024,ne=3,oe=100*1024*1024,L=3,re=500,ae=2,N=6e5,ce=15e3;function he(u){var i,n;const t=(n=(i=(u.path||u.code||"").split(".").pop())==null?void 0:i.split("?")[0])==null?void 0:n.toLowerCase();return{mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",css:"text/css",js:"application/javascript",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",xml:"application/xml",xlf:"application/xml"}[t]||"application/octet-stream"}const f={normal:0,layout:1,high:2,urgent:3},$=Symbol("BARRIER");function S(u){try{const e=u.match(/X-Amz-Expires=(\d+)/);return e?parseInt(e[1],10):1/0}catch{return 1/0}}function K(u,e=30){const t=S(u);return t===1/0?!1:Date.now()/1e3>=t-e}function G(u){if(!u.startsWith("http"))return u;const e=typeof self<"u"?self.location:void 0;if(!e||e.hostname!=="localhost"||e.port!=="8765")return u;const t=new URL(u),s=t.origin;return`/file-proxy?cms=${encodeURIComponent(s)}&url=${encodeURIComponent(t.pathname+t.search)}`}class z{constructor(e,t={}){this.fileInfo=e,this.chunkIndex=t.chunkIndex??null,this.rangeStart=t.rangeStart??null,this.rangeEnd=t.rangeEnd??null,this.state="pending",this.blob=null,this._parentFile=null,this._priority=f.normal}getUrl(){const e=this.fileInfo.path;if(K(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return G(e)}async start(){this.state="downloading";const e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`);for(let t=1;t<=L;t++){const s=new AbortController,i=setTimeout(()=>s.abort(),N);try{const n=this.getUrl(),r={signal:s.signal};Object.keys(e).length>0&&(r.headers=e);const o=await fetch(n,r);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(n){const r=s.signal.aborted?`Timeout after ${N/1e3}s`:n.message;if(t<L){const o=re*t,h=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";l.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${h} attempt ${t}/${L} failed: ${r}. Retrying in ${o/1e3}s...`),await new Promise(a=>setTimeout(a,o))}else throw this.state="failed",s.signal.aborted?new Error(r):n}finally{clearTimeout(i)}}}}class Y{constructor(e,t={}){this.fileInfo=e,this.options=t,this.state="pending",this.tasks=[],this.completedChunks=0,this.totalChunks=0,this.totalBytes=0,this.downloadedBytes=0,this.onChunkDownloaded=null,this.skipChunks=e.skipChunks||new Set,this._contentType="application/octet-stream",this._chunkBlobs=new Map,this._runningCount=0,this._resolve=null,this._reject=null,this._promise=new Promise((s,i)=>{this._resolve=s,this._reject=i}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(K(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return G(e)}wait(){return this._promise}async prepare(e){try{this.state="preparing";const{id:t,type:s,size:i}=this.fileInfo;if(l.info("[FileDownload] Starting:",`${s}/${t}`),this.totalBytes=i&&i>0?parseInt(i):0,this._contentType=he(this.fileInfo),this.totalBytes===0){const r=this.getUrl(),o=new AbortController,h=setTimeout(()=>o.abort(),ce);try{const a=await fetch(r,{method:"HEAD",signal:o.signal});a.ok&&(this.totalBytes=parseInt(a.headers.get("Content-Length")||"0"),this._contentType=a.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(h)}}l.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const n=this.options.chunkSize||j;if(this.totalBytes>oe){const r=[];for(let d=0;d<this.totalBytes;d+=n)r.push({start:d,end:Math.min(d+n-1,this.totalBytes-1),index:r.length});this.totalChunks=r.length;const o=r.filter(d=>!this.skipChunks.has(d.index)),h=r.length-o.length;for(const d of r)this.skipChunks.has(d.index)&&(this.downloadedBytes+=d.end-d.start+1);if(o.length===0){l.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}h>0&&l.info(`[FileDownload] Resuming: ${h} chunks cached, ${o.length} to download`);const a=h>0;if(a){const d=o.sort((g,y)=>g.index-y.index);for(const g of d){const y=new z(this.fileInfo,{chunkIndex:g.index,rangeStart:g.start,rangeEnd:g.end});y._parentFile=this,y._priority=f.normal,this.tasks.push(y)}}else for(const d of o){const g=new z(this.fileInfo,{chunkIndex:d.index,rangeStart:d.start,rangeEnd:d.end});g._parentFile=this,g._priority=d.index===0||d.index===r.length-1?f.high:f.normal,this.tasks.push(g)}const p=this.tasks.filter(d=>d._priority>=f.high).length;l.info(`[FileDownload] ${s}/${t}: ${this.tasks.length} chunks`+(p>0?` (${p} priority)`:"")+(a?" (resume)":""))}else{this.totalChunks=1;const r=new z(this.fileInfo,{});r._parentFile=this,this.tasks.push(r)}e.enqueueChunkTasks(this.tasks),this.state="downloading"}catch(t){l.error("[FileDownload] Prepare failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}async onTaskComplete(e){if(this.completedChunks++,this.downloadedBytes+=e.blob.size,e.chunkIndex!=null&&this._chunkBlobs.set(e.chunkIndex,e.blob),this.options.onProgress&&this.options.onProgress(this.downloadedBytes,this.totalBytes),this.onChunkDownloaded&&e.chunkIndex!=null)try{await this.onChunkDownloaded(e.chunkIndex,e.blob,this.totalChunks)}catch(t){l.warn("[FileDownload] onChunkDownloaded callback error:",t)}if(this.completedChunks===this.tasks.length&&this.state!=="complete"){this.state="complete";const{type:t,id:s}=this.fileInfo;if(e.chunkIndex==null)l.info("[FileDownload] Complete:",`${t}/${s}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)l.info("[FileDownload] Complete:",`${t}/${s}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const i=[];for(let r=0;r<this.totalChunks;r++){const o=this._chunkBlobs.get(r);o&&i.push(o)}const n=new Blob(i,{type:this._contentType});l.info("[FileDownload] Complete:",`${t}/${s}`,`(${n.size} bytes, reassembled)`),this._resolve(n)}this._chunkBlobs.clear()}}onTaskFailed(e,t){var s;if(!(this.state==="complete"||this.state==="failed")){if((s=t.message)!=null&&s.includes("URL expired")){const i=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.warn(`[FileDownload] URL expired, dropping${i}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(n=>n!==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}`,t),this.state="failed",this._reject(t)}}}class ge{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const t=q.stableKey(e);if(this.queue.active.has(t)){const i=this.queue.active.get(t);if(e.path&&e.path!==i.fileInfo.path){const n=S(i.fileInfo.path);S(e.path)>n&&(i.fileInfo.path=e.path)}return i}const s=new Y(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(t,s),this._filesToPrepare.push(s),s}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let t=0,s=0;const i=()=>{for(;t<this._maxPreparing&&s<this._filesToPrepare.length;){const n=this._filesToPrepare[s++];t++,n.prepare(this).finally(()=>{t--,s>=this._filesToPrepare.length&&t===0?e():i()})}};this._filesToPrepare.length===0?e():i()})}_sortWithBarriers(){var r;const e=[],t=[],s=[],i=[];for(const o of this._tasks)if(o.chunkIndex==null)e.push(o);else if(o.chunkIndex===0)t.push(o);else{const h=((r=o._parentFile)==null?void 0:r.totalChunks)||0;h>1&&o.chunkIndex===h-1?s.push(o):i.push(o)}e.sort((o,h)=>{var a,p;return(((a=o._parentFile)==null?void 0:a.totalBytes)||0)-(((p=h._parentFile)==null?void 0:p.totalBytes)||0)}),i.sort((o,h)=>o.chunkIndex-h.chunkIndex);const n=[...e,...t,...s];return i.length>0&&n.push($,...i),n}}class q{constructor(e={}){this.concurrency=e.concurrency||ie,this.chunkSize=e.chunkSize||j,this.maxChunksPerFile=e.chunksPerFile||ne,this.calculateMD5=e.calculateMD5,this.onProgress=e.onProgress,this.queue=[],this.active=new Map,this._activeTasks=[],this.running=0,this._prepareQueue=[],this._preparingCount=0,this._maxPreparing=2,this.paused=!1}static stableKey(e){return`${e.type}/${e.id}`}enqueue(e){const t=q.stableKey(e);if(this.active.has(t)){const i=this.active.get(t);if(e.path&&e.path!==i.fileInfo.path){const n=S(i.fileInfo.path);S(e.path)>n&&(l.info("[DownloadQueue] Refreshing URL for",t),i.fileInfo.path=e.path)}return i}const s=new Y(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(t,s),l.info("[DownloadQueue] Enqueued:",t),this._schedulePrepare(s),s}_schedulePrepare(e){this._prepareQueue.push(e),this._processPrepareQueue()}_processPrepareQueue(){for(;this._preparingCount<this._maxPreparing&&this._prepareQueue.length>0;){const e=this._prepareQueue.shift();this._preparingCount++,e.prepare(this).finally(()=>{this._preparingCount--,this._processPrepareQueue()})}}enqueueChunkTasks(e){for(const t of e)this.queue.push(t);this._sortQueue(),l.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let t=0,s=0;for(const i of e)i===$?(this.queue.push($),s++):(this.queue.push(i),t++);l.info(`[DownloadQueue] Ordered queue: ${t} tasks, ${s} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,t)=>t._priority-e._priority)}prioritize(e,t){const s=`${e}/${t}`,i=this.active.get(s);if(!i)return l.info("[DownloadQueue] Not found:",s),!1;let n=0;for(const r of this.queue)r._parentFile===i&&r._priority<f.high&&(r._priority=f.high,n++);return this._sortQueue(),l.info("[DownloadQueue] Prioritized:",s,`(${n} tasks boosted)`),!0}prioritizeLayoutFiles(e,t=f.high){var n,r;const s=new Set(e.map(String));let i=0;for(const o of this.queue)s.has(String((n=o._parentFile)==null?void 0:n.fileInfo.id))&&o._priority<t&&(o._priority=t,i++);for(const o of this._activeTasks)s.has(String((r=o._parentFile)==null?void 0:r.fileInfo.id))&&o._priority<t&&(o._priority=t);this._sortQueue(),l.info("[DownloadQueue] Layout files prioritized:",s.size,"files,",i,"tasks boosted to",t)}urgentChunk(e,t,s){const i=`${e}/${t}`,n=this.active.get(i);if(!n)return l.info("[DownloadQueue] urgentChunk: file not active:",i,"chunk",s),!1;if(this._activeTasks.some(a=>a._parentFile===n&&a.chunkIndex===s&&a.state==="downloading")){const a=this._activeTasks.find(p=>p._parentFile===n&&p.chunkIndex===s);return a&&a._priority<f.urgent?(a._priority=f.urgent,l.info(`[DownloadQueue] URGENT: ${i} chunk ${s} (already in-flight, limiting slots)`),!0):(l.info("[DownloadQueue] urgentChunk: already urgent:",i,"chunk",s),!1)}const o=this.queue.findIndex(a=>a!==$&&a._parentFile===n&&a.chunkIndex===s);if(o===-1)return l.info("[DownloadQueue] urgentChunk: chunk not in queue:",i,"chunk",s),!1;const h=this.queue.splice(o,1)[0];return h._priority=f.urgent,this.queue.unshift(h),l.info(`[DownloadQueue] URGENT: ${i} chunk ${s} (moved to front)`),this.processQueue(),!0}processQueue(){var i;if(this.paused)return;const e=this.queue.some(n=>n!==$&&n._priority>=f.urgent)||((i=this._activeTasks)==null?void 0:i.some(n=>n._priority>=f.urgent&&n.state==="downloading")),t=e?ae:this.concurrency,s=e?f.urgent:0;for(;this.running<t&&this.queue.length>0;){const n=this.queue[0];if(n===$){if(this.running>0)break;this.queue.shift();continue}if(n._priority<s||!this._canStartTask(n)){let r=!1;for(let o=1;o<this.queue.length&&this.queue[o]!==$;o++){const h=this.queue[o];if(h._priority>=s&&this._canStartTask(h)){this.queue.splice(o,1),this._startTask(h),r=!0;break}}if(!r)break;continue}this.queue.shift(),this._startTask(n)}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 t=`${e.fileInfo.type}/${e.fileInfo.id}`,s=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.info(`[DownloadQueue] Starting: ${t}${s} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(i=>i!==e),l.info(`[DownloadQueue] Fetched: ${t}${s} (${this.running} active, ${this.queue.length} pending)`),this.processQueue(),e._parentFile.onTaskComplete(e))).catch(i=>{this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(n=>n!==e),this.processQueue(),e._parentFile.onTaskFailed(e,i)})}awaitAllPrepared(){return new Promise(e=>{const t=()=>{this._preparingCount===0&&this._prepareQueue.length===0?e():setTimeout(t,50)};t()})}removeCompleted(e){const t=this.active.get(e);t&&(t.state==="complete"||t.state==="failed")&&(this.queue=this.queue.filter(s=>s===$||s._parentFile!==t),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){const e={};for(const[t,s]of this.active.entries())e[t]={downloaded:s.downloadedBytes,total:s.totalBytes,percent:s.totalBytes>0?(s.downloadedBytes/s.totalBytes*100).toFixed(1):0,state:s.state};return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0}}class we{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,t){this.queue.prioritizeLayoutFiles(e,t),this.queue.processQueue()}urgentChunk(e,t,s){return this.queue.urgentChunk(e,t,s)}clear(){this.queue.clear()}}const _=R("CacheAnalyzer");function E(u){if(u===0)return"0 B";if(!Number.isFinite(u))return"∞";const e=["B","KB","MB","GB","TB"],t=Math.floor(Math.log(u)/Math.log(1024));return`${(u/Math.pow(1024,t)).toFixed(t>0?1:0)} ${e[t]}`}class ye{constructor(e,{threshold:t=80}={}){this.cache=e,this.threshold=t}async analyze(e){const t=await this.cache.getAllFiles(),s=await this._getStorageEstimate(),i=new Set(e.map(a=>String(a.id))),n=[],r=[];for(const a of t)if(i.has(String(a.id)))n.push(a);else if(a.type==="widget"){const p=String(a.id).split("/")[0];i.has(p)?n.push(a):r.push(a)}else r.push(a);r.sort((a,p)=>(a.cachedAt||0)-(p.cachedAt||0));const o=r.reduce((a,p)=>a+(p.size||0),0),h={timestamp:Date.now(),storage:{usage:s.usage,quota:s.quota,percent:s.quota>0?Math.round(s.usage/s.quota*100):0},files:{required:n.length,orphaned:r.length,total:t.length},orphaned:r.map(a=>({id:a.id,type:a.type,size:a.size||0,cachedAt:a.cachedAt||0})),orphanedSize:o,evicted:[],threshold:this.threshold};if(_.info(`Storage: ${E(s.usage)} / ${E(s.quota)} (${h.storage.percent}%)`),_.info(`Cache: ${n.length} required, ${r.length} orphaned (${E(o)} reclaimable)`),r.length>0)for(const a of r){const p=Date.now()-(a.cachedAt||0),d=Math.floor(p/864e5),g=Math.floor(p%864e5/36e5),y=d>0?`${d}d ago`:`${g}h ago`;_.info(` Orphaned: ${a.type}/${a.id} (${E(a.size||0)}, cached ${y})`)}if(h.storage.percent>this.threshold&&r.length>0){_.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);const a=s.usage-s.quota*this.threshold/100;h.evicted=await this._evict(r,a)}else _.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:t,quota:s}=await navigator.storage.estimate();return{usage:t||0,quota:s||1/0}}}catch(t){_.warn("Storage estimate unavailable:",t.message)}return{usage:0,quota:1/0}}async _evict(e,t){const s=[];let i=0;for(const n of e){if(i>=t)break;s.push(n),i+=n.size||0}if(s.length===0)return[];try{const n=s.map(r=>({type:r.type,id:r.id}));await this.cache.deleteFiles(n);for(const r of s)_.info(` Evicted: ${r.type}/${r.id} (${E(r.size||0)})`);_.info(`Evicted ${s.length} files, freed ${E(i)}`)}catch(n){return _.warn("Eviction failed:",n.message),[]}return s.map(n=>({id:n.id,type:n.type,size:n.size||0,cachedAt:n.cachedAt||0}))}}const w=R("Cache"),le="xibo-media-v1",v=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";async function ke(u,e,t,s){const i=`${v}/cache/widget/${u}/${e}/${t}`,n=await caches.open(le),r=`<base href="${v}/cache/media/">`;let o=s;s.includes("<head>")?o=s.replace("<head>","<head>"+r):s.includes("<HEAD>")?o=s.replace("<HEAD>","<HEAD>"+r):o=r+s;const h=/https?:\/\/[^"'\s)]+(?:xmds\.php|pwa\/file)\?[^"'\s)]*file=([^&"'\s)]+)[^"'\s)]*/g,a=[];o=o.replace(h,(y,k)=>{const m=`${v}/cache/static/${k}`;return a.push({filename:k,originalUrl:y}),w.info(`Rewrote widget URL: ${k} → ${m}`),m});const p="<style>img,video{object-position:center center}</style>";o.includes("</head>")?o=o.replace("</head>",p+"</head>"):o.includes("</HEAD>")&&(o=o.replace("</HEAD>",p+"</HEAD>")),o=o.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${v}/ic"`),w.info("Injected base tag and rewrote CMS/data URLs in widget HTML");const d=new URL(i,window.location.origin),g=new Response(o,{headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":"*"}});if(await n.put(d,g),w.info(`Stored widget HTML at ${i} (${o.length} bytes)`),a.length>0){const k=await caches.open("xibo-static-v1");await Promise.all(a.map(async({filename:m,originalUrl:X})=>{const A=`${v}/cache/static/${m}`;if(!await k.match(A))try{const b=await fetch(X);if(!b.ok){w.warn(`Failed to fetch static resource: ${m} (HTTP ${b.status})`);return}const M=m.split(".").pop().toLowerCase(),W={js:"application/javascript",css:"text/css",otf:"font/otf",ttf:"font/ttf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",svg:"image/svg+xml"}[M]||"application/octet-stream";if(M==="css"){let C=await b.text();const I=[],Z=/url\((['"]?)(https?:\/\/[^'")\s]+\?[^'")\s]*file=([^&'")\s]+\.(?:woff2?|ttf|otf|eot|svg))[^'")\s]*)\1\)/gi;C=C.replace(Z,(T,D,F,P)=>(I.push({filename:P,originalUrl:F}),w.info(`Rewrote font URL in CSS: ${P}`),`url(${D}${v}/cache/static/${encodeURIComponent(P)}${D})`)),await k.put(A,new Response(C,{headers:{"Content-Type":"text/css"}})),w.info(`Cached CSS with ${I.length} rewritten font URLs: ${m}`),await Promise.all(I.map(async({filename:T,originalUrl:D})=>{const F=`${v}/cache/static/${encodeURIComponent(T)}`;if(!await k.match(F))try{const x=await fetch(D);if(!x.ok){w.warn(`Failed to fetch font: ${T} (HTTP ${x.status})`);return}const B=await x.blob(),V=T.split(".").pop().toLowerCase(),U={otf:"font/otf",ttf:"font/ttf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",svg:"image/svg+xml"}[V]||"application/octet-stream";await k.put(F,new Response(B,{headers:{"Content-Type":U}})),w.info(`Cached font: ${T} (${U}, ${B.size} bytes)`)}catch(x){w.warn(`Failed to cache font: ${T}`,x)}}))}else{const C=await b.blob();await k.put(A,new Response(C,{headers:{"Content-Type":W}})),w.info(`Cached static resource: ${m} (${W}, ${C.size} bytes)`)}}catch(b){w.warn(`Failed to cache static resource: ${m}`,b)}}))}return i}export{$ as B,ye as C,we as D,H as E,Y as F,ge as L,fe as a,se as b,ke as c,pe as d,K as i,G as r};
|
|
2
|
+
//# sourceMappingURL=widget-html-D8OwlTop.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"widget-html-D8OwlTop.js","sources":["../../../xiboplayer/packages/utils/src/event-emitter.js","../../../xiboplayer/packages/cache/src/cache.js","../../../xiboplayer/packages/cache/src/cache-proxy.js","../../../xiboplayer/packages/cache/src/download-manager.js","../../../xiboplayer/packages/cache/src/cache-analyzer.js","../../../xiboplayer/packages/cache/src/widget-html.js"],"sourcesContent":["/**\n * Simple EventEmitter implementation\n * Compatible with both browser and Node.js\n */\n\nexport class EventEmitter {\n constructor() {\n this.events = new Map();\n }\n\n /**\n * Register event listener\n * @param {string} event - Event name\n * @param {Function} callback - Callback function\n */\n on(event, callback) {\n if (!this.events.has(event)) {\n this.events.set(event, []);\n }\n this.events.get(event).push(callback);\n }\n\n /**\n * Register one-time event listener\n * @param {string} event - Event name\n * @param {Function} callback - Callback function\n */\n once(event, callback) {\n const wrapper = (...args) => {\n callback(...args);\n this.off(event, wrapper);\n };\n this.on(event, wrapper);\n }\n\n /**\n * Remove event listener\n * @param {string} event - Event name\n * @param {Function} callback - Callback function\n */\n off(event, callback) {\n if (!this.events.has(event)) return;\n\n const listeners = this.events.get(event);\n const index = listeners.indexOf(callback);\n if (index !== -1) {\n listeners.splice(index, 1);\n }\n }\n\n /**\n * Emit event\n * @param {string} event - Event name\n * @param {...any} args - Arguments to pass to listeners\n */\n emit(event, ...args) {\n if (!this.events.has(event)) return;\n\n // Make a copy to handle listeners that remove themselves during emission\n const listeners = this.events.get(event).slice();\n for (const listener of listeners) {\n listener(...args);\n }\n }\n\n /**\n * Remove all listeners for an event\n * @param {string} event - Event name (optional, removes all if not specified)\n */\n removeAllListeners(event) {\n if (event) {\n this.events.delete(event);\n } else {\n this.events.clear();\n }\n }\n}\n","/**\n * CacheManager - Dependant tracking and cache lifecycle\n *\n * After the cache unification, all downloads and file retrieval go through\n * the Service Worker (via CacheProxy). This class retains:\n * - Dependant tracking (which layouts reference which media)\n * - Cache key generation\n * - Full cache clearing\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\nconst CACHE_NAME = 'xibo-media-v1';\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\n */\n async clearAll() {\n await caches.delete(CACHE_NAME);\n this.dependants.clear();\n }\n}\n\nexport const cacheManager = new CacheManager();\n","/**\n * CacheProxy - Service Worker cache interface\n *\n * Provides a proxy to Service Worker for background downloads and caching.\n * Service Worker MUST be available - no fallback (committed to SW architecture).\n *\n * Architecture:\n * ┌─────────────────────────────────────────┐\n * │ CacheProxy (Service Worker Only) │\n * │ - Waits for Service Worker ready │\n * │ - Routes all requests to SW │\n * │ - No fallback to direct cache │\n * └─────────────────────────────────────────┘\n * ↓\n * ┌──────────────────┐\n * │ ServiceWorker │\n * │ Backend │\n * │ - postMessage │\n * │ - Background DL │\n * └──────────────────┘\n *\n * Usage:\n * const proxy = new CacheProxy();\n * await proxy.init(); // Waits for SW to be ready\n *\n * const blob = await proxy.getFile('media', '123');\n * await proxy.requestDownload([{ id, type, path, md5 }]);\n * const isCached = await proxy.isCached('layout', '456');\n */\n\nimport { EventEmitter, createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('CacheProxy');\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 * ServiceWorkerBackend - Uses Service Worker for downloads and caching\n */\nclass ServiceWorkerBackend extends EventEmitter {\n constructor() {\n super();\n this.controller = null;\n this.fetchReady = false;\n this.fetchReadyPromise = null;\n this.fetchReadyResolve = null;\n }\n\n async init() {\n // Create promise for fetch readiness (resolved when SW sends SW_READY)\n this.fetchReadyPromise = new Promise(resolve => {\n this.fetchReadyResolve = resolve;\n });\n\n // Listen for SW_READY message\n navigator.serviceWorker.addEventListener('message', (event) => {\n if (event.data?.type === 'SW_READY') {\n log.info('Received SW_READY signal - fetch handler is ready');\n this.fetchReady = true;\n this.fetchReadyResolve();\n }\n });\n\n // Get the active Service Worker (don't require controller)\n if ('serviceWorker' in navigator) {\n const registration = await navigator.serviceWorker.getRegistration();\n\n // Use active SW if it exists (controller not required!)\n if (registration && registration.active && registration.active.state === 'activated') {\n log.info('Using active Service Worker (controller not required)');\n this.controller = navigator.serviceWorker.controller || registration.active;\n\n // Request readiness signal from SW\n this.controller.postMessage({ type: 'PING' });\n\n log.info('Service Worker backend initialized, waiting for fetch readiness...');\n return;\n }\n\n // Fall back to waiting for ready\n await navigator.serviceWorker.ready;\n this.controller = navigator.serviceWorker.controller;\n\n if (!this.controller) {\n throw new Error('Service Worker not controlling page');\n }\n\n // Request readiness signal from SW\n this.controller.postMessage({ type: 'PING' });\n\n log.info('Service Worker backend initialized, waiting for fetch readiness...');\n } else {\n throw new Error('Service Worker not supported');\n }\n }\n\n /**\n * Get file from cache (via Service Worker)\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<Blob|null>}\n */\n async getFile(type, id) {\n // Wait for SW fetch handler to be ready (eliminates race condition)\n if (!this.fetchReady) {\n log.debug(`Waiting for SW fetch handler to be ready before fetching ${type}/${id}...`);\n await this.fetchReadyPromise;\n log.debug(`SW fetch handler ready, proceeding with fetch`);\n }\n\n // Service Worker serves files via fetch interception\n // Construct cache URL and fetch it\n const cacheUrl = `${BASE}/cache/${type}/${id}`;\n\n log.debug(`getFile(${type}, ${id}) → fetching ${cacheUrl}`);\n log.debug(`About to call fetch()...`);\n\n try {\n log.debug(`Calling fetch(${cacheUrl})...`);\n const response = await fetch(cacheUrl);\n log.debug(`fetch returned, status:`, response.status, response.statusText);\n\n if (!response.ok) {\n log.debug(`Response not OK (${response.status}), returning null`);\n if (response.status === 404) {\n return null; // Not cached\n }\n throw new Error(`Failed to get file: ${response.status}`);\n }\n\n log.debug(`Response OK, getting blob...`);\n const blob = await response.blob();\n log.debug(`Got blob, size:`, blob.size);\n return blob;\n } catch (error) {\n log.error('getFile EXCEPTION:', error);\n log.error('Error name:', error.name);\n log.error('Error message:', error.message);\n return null;\n }\n }\n\n /**\n * Check if file exists in cache (supports both whole files and chunked storage)\n * Service Worker's CacheManager.fileExists() handles the logic internally\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<boolean>}\n */\n async hasFile(type, id) {\n // Wait for SW fetch handler to be ready\n if (!this.fetchReady) {\n await this.fetchReadyPromise;\n }\n\n const cacheUrl = `${BASE}/cache/${type}/${id}`;\n\n try {\n // SW's handleRequest uses CacheManager.fileExists() internally\n // Returns 200 for both whole files and chunked files (via metadata check)\n const response = await fetch(cacheUrl, { method: 'HEAD' });\n return response.ok;\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Request downloads from Service Worker (non-blocking)\n * @param {Object|Array} payload - Either { layouts: [{ layoutId, mediaFiles }] } or flat Array of files\n * @returns {Promise<void>}\n */\n async requestDownload(payload) {\n if (!this.controller) {\n throw new Error('Service Worker not available');\n }\n\n // Support both grouped and flat payload (backward compat)\n const data = Array.isArray(payload)\n ? { files: payload }\n : payload;\n\n return new Promise((resolve, reject) => {\n const messageChannel = new MessageChannel();\n\n messageChannel.port1.onmessage = (event) => {\n const { success, error, enqueuedCount, activeCount, queuedCount } = event.data;\n if (success) {\n log.info('Download request acknowledged:', enqueuedCount, 'files');\n log.info('Queue state:', activeCount, 'active,', queuedCount, 'queued');\n resolve();\n } else {\n reject(new Error(error || 'Service Worker download failed'));\n }\n };\n\n this.controller.postMessage(\n {\n type: 'DOWNLOAD_FILES',\n data\n },\n [messageChannel.port2]\n );\n });\n }\n\n /**\n * Tell SW to prioritize downloading a specific file\n * Moves it to the front of the download queue if still queued\n * @param {string} fileType - 'media' or 'layout'\n * @param {string} fileId - File ID\n */\n async prioritizeDownload(fileType, fileId) {\n if (!this.controller) return;\n\n return new Promise((resolve) => {\n const messageChannel = new MessageChannel();\n messageChannel.port1.onmessage = (event) => resolve(event.data);\n this.controller.postMessage(\n { type: 'PRIORITIZE_DOWNLOAD', data: { fileType, fileId } },\n [messageChannel.port2]\n );\n });\n }\n\n /**\n * Check if file is cached (delegates to hasFile for consistent fetchReady handling)\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<boolean>}\n */\n async isCached(type, id) {\n return this.hasFile(type, id);\n }\n\n /**\n * Prioritize layout files — reorder queue and hold other downloads until done.\n * @param {string[]} mediaIds - Media IDs needed by the current layout\n */\n async prioritizeLayoutFiles(mediaIds) {\n if (!this.controller) return;\n this.controller.postMessage({ type: 'PRIORITIZE_LAYOUT_FILES', data: { mediaIds } });\n }\n}\n\n// DirectCacheBackend removed - Service Worker only architecture\n\n/**\n * CacheProxy - Service Worker only interface\n */\nexport class CacheProxy extends EventEmitter {\n constructor() {\n super();\n this.backend = null;\n this.backendType = 'service-worker';\n }\n\n /**\n * Initialize proxy - WAITS for Service Worker to be ready\n */\n async init() {\n if (!('serviceWorker' in navigator)) {\n throw new Error('Service Worker not supported - PWA requires Service Worker');\n }\n\n log.debug('Checking Service Worker state...');\n log.debug('controller =', navigator.serviceWorker.controller);\n\n // Check if SW registration exists (better than checking controller)\n const registration = await navigator.serviceWorker.getRegistration();\n log.debug('registration =', registration);\n log.debug('active =', registration?.active);\n log.debug('installing =', registration?.installing);\n log.debug('waiting =', registration?.waiting);\n\n // FAST PATH: If active SW exists AND no new SW is installing, use it immediately\n if (registration && registration.active && !registration.installing && !registration.waiting) {\n log.info('Active Service Worker found (no updates pending)');\n log.debug('SW state =', registration.active.state);\n\n // If not controlling yet, give it a moment to claim page\n if (!navigator.serviceWorker.controller) {\n log.debug('Not controlling yet, waiting 200ms for claim...');\n await new Promise(resolve => setTimeout(resolve, 200));\n log.debug('After wait, controller =', navigator.serviceWorker.controller);\n }\n\n // Use the active SW (even if controller is still null - it will work)\n this.backend = new ServiceWorkerBackend();\n await this.backend.init();\n log.info('Service Worker backend ready (fast path)');\n return;\n }\n\n // If there's a new SW installing/waiting, wait for it instead of using old one\n if (registration && (registration.installing || registration.waiting)) {\n log.info('New Service Worker detected, waiting for it to activate...');\n log.debug('installing =', registration.installing?.state);\n log.debug('waiting =', registration.waiting?.state);\n }\n\n // SLOW PATH: No active SW, wait for registration (fresh install)\n log.info('No active Service Worker, waiting for registration...');\n\n // Wait with timeout\n const swReady = navigator.serviceWorker.ready;\n const timeout = new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Service Worker ready timeout after 10s')), 10000)\n );\n\n try {\n await Promise.race([swReady, timeout]);\n log.debug('Service Worker ready promise resolved');\n } catch (error) {\n log.error('Service Worker wait failed:', error);\n throw new Error('Service Worker not ready - please reload page');\n }\n\n // Wait for SW to claim page\n await new Promise(resolve => setTimeout(resolve, 100));\n log.debug('After claim wait, controller =', navigator.serviceWorker.controller);\n\n // Controller not required - we can use registration.active instead\n // This handles the case where SW is active but hasn't set controller yet (timing issue)\n this.backend = new ServiceWorkerBackend();\n await this.backend.init();\n log.info('Service Worker backend ready (slow path)');\n }\n\n /**\n * Get file from cache\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<Blob|null>}\n */\n async getFile(type, id) {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n return await this.backend.getFile(type, id);\n }\n\n /**\n * Check if file exists in cache (for streaming - no blob creation)\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<boolean>}\n */\n async hasFile(type, id) {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n return await this.backend.hasFile(type, id);\n }\n\n /**\n * Request file downloads\n * Service Worker: Non-blocking (downloads in background)\n * Direct cache: Blocking (downloads sequentially)\n *\n * @param {Array} files - Array of { id, type, path, md5 }\n * @returns {Promise<void>}\n */\n async requestDownload(files) {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n return await this.backend.requestDownload(files);\n }\n\n /**\n * Prioritize downloading a specific file (move to front of queue)\n * @param {string} fileType - 'media' or 'layout'\n * @param {string} fileId - File ID\n */\n async prioritizeDownload(fileType, fileId) {\n if (!this.backend?.prioritizeDownload) return;\n return await this.backend.prioritizeDownload(fileType, fileId);\n }\n\n /**\n * Check if file is cached (delegates to hasFile for consistent fetchReady handling)\n * @param {string} type - 'media', 'layout', 'widget'\n * @param {string} id - File ID\n * @returns {Promise<boolean>}\n */\n async isCached(type, id) {\n return this.hasFile(type, id);\n }\n\n /**\n * Prioritize layout files — reorder queue and hold other downloads until done.\n * @param {string[]} mediaIds - Media IDs needed by the current layout\n */\n async prioritizeLayoutFiles(mediaIds) {\n if (!this.backend?.prioritizeLayoutFiles) return;\n return await this.backend.prioritizeLayoutFiles(mediaIds);\n }\n\n /**\n * Get backend type for debugging\n * @returns {string} 'service-worker' or 'direct'\n */\n getBackendType() {\n return this.backendType;\n }\n\n /**\n * Check if Service Worker is being used\n * @returns {boolean}\n */\n isUsingServiceWorker() {\n return this.backendType === 'service-worker';\n }\n\n /**\n * Get all cached files from Service Worker\n * @returns {Promise<Array<{id: string, type: string, size: number, cachedAt: number}>>}\n */\n async getAllFiles() {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n\n return new Promise((resolve) => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (event) => {\n const { success, files } = event.data;\n resolve(success ? files : []);\n };\n\n navigator.serviceWorker.controller.postMessage(\n { type: 'GET_ALL_FILES' },\n [channel.port2]\n );\n\n setTimeout(() => resolve([]), 5000);\n });\n }\n\n /**\n * Delete files from cache (purge obsolete media)\n * @param {Array<{type: string, id: string}>} files - Files to delete\n * @returns {Promise<{deleted: number, total: number}>}\n */\n async deleteFiles(files) {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n\n return new Promise((resolve, reject) => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (event) => {\n const { success, error, deleted, total } = event.data;\n if (success) {\n resolve({ deleted, total });\n } else {\n reject(new Error(error || 'Delete failed'));\n }\n };\n\n navigator.serviceWorker.controller.postMessage(\n { type: 'DELETE_FILES', data: { files } },\n [channel.port2]\n );\n\n setTimeout(() => resolve({ deleted: 0, total: files.length }), 5000);\n });\n }\n\n /**\n * Pre-warm video chunks into SW BlobCache for faster playback startup.\n * Loads first and last chunks into memory so moov atom probing is instant.\n * @param {number[]} mediaIds - Media file IDs to pre-warm\n * @returns {Promise<{warmed: number, total: number}>}\n */\n async prewarmVideoChunks(mediaIds) {\n if (!mediaIds || mediaIds.length === 0) return { warmed: 0, total: 0 };\n\n const controller = navigator.serviceWorker?.controller;\n if (!controller) return { warmed: 0, total: mediaIds.length };\n\n return new Promise((resolve) => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (event) => {\n const { success, warmed, total } = event.data;\n resolve(success ? { warmed, total } : { warmed: 0, total: mediaIds.length });\n };\n\n controller.postMessage(\n { type: 'PREWARM_VIDEO_CHUNKS', data: { mediaIds } },\n [channel.port2]\n );\n\n // Don't block layout rendering for more than 2s\n setTimeout(() => resolve({ warmed: 0, total: mediaIds.length }), 2000);\n });\n }\n\n /**\n * Get download progress from Service Worker\n * @returns {Promise<Object>} Progress info for all active downloads\n */\n async getDownloadProgress() {\n if (!this.backend) {\n throw new Error('CacheProxy not initialized');\n }\n\n return new Promise((resolve) => {\n const channel = new MessageChannel();\n\n channel.port1.onmessage = (event) => {\n const { success, progress } = event.data;\n resolve(success ? progress : {});\n };\n\n navigator.serviceWorker.controller.postMessage(\n { type: 'GET_DOWNLOAD_PROGRESS' },\n [channel.port2]\n );\n\n // Timeout after 1 second\n setTimeout(() => resolve({}), 1000);\n });\n }\n}\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';\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 MAX_RETRIES = 3;\nconst RETRY_DELAY_MS = 500; // Fast: 500ms, 1s, 1.5s → total ~3s\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 * Rewrite an absolute CMS URL through the local proxy when running behind\n * the proxy server (Chromium kiosk or Electron).\n * Detection: SW/window on localhost:8765 = proxy mode.\n */\nexport function rewriteUrlForProxy(url) {\n if (!url.startsWith('http')) return url;\n const loc = typeof self !== 'undefined' ? self.location : undefined;\n if (!loc || loc.hostname !== 'localhost' || loc.port !== '8765') return url;\n const parsed = new URL(url);\n const cmsOrigin = parsed.origin;\n return `/file-proxy?cms=${encodeURIComponent(cmsOrigin)}&url=${encodeURIComponent(parsed.pathname + parsed.search)}`;\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 }\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 rewriteUrlForProxy(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\n for (let attempt = 1; attempt <= MAX_RETRIES; 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 < MAX_RETRIES) {\n const delay = RETRY_DELAY_MS * attempt;\n const chunkLabel = this.chunkIndex != null ? ` chunk ${this.chunkIndex}` : '';\n log.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${chunkLabel} attempt ${attempt}/${MAX_RETRIES} 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 rewriteUrlForProxy(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 if (this.totalBytes === 0) {\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\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 if (idSet.has(String(t._parentFile?.fileInfo.id)) && t._priority < priority) {\n t._priority = priority;\n boosted++;\n }\n }\n for (const t of this._activeTasks) {\n if (idSet.has(String(t._parentFile?.fileInfo.id)) && 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 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 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 }\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","/**\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 CacheProxy (postMessage to SW) — 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('./cache-proxy.js').CacheProxy} cache - CacheProxy 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.getAllFiles();\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 {\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 CacheProxy.deleteFiles() which routes to SW.\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.deleteFiles(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","/**\n * Widget HTML caching — preprocesses widget HTML and stores in Cache API\n *\n * Handles:\n * - <base> tag injection for relative path resolution\n * - CMS signed URL → local cache path rewriting\n * - CSS font URL rewriting and font file caching\n * - Interactive Control hostAddress rewriting\n * - CSS object-position fix for CMS template alignment\n *\n * Runs on the main thread (needs window.location for URL construction).\n * Uses Cache API directly — the SW also serves from the same cache.\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst log = createLogger('Cache');\nconst CACHE_NAME = 'xibo-media-v1';\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 cache for iframe loading\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\n */\nexport async function cacheWidgetHtml(layoutId, regionId, mediaId, html) {\n const cacheKey = `${BASE}/cache/widget/${layoutId}/${regionId}/${mediaId}`;\n const cache = await caches.open(CACHE_NAME);\n\n // Inject <base> tag to fix relative paths for widget dependencies\n // Widget HTML has relative paths like \"bundle.min.js\" that should resolve to cache/media/\n const baseTag = `<base href=\"${BASE}/cache/media/\">`;\n let modifiedHtml = html;\n\n // Insert base tag after <head> opening tag\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 // No head tag, prepend base tag\n modifiedHtml = baseTag + html;\n }\n\n // Rewrite absolute CMS signed URLs to local cache paths\n // Matches: https://cms/xmds.php?file=... or https://cms/pwa/file?file=...\n // These absolute URLs bypass the <base> tag entirely, causing slow CMS fetches\n const cmsUrlRegex = /https?:\\/\\/[^\"'\\s)]+(?:xmds\\.php|pwa\\/file)\\?[^\"'\\s)]*file=([^&\"'\\s)]+)[^\"'\\s)]*/g;\n const staticResources = [];\n modifiedHtml = modifiedHtml.replace(cmsUrlRegex, (match, filename) => {\n const localPath = `${BASE}/cache/static/${filename}`;\n staticResources.push({ filename, originalUrl: match });\n log.info(`Rewrote widget URL: ${filename} → ${localPath}`);\n return localPath;\n });\n\n // Inject CSS default for object-position to suppress CMS template warning\n // CMS global-elements.xml uses {{alignId}} {{valignId}} which produces\n // invalid CSS (empty value) when alignment is not configured\n const cssFixTag = '<style>img,video{object-position:center center}</style>';\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 // Rewrite Interactive Control hostAddress to SW-interceptable path\n // The IC library uses hostAddress + '/info', '/trigger', etc.\n // Original: hostAddress: \"https://cms.example.com\" → XHR to /info goes to CMS (fails)\n // Rewritten: hostAddress: \"/player/pwa/ic\" → XHR to /player/pwa/ic/info (intercepted by SW)\n modifiedHtml = modifiedHtml.replace(\n /hostAddress\\s*:\\s*[\"']https?:\\/\\/[^\"']+[\"']/g,\n `hostAddress: \"${BASE}/ic\"`\n );\n\n log.info('Injected base tag and rewrote CMS/data URLs in widget HTML');\n\n // Construct full URL for cache storage\n const cacheUrl = new URL(cacheKey, window.location.origin);\n\n const response = new Response(modifiedHtml, {\n headers: {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Access-Control-Allow-Origin': '*'\n }\n });\n\n await cache.put(cacheUrl, response);\n log.info(`Stored widget HTML at ${cacheKey} (${modifiedHtml.length} bytes)`);\n\n // Fetch and cache static resources (shared Cache API - accessible from main thread and SW)\n if (staticResources.length > 0) {\n const STATIC_CACHE_NAME = 'xibo-static-v1';\n const staticCache = await caches.open(STATIC_CACHE_NAME);\n\n await Promise.all(staticResources.map(async ({ filename, originalUrl }) => {\n const staticKey = `${BASE}/cache/static/${filename}`;\n const existing = await staticCache.match(staticKey);\n if (existing) return; // Already cached\n\n try {\n const resp = await fetch(originalUrl);\n if (!resp.ok) {\n log.warn(`Failed to fetch static resource: ${filename} (HTTP ${resp.status})`);\n return;\n }\n\n const ext = filename.split('.').pop().toLowerCase();\n const contentType = {\n 'js': 'application/javascript',\n 'css': 'text/css',\n 'otf': 'font/otf', 'ttf': 'font/ttf',\n 'woff': 'font/woff', 'woff2': 'font/woff2',\n 'eot': 'application/vnd.ms-fontobject',\n 'svg': 'image/svg+xml'\n }[ext] || 'application/octet-stream';\n\n // For CSS files, rewrite font URLs and cache referenced font files\n if (ext === 'css') {\n let cssText = await resp.text();\n const fontResources = [];\n const fontUrlRegex = /url\\((['\"]?)(https?:\\/\\/[^'\")\\s]+\\?[^'\")\\s]*file=([^&'\")\\s]+\\.(?:woff2?|ttf|otf|eot|svg))[^'\")\\s]*)\\1\\)/gi;\n cssText = cssText.replace(fontUrlRegex, (_match, quote, fullUrl, fontFilename) => {\n fontResources.push({ filename: fontFilename, originalUrl: fullUrl });\n log.info(`Rewrote font URL in CSS: ${fontFilename}`);\n return `url(${quote}${BASE}/cache/static/${encodeURIComponent(fontFilename)}${quote})`;\n });\n\n await staticCache.put(staticKey, new Response(cssText, {\n headers: { 'Content-Type': 'text/css' }\n }));\n log.info(`Cached CSS with ${fontResources.length} rewritten font URLs: ${filename}`);\n\n // Fetch and cache referenced font files\n await Promise.all(fontResources.map(async ({ filename: fontFile, originalUrl: fontUrl }) => {\n const fontKey = `${BASE}/cache/static/${encodeURIComponent(fontFile)}`;\n const existingFont = await staticCache.match(fontKey);\n if (existingFont) return; // Already cached (by SW or previous widget)\n\n try {\n const fontResp = await fetch(fontUrl);\n if (!fontResp.ok) {\n log.warn(`Failed to fetch font: ${fontFile} (HTTP ${fontResp.status})`);\n return;\n }\n const fontBlob = await fontResp.blob();\n const fontExt = fontFile.split('.').pop().toLowerCase();\n const fontContentType = {\n 'otf': 'font/otf', 'ttf': 'font/ttf',\n 'woff': 'font/woff', 'woff2': 'font/woff2',\n 'eot': 'application/vnd.ms-fontobject',\n 'svg': 'image/svg+xml'\n }[fontExt] || 'application/octet-stream';\n\n await staticCache.put(fontKey, new Response(fontBlob, {\n headers: { 'Content-Type': fontContentType }\n }));\n log.info(`Cached font: ${fontFile} (${fontContentType}, ${fontBlob.size} bytes)`);\n } catch (fontErr) {\n log.warn(`Failed to cache font: ${fontFile}`, fontErr);\n }\n }));\n } else {\n const blob = await resp.blob();\n await staticCache.put(staticKey, new Response(blob, {\n headers: { 'Content-Type': contentType }\n }));\n log.info(`Cached static resource: ${filename} (${contentType}, ${blob.size} bytes)`);\n }\n } catch (error) {\n log.warn(`Failed to cache static resource: ${filename}`, error);\n }\n }));\n }\n\n return cacheKey;\n}\n"],"names":["EventEmitter","event","callback","wrapper","args","listeners","index","listener","log","createLogger","CACHE_NAME","BASE","CacheManager","type","id","filename","mediaId","layoutId","key","lid","orphaned","layouts","cacheManager","ServiceWorkerBackend","resolve","_a","registration","cacheUrl","response","blob","error","payload","data","reject","messageChannel","success","enqueuedCount","activeCount","queuedCount","fileType","fileId","mediaIds","CacheProxy","_b","swReady","timeout","_","files","channel","deleted","total","controller","warmed","progress","DEFAULT_CONCURRENCY","DEFAULT_CHUNK_SIZE","DEFAULT_MAX_CHUNKS_PER_FILE","CHUNK_THRESHOLD","MAX_RETRIES","RETRY_DELAY_MS","URGENT_CONCURRENCY","FETCH_TIMEOUT_MS","HEAD_TIMEOUT_MS","inferContentType","fileInfo","ext","PRIORITY","BARRIER","getUrlExpiry","url","match","isUrlExpired","graceSeconds","expiry","rewriteUrlForProxy","loc","parsed","cmsOrigin","DownloadTask","options","headers","attempt","ac","timer","fetchOpts","msg","delay","chunkLabel","FileDownload","res","rej","queue","size","head","chunkSize","ranges","start","needed","r","skippedCount","isResume","sorted","a","b","task","highCount","t","e","ordered","i","assembled","LayoutTaskBuilder","DownloadQueue","existing","oldExpiry","file","tasks","running","idx","next","nonChunked","chunk0s","chunkLasts","remaining","result","items","taskCount","barrierCount","item","boosted","fileIds","priority","idSet","chunkIndex","activeTask","hasUrgent","maxSlots","minPriority","found","err","check","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","baseTag","modifiedHtml","cmsUrlRegex","staticResources","localPath","cssFixTag","staticCache","originalUrl","staticKey","resp","contentType","cssText","fontResources","fontUrlRegex","_match","quote","fullUrl","fontFilename","fontFile","fontUrl","fontKey","fontResp","fontBlob","fontExt","fontContentType","fontErr"],"mappings":"0CAKO,MAAMA,CAAa,CACxB,aAAc,CACZ,KAAK,OAAS,IAAI,GACpB,CAOA,GAAGC,EAAOC,EAAU,CACb,KAAK,OAAO,IAAID,CAAK,GACxB,KAAK,OAAO,IAAIA,EAAO,CAAA,CAAE,EAE3B,KAAK,OAAO,IAAIA,CAAK,EAAE,KAAKC,CAAQ,CACtC,CAOA,KAAKD,EAAOC,EAAU,CACpB,MAAMC,EAAU,IAAIC,IAAS,CAC3BF,EAAS,GAAGE,CAAI,EAChB,KAAK,IAAIH,EAAOE,CAAO,CACzB,EACA,KAAK,GAAGF,EAAOE,CAAO,CACxB,CAOA,IAAIF,EAAOC,EAAU,CACnB,GAAI,CAAC,KAAK,OAAO,IAAID,CAAK,EAAG,OAE7B,MAAMI,EAAY,KAAK,OAAO,IAAIJ,CAAK,EACjCK,EAAQD,EAAU,QAAQH,CAAQ,EACpCI,IAAU,IACZD,EAAU,OAAOC,EAAO,CAAC,CAE7B,CAOA,KAAKL,KAAUG,EAAM,CACnB,GAAI,CAAC,KAAK,OAAO,IAAIH,CAAK,EAAG,OAG7B,MAAMI,EAAY,KAAK,OAAO,IAAIJ,CAAK,EAAE,MAAK,EAC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AAKwK,CAAW,KAAK1J,EAAK,IAAI,SAAS,CACrF,CACF,OAASC,EAAO,CACdtB,EAAI,KAAK,oCAAoCO,CAAQ,GAAIe,CAAK,CAChE,CACF,CAAC,CAAC,CACJ,CAEA,OAAO8I,CACT"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import{f as S,c as x}from"./cms-api-Cqh1b8je.js";function w(b){const e=[];for(const t of b.children)t.tagName==="criteria"&&e.push({metric:t.getAttribute("metric")||"",condition:t.getAttribute("condition")||"",type:t.getAttribute("type")||"string",value:t.textContent||""});return e}function v(b){const t=new DOMParser().parseFromString(b,"text/xml"),s={default:null,defaultDependants:[],dependants:[],layouts:[],campaigns:[],overlays:[],actions:[],commands:[],dataConnectors:[]},n=t.querySelector("schedule");if(n){const r=Array.from(n.children).filter(c=>c.tagName==="dependants");for(const c of r)if(c.parentElement===n)for(const o of c.querySelectorAll("file"))o.textContent&&s.dependants.push(o.textContent)}const a=t.querySelector("default");if(a){s.default=a.getAttribute("file");const r=a.querySelectorAll("dependants > file");r.length>0&&(s.defaultDependants=[...r].map(c=>c.textContent))}for(const r of t.querySelectorAll("campaign")){const c={id:r.getAttribute("id"),priority:parseInt(r.getAttribute("priority")||"0"),fromdt:r.getAttribute("fromdt"),todt:r.getAttribute("todt"),scheduleid:r.getAttribute("scheduleid"),maxPlaysPerHour:parseInt(r.getAttribute("maxPlaysPerHour")||"0"),shareOfVoice:parseInt(r.getAttribute("shareOfVoice")||"0"),isGeoAware:r.getAttribute("isGeoAware")==="1",geoLocation:r.getAttribute("geoLocation")||"",syncEvent:r.getAttribute("syncEvent")==="1",recurrenceType:r.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(r.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:r.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:r.getAttribute("recurrenceRange")||null,criteria:w(r),layouts:[]};for(const o of r.querySelectorAll("layout")){const g=o.getAttribute("file"),y=o.querySelectorAll("dependants > file");c.layouts.push({id:String(g),file:g,fromdt:o.getAttribute("fromdt")||c.fromdt,todt:o.getAttribute("todt")||c.todt,scheduleid:c.scheduleid,priority:c.priority,campaignId:c.id,maxPlaysPerHour:parseInt(o.getAttribute("maxPlaysPerHour")||"0"),isGeoAware:o.getAttribute("isGeoAware")==="1",geoLocation:o.getAttribute("geoLocation")||"",syncEvent:o.getAttribute("syncEvent")==="1",shareOfVoice:parseInt(o.getAttribute("shareOfVoice")||"0"),duration:parseInt(o.getAttribute("duration")||"0"),cyclePlayback:o.getAttribute("cyclePlayback")==="1",groupKey:o.getAttribute("groupKey")||null,playCount:parseInt(o.getAttribute("playCount")||"0"),dependants:y.length>0?[...y].map(d=>d.textContent):[],criteria:w(o)})}s.campaigns.push(c)}for(const r of t.querySelectorAll("schedule > layout")){const c=r.getAttribute("file"),o=r.querySelectorAll("dependants > file");s.layouts.push({id:String(c),file:c,fromdt:r.getAttribute("fromdt"),todt:r.getAttribute("todt"),scheduleid:r.getAttribute("scheduleid"),priority:parseInt(r.getAttribute("priority")||"0"),campaignId:null,maxPlaysPerHour:parseInt(r.getAttribute("maxPlaysPerHour")||"0"),isGeoAware:r.getAttribute("isGeoAware")==="1",geoLocation:r.getAttribute("geoLocation")||"",syncEvent:r.getAttribute("syncEvent")==="1",shareOfVoice:parseInt(r.getAttribute("shareOfVoice")||"0"),duration:parseInt(r.getAttribute("duration")||"0"),cyclePlayback:r.getAttribute("cyclePlayback")==="1",groupKey:r.getAttribute("groupKey")||null,playCount:parseInt(r.getAttribute("playCount")||"0"),recurrenceType:r.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(r.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:r.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:r.getAttribute("recurrenceRange")||null,dependants:o.length>0?[...o].map(g=>g.textContent):[],criteria:w(r)})}const l=t.querySelector("overlays");if(l)for(const r of l.querySelectorAll("overlay")){const c=r.getAttribute("file");s.overlays.push({id:String(c),duration:parseInt(r.getAttribute("duration")||"60"),file:c,fromdt:r.getAttribute("fromdt"),todt:r.getAttribute("todt"),priority:parseInt(r.getAttribute("priority")||"0"),scheduleid:r.getAttribute("scheduleid"),isGeoAware:r.getAttribute("isGeoAware")==="1",geoLocation:r.getAttribute("geoLocation")||"",syncEvent:r.getAttribute("syncEvent")==="1",maxPlaysPerHour:parseInt(r.getAttribute("maxPlaysPerHour")||"0"),recurrenceType:r.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(r.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:r.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:r.getAttribute("recurrenceRange")||null,criteria:w(r)})}const i=t.querySelector("actions");if(i)for(const r of i.querySelectorAll("action"))s.actions.push({actionType:r.getAttribute("actionType")||"",triggerCode:r.getAttribute("triggerCode")||"",layoutCode:r.getAttribute("layoutCode")||"",commandCode:r.getAttribute("commandCode")||"",duration:parseInt(r.getAttribute("duration")||"0"),fromdt:r.getAttribute("fromdt"),todt:r.getAttribute("todt"),priority:parseInt(r.getAttribute("priority")||"0"),scheduleid:r.getAttribute("scheduleid"),isGeoAware:r.getAttribute("isGeoAware")==="1",geoLocation:r.getAttribute("geoLocation")||""});for(const r of t.querySelectorAll("schedule > command"))s.commands.push({code:r.getAttribute("code")||"",date:r.getAttribute("date")||""});const u=t.querySelector("dataConnectors");if(u)for(const r of u.querySelectorAll("connector"))s.dataConnectors.push({id:r.getAttribute("id")||"",dataConnectorId:r.getAttribute("dataConnectorId")||"",dataSetId:r.getAttribute("dataSetId")||"",dataKey:r.getAttribute("dataKey")||"",dataParams:r.getAttribute("dataParams")||"",js:r.getAttribute("js")||"",url:r.getAttribute("url")||"",updateInterval:parseInt(r.getAttribute("updateInterval")||"300",10)});return s}const f=x("REST");class K{constructor(e){this.config=e,this.schemaVersion=7,this.retryOptions=e.retryOptions||{maxRetries:2,baseDelayMs:2e3},this._etags=new Map,this._responseCache=new Map,f.info("Using REST transport")}getRestBaseUrl(){return(this.config.restApiUrl||`${this.config.cmsAddress}/pwa`).replace(/\/+$/,"")}_isProxyMode(){var e;return typeof window<"u"&&(((e=window.electronAPI)==null?void 0:e.isElectron)||window.location.hostname==="localhost"&&window.location.port==="8765")}_rewriteForProxy(e){if(!this._isProxyMode()||!e.startsWith("http"))return e;const t=new URL(e),s=new URL("/rest-proxy",window.location.origin);s.searchParams.set("cms",t.origin),s.searchParams.set("path",t.pathname);for(const[n,a]of t.searchParams)s.searchParams.set(n,a);return s.toString()}async restGet(e,t={}){const s=new URL(`${this.getRestBaseUrl()}${e}`);s.searchParams.set("serverKey",this.config.cmsKey),s.searchParams.set("hardwareKey",this.config.hardwareKey),s.searchParams.set("v",String(this.schemaVersion));for(const[o,g]of Object.entries(t))s.searchParams.set(o,String(g));const n=e,a={},l=this._etags.get(n);l&&(a["If-None-Match"]=l),f.debug(`GET ${e}`,t);const i=await S(this._rewriteForProxy(s.toString()),{method:"GET",headers:a},this.retryOptions);if(i.status===304){const o=this._responseCache.get(n);if(o)return f.debug(`${e} → 304 (using cache)`),o}if(!i.ok){const o=await i.text().catch(()=>"");throw new Error(`REST GET ${e} failed: ${i.status} ${i.statusText} ${o}`)}const u=i.headers.get("ETag");u&&this._etags.set(n,u);const r=i.headers.get("Content-Type")||"";let c;return r.includes("application/json")?c=await i.json():c=await i.text(),this._responseCache.set(n,c),c}async restSend(e,t,s={}){const n=new URL(`${this.getRestBaseUrl()}${t}`);n.searchParams.set("v",String(this.schemaVersion)),f.debug(`${e} ${t}`);const a=await S(this._rewriteForProxy(n.toString()),{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify({serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,...s})},this.retryOptions);if(!a.ok){const i=await a.text().catch(()=>"");throw new Error(`REST ${e} ${t} failed: ${a.status} ${a.statusText} ${i}`)}return(a.headers.get("Content-Type")||"").includes("application/json")?await a.json():await a.text()}async registerDisplay(){const e=typeof navigator<"u"?`${navigator.platform} ${navigator.userAgent}`:"unknown",t=await this.restSend("POST","/register",{displayName:this.config.displayName,clientType:this.config.clientType||"chromeOS",clientVersion:this.config.clientVersion||"0.1.0",clientCode:this.config.clientCode||1,operatingSystem:e,macAddress:this.config.macAddress||"n/a",xmrChannel:this.config.xmrChannel,xmrPubKey:this.config.xmrPubKey||"",licenceResult:"licensed"});return this._parseRegisterDisplayJson(t)}_parseRegisterDisplayJson(e){const t=e.display||e,s=t["@attributes"]||{},n=s.code||t.code,a=s.message||t.message||"";if(n!=="READY")return{code:n,message:a,settings:null};const l={};let i=[],u=[];for(const[y,d]of Object.entries(t))if(!(y==="@attributes"||y==="file")){if(y==="commands"){Array.isArray(d)&&(u=d.map(p=>({commandCode:p.code||p.commandCode||"",commandString:p.commandString||""})));continue}if(y==="tags"){const p=h=>typeof h=="object"?h.tag||h.value||"":String(h);if(Array.isArray(d))i=d.map(p).filter(Boolean);else if(d&&typeof d=="object"){const h=p(d);h&&(i=[h])}else typeof d=="string"&&d&&(i=[d]);continue}l[y]=typeof d=="object"?JSON.stringify(d):String(d)}const r=s.checkRf||"",c=s.checkSchedule||"",o={date:s.date||t.date||null,timezone:s.timezone||t.timezone||null,status:s.status||t.status||null,localDate:s.localDate||t.localDate||null,version_instructions:s.version_instructions||t.version_instructions||null},g=t.syncGroup?{syncGroup:String(t.syncGroup),syncPublisherPort:parseInt(t.syncPublisherPort||"9590",10),syncSwitchDelay:parseInt(t.syncSwitchDelay||"750",10),syncVideoPauseDelay:parseInt(t.syncVideoPauseDelay||"100",10),isLead:String(t.syncGroup)==="lead"}:null;return{code:n,message:a,settings:l,tags:i,commands:u,displayAttrs:o,checkRf:r,checkSchedule:c,syncConfig:g}}async requiredFiles(){const e=await this.restGet("/requiredFiles");return this._parseRequiredFilesJson(e)}_parseRequiredFilesJson(e){var l;const t=[];let s=e.file||[];Array.isArray(s)||(s=[s]);for(const i of s){const u=i["@attributes"]||i,r=u.path||null;t.push({type:u.type||null,id:u.id||null,size:parseInt(u.size||"0"),md5:u.md5||null,download:u.download||null,path:r,saveAs:u.saveAs||null,fileType:u.fileType||null,code:u.code||null,layoutid:u.layoutid||null,regionid:u.regionid||null,mediaid:u.mediaid||null})}const n=[];let a=((l=e.purge)==null?void 0:l.item)||[];Array.isArray(a)||(a=[a]);for(const i of a){const u=i["@attributes"]||i;n.push({id:u.id||null,storedAs:u.storedAs||null})}return{files:t,purge:n}}async schedule(){const e=await this.restGet("/schedule");return v(e)}async getResource(e,t,s){return this.restGet("/getResource",{layoutId:String(e),regionId:String(t),mediaId:String(s)})}async notifyStatus(e){var t;if(typeof navigator<"u"&&((t=navigator.storage)!=null&&t.estimate))try{const s=await navigator.storage.estimate();e.availableSpace=s.quota-s.usage,e.totalSpace=s.quota}catch{}return!e.timeZone&&typeof Intl<"u"&&(e.timeZone=Intl.DateTimeFormat().resolvedOptions().timeZone),e.statusDialog||(e.statusDialog=`Current Layout: ${e.currentLayoutId||"None"}`),this.restSend("PUT","/status",{statusData:e})}async mediaInventory(e){const t=Array.isArray(e)?{inventoryItems:e}:{inventory:e};return this.restSend("POST","/mediaInventory",t)}async blackList(e,t,s){try{const n=await this.restSend("POST","/blacklist",{mediaId:String(e),type:t||"media",reason:s||"Failed to render"});return f.info(`BlackListed ${t}/${e}: ${s}`),(n==null?void 0:n.success)===!0}catch(n){return f.warn("BlackList failed:",n),!1}}async submitLog(e,t=null){const s=Array.isArray(e)?{logs:e}:{logXml:e};t&&(s.hardwareKey=t);const n=await this.restSend("POST","/log",s);return(n==null?void 0:n.success)===!0}async submitScreenShot(e){const t=await this.restSend("POST","/screenshot",{screenshot:e});return(t==null?void 0:t.success)===!0}async reportFaults(e){const t=await this.restSend("POST","/fault",{fault:e});return(t==null?void 0:t.success)===!0}async getWeather(){return this.restGet("/weather")}async submitStats(e,t=null){try{const s=Array.isArray(e)?{stats:e}:{statXml:e};t&&(s.hardwareKey=t);const n=await this.restSend("POST","/stats",s),a=(n==null?void 0:n.success)===!0;return f.info(`SubmitStats result: ${a}`),a}catch(s){throw f.error("SubmitStats failed:",s),s}}}const A=x("XMDS");class I{constructor(e){this.config=e,this.schemaVersion=5,this.retryOptions=e.retryOptions||{maxRetries:2,baseDelayMs:2e3}}buildEnvelope(e,t){const s=Object.entries(t).map(([n,a])=>{const l=String(a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");return`<${n} xsi:type="xsd:string">${l}</${n}>`}).join(`
|
|
2
|
+
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
|
+
<soap:Envelope
|
|
4
|
+
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
|
|
5
|
+
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
|
|
6
|
+
xmlns:tns="urn:xmds"
|
|
7
|
+
xmlns:types="urn:xmds/encodedTypes"
|
|
8
|
+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
9
|
+
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
|
|
10
|
+
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
|
|
11
|
+
<tns:${e}>
|
|
12
|
+
${s}
|
|
13
|
+
</tns:${e}>
|
|
14
|
+
</soap:Body>
|
|
15
|
+
</soap:Envelope>`}rewriteXmdsUrl(e){var t;return typeof window<"u"&&((t=window.electronAPI)!=null&&t.isElectron||window.location.hostname==="localhost"&&window.location.port==="8765")?`/xmds-proxy?cms=${encodeURIComponent(e)}`:`${e}/xmds.php`}async call(e,t={}){const s=this.rewriteXmdsUrl(this.config.cmsAddress),n=`${s}${s.includes("?")?"&":"?"}v=${this.schemaVersion}&method=${e}`,a=this.buildEnvelope(e,t);A.debug(`${e}`,t),A.debug(`URL: ${n}`);const l=await S(n,{method:"POST",headers:{"Content-Type":"text/xml; charset=utf-8"},body:a},this.retryOptions);if(!l.ok)throw new Error(`XMDS ${e} failed: ${l.status} ${l.statusText}`);const i=await l.text();return this.parseResponse(i,e)}parseResponse(e,t){var r,c;const n=new DOMParser().parseFromString(e,"text/xml");let a=n.querySelector("Fault");if(a||(a=Array.from(n.querySelectorAll("*")).find(o=>o.localName==="Fault"||o.tagName.endsWith(":Fault"))),a){const o=((r=a.querySelector("faultstring"))==null?void 0:r.textContent)||((c=Array.from(a.querySelectorAll("*")).find(g=>g.localName==="faultstring"))==null?void 0:c.textContent)||"Unknown SOAP fault";throw new Error(`SOAP Fault: ${o}`)}const l=`${t}Response`;let i=n.querySelector(l);if(i||(i=Array.from(n.querySelectorAll("*")).find(o=>o.localName===l||o.tagName.endsWith(":"+l))),!i)throw new Error(`No ${l} element in SOAP response`);const u=i.firstElementChild;return u?u.textContent:null}async registerDisplay(){const e=`${navigator.platform} ${navigator.userAgent}`,t=await this.call("RegisterDisplay",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,displayName:this.config.displayName,clientType:this.config.clientType||"chromeOS",clientVersion:this.config.clientVersion||"0.1.0",clientCode:this.config.clientCode||"1",operatingSystem:e,macAddress:this.config.macAddress||"n/a",xmrChannel:this.config.xmrChannel||"",xmrPubKey:this.config.xmrPubKey||"",licenceResult:"licensed"});return this.parseRegisterDisplayResponse(t)}parseRegisterDisplayResponse(e){const n=new DOMParser().parseFromString(e,"text/xml").querySelector("display");if(!n)throw new Error("Invalid RegisterDisplay response: no <display> element");const a=n.getAttribute("code"),l=n.getAttribute("message");if(a!=="READY")return{code:a,message:l,settings:null};const i={},u=[],r=[];for(const p of n.children){const h=p.tagName.toLowerCase();if(h!=="file"){if(h==="commands"){for(const m of p.querySelectorAll("command"))r.push({commandCode:m.getAttribute("code")||m.getAttribute("commandCode")||"",commandString:m.getAttribute("commandString")||""});continue}if(h==="tags"){for(const m of p.querySelectorAll("tag"))m.textContent&&u.push(m.textContent);continue}i[p.tagName]=p.textContent}}const c=n.getAttribute("checkRf")||"",o=n.getAttribute("checkSchedule")||"",g={date:n.getAttribute("date")||null,timezone:n.getAttribute("timezone")||null,status:n.getAttribute("status")||null,localDate:n.getAttribute("localDate")||null,version_instructions:n.getAttribute("version_instructions")||null},y=i.syncGroup||null,d=y?{syncGroup:y,syncPublisherPort:parseInt(i.syncPublisherPort||"9590",10),syncSwitchDelay:parseInt(i.syncSwitchDelay||"750",10),syncVideoPauseDelay:parseInt(i.syncVideoPauseDelay||"100",10),isLead:y==="lead"}:null;return{code:a,message:l,settings:i,tags:u,commands:r,displayAttrs:g,checkRf:c,checkSchedule:o,syncConfig:d}}async requiredFiles(){const e=await this.call("RequiredFiles",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey});return this.parseRequiredFilesResponse(e)}parseRequiredFilesResponse(e){const s=new DOMParser().parseFromString(e,"text/xml"),n=[];for(const i of s.querySelectorAll("file"))n.push({type:i.getAttribute("type"),id:i.getAttribute("id"),size:parseInt(i.getAttribute("size")||"0"),md5:i.getAttribute("md5"),download:i.getAttribute("download"),path:i.getAttribute("path"),saveAs:i.getAttribute("saveAs")||null,fileType:i.getAttribute("fileType")||null,code:i.getAttribute("code"),layoutid:i.getAttribute("layoutid"),regionid:i.getAttribute("regionid"),mediaid:i.getAttribute("mediaid")});const a=[],l=s.querySelector("purge");if(l)for(const i of l.querySelectorAll("item"))a.push({id:i.getAttribute("id"),storedAs:i.getAttribute("storedAs")});return{files:n,purge:a}}async schedule(){const e=await this.call("Schedule",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey});return v(e)}async getResource(e,t,s){return await this.call("GetResource",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,layoutId:String(e),regionId:String(t),mediaId:String(s)})}async notifyStatus(e){var t;if(typeof navigator<"u"&&((t=navigator.storage)!=null&&t.estimate))try{const s=await navigator.storage.estimate();e.availableSpace=s.quota-s.usage,e.totalSpace=s.quota}catch{}return!e.timeZone&&typeof Intl<"u"&&(e.timeZone=Intl.DateTimeFormat().resolvedOptions().timeZone),e.statusDialog||(e.statusDialog=`Current Layout: ${e.currentLayoutId||"None"}`),await this.call("NotifyStatus",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,status:JSON.stringify(e)})}async mediaInventory(e){return await this.call("MediaInventory",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,mediaInventory:e})}async blackList(e,t,s){try{const n=await this.call("BlackList",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,mediaId:String(e),type:t||"media",reason:s||"Failed to render"});return A.info(`BlackListed ${t}/${e}: ${s}`),n==="true"}catch(n){return A.warn("BlackList failed:",n),!1}}async submitLog(e,t=null){return await this.call("SubmitLog",{serverKey:this.config.cmsKey,hardwareKey:t||this.config.hardwareKey,logXml:e})==="true"}async submitScreenShot(e){return await this.call("SubmitScreenShot",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,screenShot:e})==="true"}async reportFaults(e){return this.call("ReportFaults",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,fault:e})}async getWeather(){return this.call("GetWeather",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey})}async submitStats(e,t=null){try{const n=await this.call("SubmitStats",{serverKey:this.config.cmsKey,hardwareKey:t||this.config.hardwareKey,statXml:e})==="true";return A.info(`SubmitStats result: ${n}`),n}catch(s){throw A.error("SubmitStats failed:",s),s}}}export{K as R,I as X,v as p};
|
|
16
|
+
//# sourceMappingURL=xmds-client-BPdCcQeh.js.map
|