@xiboplayer/pwa 0.5.4 → 0.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -0
- package/dist/assets/{cms-api-B3gEu-pj.js → cms-api-Df_4fWKB.js} +2 -2
- package/dist/assets/{cms-api-B3gEu-pj.js.map → cms-api-Df_4fWKB.js.map} +1 -1
- package/dist/assets/{index-BJfE9Kwo.js → index-BI2Wgrnr.js} +2 -2
- package/dist/assets/{index-BJfE9Kwo.js.map → index-BI2Wgrnr.js.map} +1 -1
- package/dist/assets/index-BtefBXN1.js +2 -0
- package/dist/assets/{index-CQyGlAYj.js.map → index-BtefBXN1.js.map} +1 -1
- package/dist/assets/index-C6HTCgOh.js +2 -0
- package/dist/assets/{index-CzDf1qpA.js.map → index-C6HTCgOh.js.map} +1 -1
- package/dist/assets/{index-CXNhzvrm.js → index-CO_3HB3b.js} +2 -2
- package/dist/assets/{index-CXNhzvrm.js.map → index-CO_3HB3b.js.map} +1 -1
- package/dist/assets/{index-DxBxL_GE.js → index-CSP8cHo2.js} +2 -2
- package/dist/assets/{index-DxBxL_GE.js.map → index-CSP8cHo2.js.map} +1 -1
- package/dist/assets/index-CXUhpySp.js +2 -0
- package/dist/assets/{index-B0GfHN6H.js.map → index-CXUhpySp.js.map} +1 -1
- package/dist/assets/index-DjVtpboH.js +2 -0
- package/dist/assets/{index-Y1vt-BGr.js.map → index-DjVtpboH.js.map} +1 -1
- package/dist/assets/{index-CUXQMBpU.js → index-DozRpAD9.js} +2 -2
- package/dist/assets/{index-CUXQMBpU.js.map → index-DozRpAD9.js.map} +1 -1
- package/dist/assets/index-O5-FLIor.js +2 -0
- package/dist/assets/{index-CExOPp2u.js.map → index-O5-FLIor.js.map} +1 -1
- package/dist/assets/main-4E7jVmyh.js +715 -0
- package/dist/assets/main-4E7jVmyh.js.map +1 -0
- package/dist/assets/{setup-DgQcE5P_.js → setup-D2LzAr3z.js} +2 -2
- package/dist/assets/{setup-DgQcE5P_.js.map → setup-D2LzAr3z.js.map} +1 -1
- package/dist/assets/{sync-manager-DBfiw5Ey.js → sync-manager-Cibvio-3.js} +2 -2
- package/dist/assets/{sync-manager-DBfiw5Ey.js.map → sync-manager-Cibvio-3.js.map} +1 -1
- package/dist/assets/widget-html-BzYo0-WO.js +5 -0
- package/dist/assets/widget-html-BzYo0-WO.js.map +1 -0
- package/dist/assets/{xmds-client-CX0t7Oes.js → xmds-client-uoul_PDG.js} +2 -2
- package/dist/assets/{xmds-client-CX0t7Oes.js.map → xmds-client-uoul_PDG.js.map} +1 -1
- package/dist/index.html +3 -3
- package/dist/setup.html +3 -3
- package/dist/sw-pwa.js +1 -1
- package/package.json +1 -1
- package/dist/assets/index-B0GfHN6H.js +0 -2
- package/dist/assets/index-CExOPp2u.js +0 -2
- package/dist/assets/index-CQyGlAYj.js +0 -2
- package/dist/assets/index-CzDf1qpA.js +0 -2
- package/dist/assets/index-Y1vt-BGr.js +0 -2
- package/dist/assets/main-ByDZRbW8.js +0 -715
- package/dist/assets/main-ByDZRbW8.js.map +0 -1
- package/dist/assets/widget-html-B_acad6q.js +0 -2
- package/dist/assets/widget-html-B_acad6q.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./modulepreload-polyfill-B5Qt9EMX.js";import{
|
|
2
|
-
//# sourceMappingURL=setup-
|
|
1
|
+
import"./modulepreload-polyfill-B5Qt9EMX.js";import{a as e}from"./cms-api-Df_4fWKB.js";import{R as P,X as K}from"./xmds-client-uoul_PDG.js";const $="0.5.5";document.getElementById("version-footer").textContent=`Xibo Player v${$}`;const L=document.getElementById("setup-form"),h=document.getElementById("error"),c=document.getElementById("submit-btn"),S=document.getElementById("phase-unlock"),I=document.getElementById("phase-setup"),b=document.getElementById("phase-waiting"),C=document.getElementById("countdown"),T=document.getElementById("waiting-display-name"),z=document.getElementById("btn-back"),N=document.getElementById("success-flash"),E=e.hardwareKey;document.getElementById("hw-key-display").textContent=E;document.getElementById("hw-key-waiting").textContent=E;const j=e.cmsUrl||"";let m=null,r=null,x=15,l=null;async function v(){if(l)return l;try{const t=new P(e);await t.registerDisplay(),console.log("[Setup] Using REST transport"),l=t}catch(t){console.log("[Setup] REST unavailable, using XMDS/SOAP:",t.message),l=new K(e)}return l}function y(t){S.classList.remove("active"),I.classList.remove("active"),b.classList.remove("active"),t.classList.add("active")}function O(t){h.textContent=t,h.style.display="block"}function _(){h.style.display="none"}function f(){let t=x;C.textContent=t,clearInterval(r),r=setInterval(()=>{t--,C.textContent=Math.max(0,t),t<=0&&clearInterval(r)},1e3)}async function w(){if(document.getElementById("cms-url").value.trim().replace(/\/$/,"")!==j){console.log("[Setup] CMS URL changed — wiping cached content");const n=await caches.keys();await Promise.all(n.map(a=>caches.delete(a)))}N.classList.add("active"),setTimeout(()=>{window.location.href="/player/index.html"},800)}async function M(){try{const n=await(await v()).registerDisplay();if(console.log("[Setup] Poll result:",n.code,n.message),n.code==="READY"){clearInterval(m),clearInterval(r),w();return}f()}catch(t){console.warn("[Setup] Poll failed:",t.message),f()}}function R(t){T.textContent=t,y(b),f(),m=setInterval(M,x*1e3)}function A(){clearInterval(m),clearInterval(r),m=null}async function X(t,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=await fetch(`/rest-proxy?cms=${encodeURIComponent(t)}&path=/api/authorize/access_token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:a,client_secret:o})});if(!s.ok)throw new Error(`OAuth2 failed: ${s.status}`);const{access_token:i}=await s.json(),u=await fetch(`/rest-proxy?cms=${encodeURIComponent(t)}&path=/api/display&hardwareKey=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${i}`}});if(!u.ok)throw new Error(`Find display failed: ${u.status}`);const p=await u.json();if(!p.length)return console.log("[Setup] Display not found via API (may not be registered yet)"),!1;const g=p[0];if(g.licensed===1)return console.log("[Setup] Display already authorized"),!0;const B=await fetch(`/rest-proxy?cms=${encodeURIComponent(t)}&path=/api/display/authorise/${g.displayId}`,{method:"PUT",headers:{Authorization:`Bearer ${i}`}});if(!B.ok)throw new Error(`Authorize failed: ${B.status}`);return console.log("[Setup] Display auto-authorized via proxy!"),e.apiClientId=a,e.apiClientSecret=o,!0}catch(s){return console.warn("[Setup] Auto-authorize failed:",s.message),!1}}const d=e.isConfigured()&&e.cmsKey,k=new URLSearchParams(window.location.search).has("unlocked"),D=document.getElementById("btn-back-player");d&&!k&&y(S);(d||k)&&(D.style.display="block",document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""));function U(){A(),window.location.href="/player/index.html"}D.addEventListener("click",U);(d||k)&&document.addEventListener("keydown",t=>{t.key==="Escape"&&(t.preventDefault(),U())});document.getElementById("unlock-form").addEventListener("submit",t=>{t.preventDefault();const n=document.getElementById("unlock-error");document.getElementById("unlock-key").value.trim()===e.cmsKey?(n.style.display="none",document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""),y(I)):(n.textContent="Incorrect CMS key",n.style.display="block")});!d&&e.isConfigured()&&(document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""));L.addEventListener("submit",async t=>{t.preventDefault(),_();const n=document.getElementById("cms-url").value.trim().replace(/\/$/,""),a=document.getElementById("cms-key").value.trim(),o=document.getElementById("display-name").value.trim();try{if(c.textContent="Saving...",c.disabled=!0,!(await fetch("/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cmsUrl:n,cmsKey:a,displayName:o})})).ok)throw new Error("Failed to save config");e.data.cmsUrl=n,e.data.cmsKey=a,e.data.displayName=o,e.save(),Y(e.hardwareKey),c.textContent="Connecting...",l=null;const i=await v();if((await i.registerDisplay()).code==="READY")w();else{if(c.textContent="Authorizing...",await X(n,E)&&(await i.registerDisplay()).code==="READY"){w();return}R(o)}}catch(s){O(`Connection failed: ${s.message}`),c.textContent="Connect",c.disabled=!1}});z.addEventListener("click",()=>{A(),y(I),c.textContent="Connect",c.disabled=!1});async function Y(t){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(t,"hardwareKey"),o.oncomplete=()=>a.close()}}catch(n){console.warn("[Setup] IndexedDB backup failed:",n)}}c.disabled=!1;c.textContent="Connect";e.isConfigured()&&!d&&(async()=>{try{(await(await v()).registerDisplay()).code==="READY"?window.location.href="/player/index.html":R(e.displayName)}catch{console.log("[Setup] Auto-check failed, showing form")}})();
|
|
2
|
+
//# sourceMappingURL=setup-D2LzAr3z.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setup-DgQcE5P_.js","sources":["../../setup.html?html-proxy&index=1.js"],"sourcesContent":["\n import { config } from '@xiboplayer/utils';\n import { RestClient, XmdsClient } from '@xiboplayer/xmds';\n\n // Inject version from Vite build\n const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '?';\n document.getElementById('version-footer').textContent = `Xibo Player v${appVersion}`;\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 phaseUnlock = document.getElementById('phase-unlock');\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 const previousCmsUrl = config.cmsUrl || '';\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 phaseUnlock.classList.remove('active');\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 async function showSuccess() {\n // If CMS URL changed, wipe all cached content (media, layouts, widgets\n // from the old CMS are useless) and the SW's cached index.html (which\n // may have a stale config injection script).\n const newUrl = document.getElementById('cms-url').value.trim().replace(/\\/$/, '');\n if (newUrl !== previousCmsUrl) {\n console.log('[Setup] CMS URL changed — wiping cached content');\n const cacheNames = await caches.keys();\n await Promise.all(cacheNames.map(name => caches.delete(name)));\n }\n successFlash.classList.add('active');\n setTimeout(() => {\n window.location.href = '/player/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 (through rest-proxy to avoid CORS) ──\n async function tryAutoAuthorize(cmsUrl, 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 // Step 1: OAuth2 token via proxy\n const tokenResp = await fetch(`/rest-proxy?cms=${encodeURIComponent(cmsUrl)}&path=/api/authorize/access_token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret }),\n });\n if (!tokenResp.ok) throw new Error(`OAuth2 failed: ${tokenResp.status}`);\n const { access_token } = await tokenResp.json();\n\n // Step 2: Find display by hardwareKey via proxy\n const displayResp = await fetch(\n `/rest-proxy?cms=${encodeURIComponent(cmsUrl)}&path=/api/display&hardwareKey=${encodeURIComponent(hardwareKey)}`,\n { headers: { Authorization: `Bearer ${access_token}` } }\n );\n if (!displayResp.ok) throw new Error(`Find display failed: ${displayResp.status}`);\n const displays = await displayResp.json();\n if (!displays.length) { console.log('[Setup] Display not found via API (may not be registered yet)'); return false; }\n\n const display = displays[0];\n if (display.licensed === 1) { console.log('[Setup] Display already authorized'); return true; }\n\n // Step 3: Authorize display via proxy\n const authResp = await fetch(\n `/rest-proxy?cms=${encodeURIComponent(cmsUrl)}&path=/api/display/authorise/${display.displayId}`,\n { method: 'PUT', headers: { Authorization: `Bearer ${access_token}` } }\n );\n if (!authResp.ok) throw new Error(`Authorize failed: ${authResp.status}`);\n\n console.log('[Setup] Display auto-authorized via proxy!');\n config.apiClientId = clientId;\n config.apiClientSecret = clientSecret;\n return true;\n } catch (error) {\n console.warn('[Setup] Auto-authorize failed:', error.message);\n return false;\n }\n }\n\n // ── Unlock gate for reconfiguration ──\n const isReconfigure = config.isConfigured() && config.cmsKey;\n const alreadyUnlocked = new URLSearchParams(window.location.search).has('unlocked');\n const btnBackPlayer = document.getElementById('btn-back-player');\n if (isReconfigure && !alreadyUnlocked) {\n // Show unlock phase instead of setup form\n showPhase(phaseUnlock);\n }\n if (isReconfigure || alreadyUnlocked) {\n // Show \"Back to Player\" on the setup form\n btnBackPlayer.style.display = 'block';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\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\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = '/player/index.html';\n }\n btnBackPlayer.addEventListener('click', goBackToPlayer);\n\n // Esc also goes back to player when reconfiguring\n if (isReconfigure || alreadyUnlocked) {\n document.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n goBackToPlayer();\n }\n });\n }\n\n // ── Unlock form handler ──\n document.getElementById('unlock-form').addEventListener('submit', (e) => {\n e.preventDefault();\n const unlockError = document.getElementById('unlock-error');\n const enteredKey = document.getElementById('unlock-key').value.trim();\n\n if (enteredKey === config.cmsKey) {\n unlockError.style.display = 'none';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.apiClientSecret || '';\n }\n showPhase(phaseSetup);\n } else {\n unlockError.textContent = 'Incorrect CMS key';\n unlockError.style.display = 'block';\n }\n });\n\n // ── Pre-fill if first-time setup (no unlock gate) ──\n if (!isReconfigure && config.isConfigured()) {\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\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\n // ── Form Submit ──\n form.addEventListener('submit', async (e) => {\n e.preventDefault();\n hideError();\n\n const cmsUrl = document.getElementById('cms-url').value.trim().replace(/\\/$/, '');\n const cmsKey = document.getElementById('cms-key').value.trim();\n const displayName = document.getElementById('display-name').value.trim();\n\n // Write config.json via proxy (master config file)\n // The boot path (proxy injection → Config.load()) handles the rest.\n try {\n submitBtn.textContent = 'Saving...';\n submitBtn.disabled = true;\n\n const saveResp = await fetch('/config', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ cmsUrl, cmsKey, displayName }),\n });\n if (!saveResp.ok) throw new Error('Failed to save config');\n\n // Also update in-memory config for the test connection below\n config.data.cmsUrl = cmsUrl;\n config.data.cmsKey = cmsKey;\n config.data.displayName = displayName;\n config.save();\n\n // Backup hardware key to IndexedDB for stability\n backupHardwareKey(config.hardwareKey);\n\n // Test connection\n submitBtn.textContent = 'Connecting...';\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(cmsUrl, 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 // Skip auto-resume when reconfiguring (user explicitly opened setup)\n if (config.isConfigured() && !isReconfigure) {\n (async () => {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n if (result.code === 'READY') {\n window.location.href = '/player/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":["appVersion","form","errorEl","submitBtn","phaseUnlock","phaseSetup","phaseWaiting","countdownEl","waitingNameEl","btnBack","successFlash","hwKey","config","previousCmsUrl","pollTimer","countdownTimer","pollSeconds","transport","getTransport","rest","RestClient","e","XmdsClient","showPhase","phase","showError","msg","hideError","startCountdown","remaining","showSuccess","cacheNames","name","checkAuthorization","result","error","startPolling","displayName","stopPolling","tryAutoAuthorize","cmsUrl","hardwareKey","clientId","clientSecret","tokenResp","access_token","displayResp","displays","display","authResp","isReconfigure","alreadyUnlocked","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,CACdV,EAAU,sBAAsBU,EAAM,OAAO,EAAE,EAC/ChC,EAAU,YAAc,UACxBA,EAAU,SAAW,EACvB,CACF,CAAC,EAGDM,EAAQ,iBAAiB,QAAS,IAAM,CACtC6B,EAAA,EACAf,EAAUlB,CAAU,EACpBF,EAAU,YAAc,UACxBA,EAAU,SAAW,EACvB,CAAC,EAGD,eAAeqD,EAAkBE,EAAK,CACpC,GAAI,CACF,MAAMC,EAAM,UAAU,KAAK,iBAAkB,CAAC,EAC9CA,EAAI,gBAAkB,IAAM,CAC1B,MAAMC,EAAKD,EAAI,OACVC,EAAG,iBAAiB,SAAS,MAAM,GACtCA,EAAG,kBAAkB,MAAM,CAE/B,EACAD,EAAI,UAAY,IAAM,CACpB,MAAMC,EAAKD,EAAI,OACTE,EAAKD,EAAG,YAAY,OAAQ,WAAW,EAC7CC,EAAG,YAAY,MAAM,EAAE,IAAIH,EAAK,aAAa,EAC7CG,EAAG,WAAa,IAAMD,EAAG,MAAA,CAC3B,CACF,OAASvC,EAAG,CACV,QAAQ,KAAK,mCAAoCA,CAAC,CACpD,CACF,CAGAlB,EAAU,SAAW,GACrBA,EAAU,YAAc,UAIpBS,EAAO,gBAAkB,CAACsC,IAC3B,SAAY,CACX,GAAI,EAEa,MADA,MAAMhC,EAAA,GACO,gBAAA,GACjB,OAAS,QAClB,OAAO,SAAS,KAAO,qBAGvBkB,EAAaxB,EAAO,WAAW,CAEnC,MAAY,CAEV,QAAQ,IAAI,yCAAyC,CACvD,CACF,GAAA"}
|
|
1
|
+
{"version":3,"file":"setup-D2LzAr3z.js","sources":["../../setup.html?html-proxy&index=1.js"],"sourcesContent":["\n import { config } from '@xiboplayer/utils';\n import { RestClient, XmdsClient } from '@xiboplayer/xmds';\n\n // Inject version from Vite build\n const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '?';\n document.getElementById('version-footer').textContent = `Xibo Player v${appVersion}`;\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 phaseUnlock = document.getElementById('phase-unlock');\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 const previousCmsUrl = config.cmsUrl || '';\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 phaseUnlock.classList.remove('active');\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 async function showSuccess() {\n // If CMS URL changed, wipe all cached content (media, layouts, widgets\n // from the old CMS are useless) and the SW's cached index.html (which\n // may have a stale config injection script).\n const newUrl = document.getElementById('cms-url').value.trim().replace(/\\/$/, '');\n if (newUrl !== previousCmsUrl) {\n console.log('[Setup] CMS URL changed — wiping cached content');\n const cacheNames = await caches.keys();\n await Promise.all(cacheNames.map(name => caches.delete(name)));\n }\n successFlash.classList.add('active');\n setTimeout(() => {\n window.location.href = '/player/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 (through rest-proxy to avoid CORS) ──\n async function tryAutoAuthorize(cmsUrl, 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 // Step 1: OAuth2 token via proxy\n const tokenResp = await fetch(`/rest-proxy?cms=${encodeURIComponent(cmsUrl)}&path=/api/authorize/access_token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret }),\n });\n if (!tokenResp.ok) throw new Error(`OAuth2 failed: ${tokenResp.status}`);\n const { access_token } = await tokenResp.json();\n\n // Step 2: Find display by hardwareKey via proxy\n const displayResp = await fetch(\n `/rest-proxy?cms=${encodeURIComponent(cmsUrl)}&path=/api/display&hardwareKey=${encodeURIComponent(hardwareKey)}`,\n { headers: { Authorization: `Bearer ${access_token}` } }\n );\n if (!displayResp.ok) throw new Error(`Find display failed: ${displayResp.status}`);\n const displays = await displayResp.json();\n if (!displays.length) { console.log('[Setup] Display not found via API (may not be registered yet)'); return false; }\n\n const display = displays[0];\n if (display.licensed === 1) { console.log('[Setup] Display already authorized'); return true; }\n\n // Step 3: Authorize display via proxy\n const authResp = await fetch(\n `/rest-proxy?cms=${encodeURIComponent(cmsUrl)}&path=/api/display/authorise/${display.displayId}`,\n { method: 'PUT', headers: { Authorization: `Bearer ${access_token}` } }\n );\n if (!authResp.ok) throw new Error(`Authorize failed: ${authResp.status}`);\n\n console.log('[Setup] Display auto-authorized via proxy!');\n config.apiClientId = clientId;\n config.apiClientSecret = clientSecret;\n return true;\n } catch (error) {\n console.warn('[Setup] Auto-authorize failed:', error.message);\n return false;\n }\n }\n\n // ── Unlock gate for reconfiguration ──\n const isReconfigure = config.isConfigured() && config.cmsKey;\n const alreadyUnlocked = new URLSearchParams(window.location.search).has('unlocked');\n const btnBackPlayer = document.getElementById('btn-back-player');\n if (isReconfigure && !alreadyUnlocked) {\n // Show unlock phase instead of setup form\n showPhase(phaseUnlock);\n }\n if (isReconfigure || alreadyUnlocked) {\n // Show \"Back to Player\" on the setup form\n btnBackPlayer.style.display = 'block';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\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\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = '/player/index.html';\n }\n btnBackPlayer.addEventListener('click', goBackToPlayer);\n\n // Esc also goes back to player when reconfiguring\n if (isReconfigure || alreadyUnlocked) {\n document.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n goBackToPlayer();\n }\n });\n }\n\n // ── Unlock form handler ──\n document.getElementById('unlock-form').addEventListener('submit', (e) => {\n e.preventDefault();\n const unlockError = document.getElementById('unlock-error');\n const enteredKey = document.getElementById('unlock-key').value.trim();\n\n if (enteredKey === config.cmsKey) {\n unlockError.style.display = 'none';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.apiClientSecret || '';\n }\n showPhase(phaseSetup);\n } else {\n unlockError.textContent = 'Incorrect CMS key';\n unlockError.style.display = 'block';\n }\n });\n\n // ── Pre-fill if first-time setup (no unlock gate) ──\n if (!isReconfigure && config.isConfigured()) {\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\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\n // ── Form Submit ──\n form.addEventListener('submit', async (e) => {\n e.preventDefault();\n hideError();\n\n const cmsUrl = document.getElementById('cms-url').value.trim().replace(/\\/$/, '');\n const cmsKey = document.getElementById('cms-key').value.trim();\n const displayName = document.getElementById('display-name').value.trim();\n\n // Write config.json via proxy (master config file)\n // The boot path (proxy injection → Config.load()) handles the rest.\n try {\n submitBtn.textContent = 'Saving...';\n submitBtn.disabled = true;\n\n const saveResp = await fetch('/config', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ cmsUrl, cmsKey, displayName }),\n });\n if (!saveResp.ok) throw new Error('Failed to save config');\n\n // Also update in-memory config for the test connection below\n config.data.cmsUrl = cmsUrl;\n config.data.cmsKey = cmsKey;\n config.data.displayName = displayName;\n config.save();\n\n // Backup hardware key to IndexedDB for stability\n backupHardwareKey(config.hardwareKey);\n\n // Test connection\n submitBtn.textContent = 'Connecting...';\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(cmsUrl, 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 // Skip auto-resume when reconfiguring (user explicitly opened setup)\n if (config.isConfigured() && !isReconfigure) {\n (async () => {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n if (result.code === 'READY') {\n window.location.href = '/player/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":["appVersion","form","errorEl","submitBtn","phaseUnlock","phaseSetup","phaseWaiting","countdownEl","waitingNameEl","btnBack","successFlash","hwKey","config","previousCmsUrl","pollTimer","countdownTimer","pollSeconds","transport","getTransport","rest","RestClient","e","XmdsClient","showPhase","phase","showError","msg","hideError","startCountdown","remaining","showSuccess","cacheNames","name","checkAuthorization","result","error","startPolling","displayName","stopPolling","tryAutoAuthorize","cmsUrl","hardwareKey","clientId","clientSecret","tokenResp","access_token","displayResp","displays","display","authResp","isReconfigure","alreadyUnlocked","btnBackPlayer","goBackToPlayer","unlockError","cmsKey","backupHardwareKey","client","key","req","db","tx"],"mappings":"4IAKI,MAAMA,EAAsD,QAC5D,SAAS,eAAe,gBAAgB,EAAE,YAAc,gBAAgBA,CAAU,GAGlF,MAAMC,EAAO,SAAS,eAAe,YAAY,EAC3CC,EAAU,SAAS,eAAe,OAAO,EACzCC,EAAY,SAAS,eAAe,YAAY,EAChDC,EAAc,SAAS,eAAe,cAAc,EACpDC,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,MAAME,EAAiBD,EAAO,QAAU,GACxC,IAAIE,EAAY,KACZC,EAAiB,KACjBC,EAAc,GAGdC,EAAY,KAChB,eAAeC,GAAe,CAC5B,GAAID,EAAW,OAAOA,EACtB,GAAI,CACF,MAAME,EAAO,IAAIC,EAAWR,CAAM,EAClC,MAAMO,EAAK,gBAAA,EACX,QAAQ,IAAI,8BAA8B,EAC1CF,EAAYE,CACd,OAASE,EAAG,CACV,QAAQ,IAAI,6CAA8CA,EAAE,OAAO,EACnEJ,EAAY,IAAIK,EAAWV,CAAM,CACnC,CACA,OAAOK,CACT,CAGA,SAASM,EAAUC,EAAO,CACxBpB,EAAY,UAAU,OAAO,QAAQ,EACrCC,EAAW,UAAU,OAAO,QAAQ,EACpCC,EAAa,UAAU,OAAO,QAAQ,EACtCkB,EAAM,UAAU,IA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=15e3,d=1e4;class f{constructor(t){this.displayId=t.displayId,this.syncConfig=t.syncConfig,this.isLead=t.syncConfig.isLead,this.switchDelay=t.syncConfig.syncSwitchDelay||750,this.videoPauseDelay=t.syncConfig.syncVideoPauseDelay||100,this.onLayoutChange=t.onLayoutChange||(()=>{}),this.onLayoutShow=t.onLayoutShow||(()=>{}),this.onVideoStart=t.onVideoStart||(()=>{}),this.onStatsReport=t.onStatsReport||null,this.onLogsReport=t.onLogsReport||null,this.onStatsAck=t.onStatsAck||null,this.onLogsAck=t.onLogsAck||null,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]",this._log=n(this.isLead?"Sync:LEAD":"Sync:FOLLOW")}start(){if(!this._started){if(this._started=!0,typeof BroadcastChannel>"u"){this._log.warn("BroadcastChannel not available — sync disabled");return}this.channel=new BroadcastChannel(r),this.channel.onmessage=t=>this._handleMessage(t.data),this._heartbeatTimer=setInterval(()=>this._sendHeartbeat(),l),this._sendHeartbeat(),this.isLead&&(this._cleanupTimer=setInterval(()=>this._cleanupStaleFollowers(),l)),this._log.info("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(),this._log.info("Stopped"))}async requestLayoutChange(t){if(!this.isLead){this._log.warn("requestLayoutChange called on follower — ignoring");return}t=String(t),this._pendingLayoutId=t;for(const[,a]of this.followers)a.ready=!1,a.readyLayoutId=null;const e=Date.now()+this.switchDelay;this._log.info(`Requesting layout change: ${t} (show at ${new Date(e).toISOString()}, ${this.followers.size} followers)`),this._send({type:"layout-change",layoutId:t,showAt:e,displayId:this.displayId}),this.followers.size>0&&await this._waitForFollowersReady(t);const s=e-Date.now();s>0&&await new Promise(a=>setTimeout(a,s)),this._log.info(`Sending layout-show: ${t}`),this._send({type:"layout-show",layoutId:t,displayId:this.displayId}),this.onLayoutShow(t),this._pendingLayoutId=null}async requestVideoStart(t,e){this.isLead&&(await new Promise(s=>setTimeout(s,this.videoPauseDelay)),this._send({type:"video-start",layoutId:String(t),regionId:e,displayId:this.displayId}),this.onVideoStart(String(t),e))}reportReady(t){t=String(t),this._log.info(`Reporting ready for layout ${t}`),this._send({type:"layout-ready",layoutId:t,displayId:this.displayId})}reportStats(t){this.isLead||(this._log.info("Delegating stats to lead"),this._send({type:"stats-report",displayId:this.displayId,statsXml:t}))}reportLogs(t){this.isLead||(this._log.info("Delegating logs to lead"),this._send({type:"logs-report",displayId:this.displayId,logsXml:t}))}_handleMessage(t){if(t.displayId!==this.displayId)switch(t.type){case"heartbeat":this._handleHeartbeat(t);break;case"layout-change":this.isLead||(this._log.info(`Layout change requested: ${t.layoutId}`),this.onLayoutChange(t.layoutId,t.showAt));break;case"layout-ready":this.isLead&&this._handleFollowerReady(t);break;case"layout-show":this.isLead||(this._log.info(`Layout show signal: ${t.layoutId}`),this.onLayoutShow(t.layoutId));break;case"video-start":this.isLead||(this._log.info(`Video start signal: ${t.layoutId} region ${t.regionId}`),this.onVideoStart(t.layoutId,t.regionId));break;case"stats-report":if(this.isLead&&this.onStatsReport){const e=()=>this._send({type:"stats-ack",displayId:this.displayId,targetDisplayId:t.displayId});this.onStatsReport(t.displayId,t.statsXml,e)}break;case"logs-report":if(this.isLead&&this.onLogsReport){const e=()=>this._send({type:"logs-ack",displayId:this.displayId,targetDisplayId:t.displayId});this.onLogsReport(t.displayId,t.logsXml,e)}break;case"stats-ack":!this.isLead&&t.targetDisplayId===this.displayId&&this.onStatsAck&&(this._log.info("Stats acknowledged by lead"),this.onStatsAck(t.targetDisplayId));break;case"logs-ack":!this.isLead&&t.targetDisplayId===this.displayId&&this.onLogsAck&&(this._log.info("Logs acknowledged by lead"),this.onLogsAck(t.targetDisplayId));break;default:this._log.warn("Unknown message type:",t.type)}}_handleHeartbeat(t){const e=this.followers.get(t.displayId);e?e.lastSeen=Date.now():(this.followers.set(t.displayId,{lastSeen:Date.now(),ready:!1,readyLayoutId:null,role:t.role||"unknown"}),this._log.info(`Follower joined: ${t.displayId} (${this.followers.size} total)`))}_handleFollowerReady(t){const e=this.followers.get(t.displayId);e?(e.ready=!0,e.readyLayoutId=t.layoutId,e.lastSeen=Date.now()):this.followers.set(t.displayId,{lastSeen:Date.now(),ready:!0,readyLayoutId:t.layoutId}),this._log.info(`Follower ${t.displayId} ready for layout ${t.layoutId}`),this._pendingLayoutId===t.layoutId&&this._readyResolve&&this._allFollowersReady(t.layoutId)&&(this._log.info("All followers ready"),this._readyResolve(),this._readyResolve=null)}_allFollowersReady(t){for(const[,e]of this.followers)if(!(Date.now()-e.lastSeen>i)&&(!e.ready||e.readyLayoutId!==t))return!1;return!0}_waitForFollowersReady(t){return new Promise(e=>{if(this._allFollowersReady(t)){e();return}this._readyResolve=e,setTimeout(()=>{if(this._readyResolve===e){const s=[];for(const[a,o]of this.followers)(!o.ready||o.readyLayoutId!==t)&&s.push(a);this._log.warn(`Ready timeout — proceeding without: ${s.join(", ")}`),this._readyResolve=null,e()}},d)})}_sendHeartbeat(){this._send({type:"heartbeat",displayId:this.displayId,role:this.isLead?"lead":"follower",timestamp:Date.now()})}_cleanupStaleFollowers(){const t=Date.now();for(const[e,s]of this.followers)t-s.lastSeen>i&&(this._log.info(`Removing stale follower: ${e} (last seen ${Math.round((t-s.lastSeen)/1e3)}s ago)`),this.followers.delete(e))}_send(t){if(this.channel)try{this.channel.postMessage(t)}catch(e){this._log.error("Failed to send:",e)}}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(([t,e])=>({displayId:t,lastSeen:e.lastSeen,ready:e.ready,readyLayoutId:e.readyLayoutId,stale:Date.now()-e.lastSeen>i}))}}}export{f as SyncManager};
|
|
2
|
+
//# sourceMappingURL=sync-manager-Cibvio-3.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync-manager-DBfiw5Ey.js","sources":["../../node_modules/.pnpm/@xiboplayer+sync@0.5.4/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\nimport { createLogger } from '@xiboplayer/utils';\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 * @param {Function} [options.onStatsReport] - (Lead) Called when follower sends stats\n * @param {Function} [options.onLogsReport] - (Lead) Called when follower sends logs\n * @param {Function} [options.onStatsAck] - (Follower) Called when lead confirms stats submission\n * @param {Function} [options.onLogsAck] - (Follower) Called when lead confirms logs submission\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 this.onStatsReport = options.onStatsReport || null;\n this.onLogsReport = options.onLogsReport || null;\n this.onStatsAck = options.onStatsAck || null;\n this.onLogsAck = options.onLogsAck || null;\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 // Logger with role prefix for clarity in multi-tab console\n this._tag = this.isLead ? '[Sync:LEAD]' : '[Sync:FOLLOW]';\n this._log = createLogger(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 this._log.warn( '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 this._log.info( '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 this._log.info( '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 this._log.warn( '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 this._log.info( `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 this._log.info( `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 this._log.info( `Reporting ready for layout ${layoutId}`);\n\n this._send({\n type: 'layout-ready',\n layoutId,\n displayId: this.displayId,\n });\n }\n\n /**\n * [Follower only] Delegate stats submission to the lead.\n * Lead will submit on our behalf and send a stats-ack when done.\n *\n * @param {string} statsXml - Formatted stats XML to submit\n */\n reportStats(statsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating stats to lead');\n this._send({\n type: 'stats-report',\n displayId: this.displayId,\n statsXml,\n });\n }\n\n /**\n * [Follower only] Delegate logs submission to the lead.\n * Lead will submit on our behalf and send a logs-ack when done.\n *\n * @param {string} logsXml - Formatted logs XML to submit\n */\n reportLogs(logsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating logs to lead');\n this._send({\n type: 'logs-report',\n displayId: this.displayId,\n logsXml,\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 this._log.info( `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 this._log.info( `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 this._log.info( `Video start signal: ${msg.layoutId} region ${msg.regionId}`);\n this.onVideoStart(msg.layoutId, msg.regionId);\n }\n break;\n\n case 'stats-report':\n // Lead: follower is delegating stats submission\n if (this.isLead && this.onStatsReport) {\n const statsAck = () => this._send({ type: 'stats-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onStatsReport(msg.displayId, msg.statsXml, statsAck);\n }\n break;\n\n case 'logs-report':\n // Lead: follower is delegating logs submission\n if (this.isLead && this.onLogsReport) {\n const logsAck = () => this._send({ type: 'logs-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onLogsReport(msg.displayId, msg.logsXml, logsAck);\n }\n break;\n\n case 'stats-ack':\n // Follower: lead confirmed stats were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onStatsAck) {\n this._log.info('Stats acknowledged by lead');\n this.onStatsAck(msg.targetDisplayId);\n }\n break;\n\n case 'logs-ack':\n // Follower: lead confirmed logs were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onLogsAck) {\n this._log.info('Logs acknowledged by lead');\n this.onLogsAck(msg.targetDisplayId);\n }\n break;\n\n default:\n this._log.warn( '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 this._log.info( `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 this._log.info( `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 this._log.info( '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 this._log.warn( `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 this._log.info( `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 this._log.error( '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","HEARTBEAT_INTERVAL","FOLLOWER_TIMEOUT","READY_TIMEOUT","SyncManager","options","createLogger","event","layoutId","follower","showAt","remaining","resolve","regionId","statsXml","logsXml","msg","statsAck","logsAck","existing","notReady","id","f","now"],"mappings":"0CAiCA,MAAMA,EAAe,YACfC,EAAqB,IACrBC,EAAmB,KACnBC,EAAgB,IAEf,MAAMC,CAAY,CAavB,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,IAGjE,KAAK,eAAiBA,EAAQ,iBAAmB,IAAM,CAAC,GACxD,KAAK,aAAeA,EAAQ,eAAiB,IAAM,CAAC,GACpD,KAAK,aAAeA,EAAQ,eAAiB,IAAM,CAAC,GACpD,KAAK,cAAgBA,EAAQ,eAAiB,KAC9C,KAAK,aAAeA,EAAQ,cAAgB,KAC5C,KAAK,WAAaA,EAAQ,YAAc,KACxC,KAAK,UAAYA,EAAQ,WAAa,KAGtC,KAAK,QAAU,KACf,KAAK,UAAY,IAAI,IACrB,KAAK,gBAAkB,KACvB,KAAK,cAAgB,KACrB,KAAK,cAAgB,KACrB,KAAK,iBAAmB,KACxB,KAAK,SAAW,GAGhB,KAAK,KAAO,KAAK,OAAS,cAAgB,gBAC1C,KAAK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AAE,EAGpB,KAAK,KAAK,KAAM,uCAAuCD,EAAS,KAAK,IAAI,CAAC,EAAE,EAC5E,KAAK,cAAgB,KACrBR,EAAO,CACT,CACF,EAAGT,CAAa,CAClB,CAAC,CACH,CAKA,gBAAiB,CACf,KAAK,MAAM,CACT,KAAM,YACN,UAAW,KAAK,UAChB,KAAM,KAAK,OAAS,OAAS,WAC7B,UAAW,KAAK,IAAG,CACzB,CAAK,CACH,CAGA,wBAAyB,CACvB,MAAMoB,EAAM,KAAK,IAAG,EACpB,SAAW,CAACF,EAAIZ,CAAQ,IAAK,KAAK,UAC5Bc,EAAMd,EAAS,SAAWP,IAC5B,KAAK,KAAK,KAAM,4BAA4BmB,CAAE,eAAe,KAAK,OAAOE,EAAMd,EAAS,UAAY,GAAI,CAAC,QAAQ,EACjH,KAAK,UAAU,OAAOY,CAAE,EAG9B,CAGA,MAAML,EAAK,CACT,GAAK,KAAK,QACV,GAAI,CACF,KAAK,QAAQ,YAAYA,CAAG,CAC9B,OAAS,EAAG,CACV,KAAK,KAAK,MAAO,kBAAmB,CAAC,CACvC,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,CAACK,EAAIC,CAAC,KAAO,CACtE,UAAWD,EACX,SAAUC,EAAE,SACZ,MAAOA,EAAE,MACT,cAAeA,EAAE,cACjB,MAAO,KAAK,IAAG,EAAKA,EAAE,SAAWpB,CACzC,EAAQ,CACR,CACE,CACF","x_google_ignoreList":[0]}
|
|
1
|
+
{"version":3,"file":"sync-manager-Cibvio-3.js","sources":["../../node_modules/.pnpm/@xiboplayer+sync@0.5.5/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\nimport { createLogger } from '@xiboplayer/utils';\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 * @param {Function} [options.onStatsReport] - (Lead) Called when follower sends stats\n * @param {Function} [options.onLogsReport] - (Lead) Called when follower sends logs\n * @param {Function} [options.onStatsAck] - (Follower) Called when lead confirms stats submission\n * @param {Function} [options.onLogsAck] - (Follower) Called when lead confirms logs submission\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 this.onStatsReport = options.onStatsReport || null;\n this.onLogsReport = options.onLogsReport || null;\n this.onStatsAck = options.onStatsAck || null;\n this.onLogsAck = options.onLogsAck || null;\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 // Logger with role prefix for clarity in multi-tab console\n this._tag = this.isLead ? '[Sync:LEAD]' : '[Sync:FOLLOW]';\n this._log = createLogger(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 this._log.warn( '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 this._log.info( '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 this._log.info( '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 this._log.warn( '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 this._log.info( `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 this._log.info( `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 this._log.info( `Reporting ready for layout ${layoutId}`);\n\n this._send({\n type: 'layout-ready',\n layoutId,\n displayId: this.displayId,\n });\n }\n\n /**\n * [Follower only] Delegate stats submission to the lead.\n * Lead will submit on our behalf and send a stats-ack when done.\n *\n * @param {string} statsXml - Formatted stats XML to submit\n */\n reportStats(statsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating stats to lead');\n this._send({\n type: 'stats-report',\n displayId: this.displayId,\n statsXml,\n });\n }\n\n /**\n * [Follower only] Delegate logs submission to the lead.\n * Lead will submit on our behalf and send a logs-ack when done.\n *\n * @param {string} logsXml - Formatted logs XML to submit\n */\n reportLogs(logsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating logs to lead');\n this._send({\n type: 'logs-report',\n displayId: this.displayId,\n logsXml,\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 this._log.info( `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 this._log.info( `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 this._log.info( `Video start signal: ${msg.layoutId} region ${msg.regionId}`);\n this.onVideoStart(msg.layoutId, msg.regionId);\n }\n break;\n\n case 'stats-report':\n // Lead: follower is delegating stats submission\n if (this.isLead && this.onStatsReport) {\n const statsAck = () => this._send({ type: 'stats-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onStatsReport(msg.displayId, msg.statsXml, statsAck);\n }\n break;\n\n case 'logs-report':\n // Lead: follower is delegating logs submission\n if (this.isLead && this.onLogsReport) {\n const logsAck = () => this._send({ type: 'logs-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onLogsReport(msg.displayId, msg.logsXml, logsAck);\n }\n break;\n\n case 'stats-ack':\n // Follower: lead confirmed stats were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onStatsAck) {\n this._log.info('Stats acknowledged by lead');\n this.onStatsAck(msg.targetDisplayId);\n }\n break;\n\n case 'logs-ack':\n // Follower: lead confirmed logs were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onLogsAck) {\n this._log.info('Logs acknowledged by lead');\n this.onLogsAck(msg.targetDisplayId);\n }\n break;\n\n default:\n this._log.warn( '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 this._log.info( `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 this._log.info( `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 this._log.info( '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 this._log.warn( `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 this._log.info( `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 this._log.error( '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","HEARTBEAT_INTERVAL","FOLLOWER_TIMEOUT","READY_TIMEOUT","SyncManager","options","createLogger","event","layoutId","follower","showAt","remaining","resolve","regionId","statsXml","logsXml","msg","statsAck","logsAck","existing","notReady","id","f","now"],"mappings":"0CAiCA,MAAMA,EAAe,YACfC,EAAqB,IACrBC,EAAmB,KACnBC,EAAgB,IAEf,MAAMC,CAAY,CAavB,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,IAGjE,KAAK,eAAiBA,EAAQ,iBAAmB,IAAM,CAAC,GACxD,KAAK,aAAeA,EAAQ,eAAiB,IAAM,CAAC,GACpD,KAAK,aAAeA,EAAQ,eAAiB,IAAM,CAAC,GACpD,KAAK,cAAgBA,EAAQ,eAAiB,KAC9C,KAAK,aAAeA,EAAQ,cAAgB,KAC5C,KAAK,WAAaA,EAAQ,YAAc,KACxC,KAAK,UAAYA,EAAQ,WAAa,KAGtC,KAAK,QAAU,KACf,KAAK,UAAY,IAAI,IACrB,KAAK,gBAAkB,KACvB,KAAK,cAAgB,KACrB,KAAK,cAAgB,KACrB,KAAK,iBAAmB,KACxB,KAAK,SAAW,GAGhB,KAAK,KAAO,KAAK,OAAS,cAAgB,gBAC1C,KAAK,KAAOC,EAAa,KAAK,OAAS,YAAc,aAAa,CACpE,CAKA,OAAQ,CACN,GAAI,MAAK,SAGT,IAFA,KAAK,SAAW,GAEZ,OAAO,iBAAqB,IAAa,CAC3C,KAAK,KAAK,KAAM,gDAAgD,EAChE,MACF,CAEA,KAAK,QAAU,IAAI,iBAAiBN,CAAY,EAChD,KAAK,QAAQ,UAAaO,GAAU,KAAK,eAAeA,EAAM,IAAI,EAGlE,K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GA,wBAAyB,CACvB,MAAMoB,EAAM,KAAK,IAAG,EACpB,SAAW,CAACF,EAAIZ,CAAQ,IAAK,KAAK,UAC5Bc,EAAMd,EAAS,SAAWP,IAC5B,KAAK,KAAK,KAAM,4BAA4BmB,CAAE,eAAe,KAAK,OAAOE,EAAMd,EAAS,UAAY,GAAI,CAAC,QAAQ,EACjH,KAAK,UAAU,OAAOY,CAAE,EAG9B,CAGA,MAAML,EAAK,CACT,GAAK,KAAK,QACV,GAAI,CACF,KAAK,QAAQ,YAAYA,CAAG,CAC9B,OAAS,EAAG,CACV,KAAK,KAAK,MAAO,kBAAmB,CAAC,CACvC,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,CAACK,EAAIC,CAAC,KAAO,CACtE,UAAWD,EACX,SAAUC,EAAE,SACZ,MAAOA,EAAE,MACT,cAAeA,EAAE,cACjB,MAAO,KAAK,IAAG,EAAKA,EAAE,SAAWpB,CACzC,EAAQ,CACR,CACE,CACF","x_google_ignoreList":[0]}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{c as L}from"./cms-api-Df_4fWKB.js";const _={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},ee=[];class xe{constructor(e,t=null){this.name=e,this.useGlobal=t===null,this.useGlobal||this.setLevel(t)}setLevel(e){this.useGlobal=!1,typeof e=="string"?this.level=_[e.toUpperCase()]??_.INFO:this.level=e}getEffectiveLevel(){return this.useGlobal?P.level:this.level}debug(...e){this.getEffectiveLevel()<=_.DEBUG&&console.log(`[${this.name}] DEBUG:`,...e),K("debug",this.name,e)}info(...e){this.getEffectiveLevel()<=_.INFO&&console.log(`[${this.name}]`,...e),K("info",this.name,e)}warn(...e){this.getEffectiveLevel()<=_.WARNING&&console.warn(`[${this.name}]`,...e),K("warning",this.name,e)}error(...e){this.getEffectiveLevel()<=_.ERROR&&console.error(`[${this.name}]`,...e),K("error",this.name,e)}log(e,...t){switch(e.toUpperCase()){case"DEBUG":return this.debug(...t);case"INFO":return this.info(...t);case"WARNING":case"WARN":return this.warn(...t);case"ERROR":return this.error(...t)}}}const P={level:_.WARNING,setGlobalLevel(l){typeof l=="string"?this.level=_[l.toUpperCase()]??_.INFO:this.level=l,console.log(`[Logger] Global log level set to: ${this.getLevelName(this.level)}`)},getLevelName(l){return Object.keys(_).find(e=>_[e]===l)||"UNKNOWN"}};let j=!1;if(typeof window<"u"){const e=new URLSearchParams(window.location.search).get("logLevel"),t=localStorage.getItem("xibo_log_level");e?(P.setGlobalLevel(e),j=!0):t?(P.setGlobalLevel(t),j=!0):P.setGlobalLevel("WARNING")}function Y(l,e=null){return new xe(l,e)}function et(l){if(j||!l)return!1;const e=Ee(l);return P.setGlobalLevel(e),!0}function Ee(l){switch((l||"").toLowerCase()){case"debug":return"DEBUG";case"info":case"notice":case"audit":return"INFO";case"warning":return"WARNING";case"error":case"critical":case"alert":case"emergency":return"ERROR";default:return"INFO"}}function K(l,e,t){if(ee.length!==0)for(const s of ee)try{s({level:l,name:e,args:t})}catch{}}function te(l,e){const t=new Uint8Array(l);let s="";for(let o=0;o<t.length;o++)s+=String.fromCharCode(t[o]);const n=btoa(s),i=[];for(let o=0;o<n.length;o+=64)i.push(n.substring(o,o+64));return`-----BEGIN ${e}-----
|
|
2
|
+
${i.join(`
|
|
3
|
+
`)}
|
|
4
|
+
-----END ${e}-----`}async function Te(){const l=await crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:1024,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),e=await crypto.subtle.exportKey("spki",l.publicKey),t=await crypto.subtle.exportKey("pkcs8",l.privateKey);return{publicKeyPem:te(e,"PUBLIC KEY"),privateKeyPem:te(t,"PRIVATE KEY")}}function Re(l){return!l||typeof l!="string"?!1:/^-----BEGIN (PUBLIC KEY|PRIVATE KEY)-----\n[A-Za-z0-9+/=\n]+\n-----END \1-----$/.test(l.trim())}var se={};const Q="xibo_config",ne="xibo-hw-backup",ie=1;function Se(){const l=typeof process<"u"&&se?se:{},e={cmsUrl:l.CMS_URL||"",cmsKey:l.CMS_KEY||"",displayName:l.DISPLAY_NAME||"",hardwareKey:l.HARDWARE_KEY||"",xmrChannel:l.XMR_CHANNEL||"",googleGeoApiKey:l.GOOGLE_GEO_API_KEY||""};return Object.values(e).some(s=>s!=="")?e:null}class De{constructor(){this.data=this.load(),this._fromEnv||this._restoreHardwareKeyFromBackup()}load(){const e=Se();if(e)return this._fromEnv=!0,e;if(typeof localStorage>"u")return{cmsUrl:"",cmsKey:"",displayName:"",hardwareKey:"",xmrChannel:""};const t=localStorage.getItem(Q);let s={};if(t)try{s=JSON.parse(t)}catch(i){console.error("[Config] Failed to parse localStorage config:",i)}let n=!1;return!s.hardwareKey||s.hardwareKey.length<10?(console.warn("[Config] Missing/invalid hardwareKey — generating"),s.hardwareKey=this.generateStableHardwareKey(),this._backupHardwareKey(s.hardwareKey),n=!0):console.log("[Config] ✓ Loaded existing hardwareKey:",s.hardwareKey),s.xmrChannel||(console.warn("[Config] Missing xmrChannel — generating"),s.xmrChannel=this.generateXmrChannel(),n=!0),s.cmsUrl=s.cmsUrl||"",s.cmsKey=s.cmsKey||"",s.displayName=s.displayName||"",n&&localStorage.setItem(Q,JSON.stringify(s)),s}_backupKeys(e){try{const t=indexedDB.open(ne,ie);t.onupgradeneeded=()=>{const s=t.result;s.objectStoreNames.contains("keys")||s.createObjectStore("keys")},t.onsuccess=()=>{const s=t.result,n=s.transaction("keys","readwrite"),i=n.objectStore("keys");for(const[o,r]of Object.entries(e))i.put(r,o);n.oncomplete=()=>{console.log("[Config] Keys backed up to IndexedDB:",Object.keys(e).join(", ")),s.close()}}}catch{}}_backupHardwareKey(e){this._backupKeys({hardwareKey:e})}async _restoreHardwareKeyFromBackup(){if(!(typeof indexedDB>"u"))try{const e=await new Promise((i,o)=>{const r=indexedDB.open(ne,ie);r.onupgradeneeded=()=>{const h=r.result;h.objectStoreNames.contains("keys")||h.createObjectStore("keys")},r.onsuccess=()=>i(r.result),r.onerror=()=>o(r.error)}),s=e.transaction("keys","readonly").objectStore("keys"),n=await new Promise(i=>{const o=s.get("hardwareKey");o.onsuccess=()=>i(o.result),o.onerror=()=>i(null)});e.close(),n&&n!==this.data.hardwareKey?(console.log("[Config] Restoring hardware key from IndexedDB backup:",n),console.log("[Config] (was:",this.data.hardwareKey,")"),this.data.hardwareKey=n,this.save()):!n&&this.data.hardwareKey&&this._backupHardwareKey(this.data.hardwareKey)}catch{}}save(){typeof localStorage<"u"&&localStorage.setItem(Q,JSON.stringify(this.data))}isConfigured(){return!!(this.data.cmsUrl&&this.data.cmsKey&&this.data.displayName)}generateStableHardwareKey(){if(typeof crypto<"u"&&crypto.randomUUID){const n="pwa-"+crypto.randomUUID().replace(/-/g,"").substring(0,28);return console.log("[Config] Generated new UUID-based hardware key:",n),n}const t="pwa-"+Array.from({length:28},()=>Math.floor(Math.random()*16).toString(16)).join("");return console.log("[Config] Generated new random hardware key:",t),t}getCanvasFingerprint(){try{const e=document.createElement("canvas"),t=e.getContext("2d");return t?(t.textBaseline="top",t.font="14px Arial",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("Xibo Player",2,15),e.toDataURL()):"no-canvas"}catch{return"canvas-error"}}generateHardwareKey(){return this.generateStableHardwareKey()}generateXmrChannel(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}async ensureXmrKeyPair(){if(this.data.xmrPubKey&&Re(this.data.xmrPubKey))return;console.log("[Config] Generating RSA key pair for XMR registration...");const{publicKeyPem:e,privateKeyPem:t}=await Te();this.data.xmrPubKey=e,this.data.xmrPrivKey=t,this.save(),typeof indexedDB<"u"&&this._backupKeys({xmrPubKey:e,xmrPrivKey:t}),console.log("[Config] RSA key pair generated and saved")}hash(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);t=t>>>0;let s="";for(let n=0;n<4;n++){let i=t+n*1234567;for(let o=0;o<e.length;o++)i^=e.charCodeAt(o)+n,i+=(i<<1)+(i<<4)+(i<<7)+(i<<8)+(i<<24);i=i>>>0,s+=i.toString(16).padStart(8,"0")}return s.substring(0,32)}get cmsUrl(){return this.data.cmsUrl}set cmsUrl(e){this.data.cmsUrl=e,this.save()}get cmsKey(){return this.data.cmsKey}set cmsKey(e){this.data.cmsKey=e,this.save()}get displayName(){return this.data.displayName}set displayName(e){this.data.displayName=e,this.save()}get hardwareKey(){return this.data.hardwareKey||(console.error("[Config] CRITICAL: hardwareKey missing! Generating emergency key."),this.data.hardwareKey=this.generateStableHardwareKey(),this.save()),this.data.hardwareKey}get xmrChannel(){return this.data.xmrChannel||(console.warn("[Config] xmrChannel missing at access time — generating"),this.data.xmrChannel=this.generateXmrChannel(),this.save()),this.data.xmrChannel}get xmrPubKey(){return this.data.xmrPubKey||""}get xmrPrivKey(){return this.data.xmrPrivKey||""}get googleGeoApiKey(){return this.data.googleGeoApiKey||""}set googleGeoApiKey(e){this.data.googleGeoApiKey=e,this.save()}}new De;const re=Y("FetchRetry"),oe=3e4,ae=12e4;function Ie(l){if(!l)return oe;const e=Number(l);if(!isNaN(e)&&e>=0)return Math.min(e*1e3,ae);const t=new Date(l);if(!isNaN(t.getTime())){const s=t.getTime()-Date.now();return Math.min(Math.max(s,0),ae)}return oe}async function tt(l,e={},t={}){const{maxRetries:s=3,baseDelayMs:n=1e3,maxDelayMs:i=3e4}=t;let o,r;for(let h=0;h<=s;h++){try{const a=await fetch(l,e);if(a.status===429){const u=Ie(a.headers.get("Retry-After"));if(re.debug(`429 Rate limited, waiting ${u}ms (Retry-After: ${a.headers.get("Retry-After")})`),r=a,o=new Error("HTTP 429: Too Many Requests"),o.status=429,h<s){await new Promise(c=>setTimeout(c,u));continue}break}if(a.ok||a.status>=400&&a.status<500)return a;r=a,o=new Error(`HTTP ${a.status}: ${a.statusText}`),o.status=a.status}catch(a){o=a,r=null}if(h<s){const u=Math.min(n*Math.pow(2,h),i)*(.5+Math.random()*.5);re.debug(`Retry ${h+1}/${s} in ${Math.round(u)}ms:`,String(l).slice(0,80)),await new Promise(c=>setTimeout(c,u))}}if(r)return r;throw o}Y("CmsApi");const f=Y("Download"),Pe=6,de=50*1024*1024,Fe=3,Ae=100*1024*1024,O=3,Le=500,qe=2,le=6e5,Ue=15e3;function Be(l){var n,i;const t=(i=(n=(l.path||l.code||"").split(".").pop())==null?void 0:n.split("?")[0])==null?void 0:i.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 w={normal:0,layout:1,high:2,urgent:3},C=Symbol("BARRIER");function F(l){try{const e=l.match(/X-Amz-Expires=(\d+)/);return e?parseInt(e[1],10):1/0}catch{return 1/0}}function fe(l,e=30){const t=F(l);return t===1/0?!1:Date.now()/1e3>=t-e}function pe(l){if(!l.startsWith("http"))return l;const e=typeof self<"u"?self.location:void 0;if(!e||e.hostname!=="localhost"||e.port!=="8765")return l;const t=new URL(l),s=t.origin;return`/file-proxy?cms=${encodeURIComponent(s)}&url=${encodeURIComponent(t.pathname+t.search)}`}let W=class{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=w.normal}getUrl(){const e=this.fileInfo.path;if(fe(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return pe(e)}async start(){this.state="downloading";const e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`);for(let t=1;t<=O;t++){const s=new AbortController,n=setTimeout(()=>s.abort(),le);try{const i=this.getUrl(),o={signal:s.signal};Object.keys(e).length>0&&(o.headers=e);const r=await fetch(i,o);if(!r.ok&&r.status!==206)throw new Error(`Fetch failed: ${r.status}`);return this.blob=await r.blob(),this.state="complete",this.blob}catch(i){const o=s.signal.aborted?`Timeout after ${le/1e3}s`:i.message;if(t<O){const r=Le*t,h=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";f.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${h} attempt ${t}/${O} failed: ${o}. Retrying in ${r/1e3}s...`),await new Promise(a=>setTimeout(a,r))}else throw this.state="failed",s.signal.aborted?new Error(o):i}finally{clearTimeout(n)}}}},ge=class{constructor(e,t={}){this.fileInfo=e,this.options=t,this.state="pending",this.tasks=[],this.completedChunks=0,this.totalChunks=0,this.totalBytes=0,this.downloadedBytes=0,this.onChunkDownloaded=null,this.skipChunks=e.skipChunks||new Set,this._contentType="application/octet-stream",this._chunkBlobs=new Map,this._runningCount=0,this._resolve=null,this._reject=null,this._promise=new Promise((s,n)=>{this._resolve=s,this._reject=n}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(fe(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return pe(e)}wait(){return this._promise}async prepare(e){try{this.state="preparing";const{id:t,type:s,size:n}=this.fileInfo;if(f.info("[FileDownload] Starting:",`${s}/${t}`),this.totalBytes=n&&n>0?parseInt(n):0,this._contentType=Be(this.fileInfo),this.totalBytes===0){const o=this.getUrl(),r=new AbortController,h=setTimeout(()=>r.abort(),Ue);try{const a=await fetch(o,{method:"HEAD",signal:r.signal});a.ok&&(this.totalBytes=parseInt(a.headers.get("Content-Length")||"0"),this._contentType=a.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(h)}}f.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const i=this.options.chunkSize||de;if(this.totalBytes>Ae){const o=[];for(let c=0;c<this.totalBytes;c+=i)o.push({start:c,end:Math.min(c+i-1,this.totalBytes-1),index:o.length});this.totalChunks=o.length;const r=o.filter(c=>!this.skipChunks.has(c.index)),h=o.length-r.length;for(const c of o)this.skipChunks.has(c.index)&&(this.downloadedBytes+=c.end-c.start+1);if(r.length===0){f.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}h>0&&f.info(`[FileDownload] Resuming: ${h} chunks cached, ${r.length} to download`);const a=h>0;if(a){const c=r.sort((g,y)=>g.index-y.index);for(const g of c){const y=new W(this.fileInfo,{chunkIndex:g.index,rangeStart:g.start,rangeEnd:g.end});y._parentFile=this,y._priority=w.normal,this.tasks.push(y)}}else for(const c of r){const g=new W(this.fileInfo,{chunkIndex:c.index,rangeStart:c.start,rangeEnd:c.end});g._parentFile=this,g._priority=c.index===0||c.index===o.length-1?w.high:w.normal,this.tasks.push(g)}const u=this.tasks.filter(c=>c._priority>=w.high).length;f.info(`[FileDownload] ${s}/${t}: ${this.tasks.length} chunks`+(u>0?` (${u} priority)`:"")+(a?" (resume)":""))}else{this.totalChunks=1;const o=new W(this.fileInfo,{});o._parentFile=this,this.tasks.push(o)}e.enqueueChunkTasks(this.tasks),this.state="downloading"}catch(t){f.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){f.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)f.info("[FileDownload] Complete:",`${t}/${s}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)f.info("[FileDownload] Complete:",`${t}/${s}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const n=[];for(let o=0;o<this.totalChunks;o++){const r=this._chunkBlobs.get(o);r&&n.push(r)}const i=new Blob(n,{type:this._contentType});f.info("[FileDownload] Complete:",`${t}/${s}`,`(${i.size} bytes, reassembled)`),this._resolve(i)}this._chunkBlobs.clear()}}onTaskFailed(e,t){var s;if(!(this.state==="complete"||this.state==="failed")){if((s=t.message)!=null&&s.includes("URL expired")){const n=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";f.warn(`[FileDownload] URL expired, dropping${n}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(i=>i!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state="complete",this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}f.error("[FileDownload] Failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}},it=class{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const t=Ke.stableKey(e);if(this.queue.active.has(t)){const n=this.queue.active.get(t);if(e.path&&e.path!==n.fileInfo.path){const i=F(n.fileInfo.path);F(e.path)>i&&(n.fileInfo.path=e.path)}return n}const s=new ge(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(t,s),this._filesToPrepare.push(s),s}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let t=0,s=0;const n=()=>{for(;t<this._maxPreparing&&s<this._filesToPrepare.length;){const i=this._filesToPrepare[s++];t++,i.prepare(this).finally(()=>{t--,s>=this._filesToPrepare.length&&t===0?e():n()})}};this._filesToPrepare.length===0?e():n()})}_sortWithBarriers(){var o;const e=[],t=[],s=[],n=[];for(const r of this._tasks)if(r.chunkIndex==null)e.push(r);else if(r.chunkIndex===0)t.push(r);else{const h=((o=r._parentFile)==null?void 0:o.totalChunks)||0;h>1&&r.chunkIndex===h-1?s.push(r):n.push(r)}e.sort((r,h)=>{var a,u;return(((a=r._parentFile)==null?void 0:a.totalBytes)||0)-(((u=h._parentFile)==null?void 0:u.totalBytes)||0)}),n.sort((r,h)=>r.chunkIndex-h.chunkIndex);const i=[...e,...t,...s];return n.length>0&&i.push(C,...n),i}},Ke=class ye{constructor(e={}){this.concurrency=e.concurrency||Pe,this.chunkSize=e.chunkSize||de,this.maxChunksPerFile=e.chunksPerFile||Fe,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=ye.stableKey(e);if(this.active.has(t)){const n=this.active.get(t);if(e.path&&e.path!==n.fileInfo.path){const i=F(n.fileInfo.path);F(e.path)>i&&(f.info("[DownloadQueue] Refreshing URL for",t),n.fileInfo.path=e.path)}return n}const s=new ge(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(t,s),f.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(),f.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let t=0,s=0;for(const n of e)n===C?(this.queue.push(C),s++):(this.queue.push(n),t++);f.info(`[DownloadQueue] Ordered queue: ${t} tasks, ${s} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,t)=>t._priority-e._priority)}prioritize(e,t){const s=`${e}/${t}`,n=this.active.get(s);if(!n)return f.info("[DownloadQueue] Not found:",s),!1;let i=0;for(const o of this.queue)o._parentFile===n&&o._priority<w.high&&(o._priority=w.high,i++);return this._sortQueue(),f.info("[DownloadQueue] Prioritized:",s,`(${i} tasks boosted)`),!0}prioritizeLayoutFiles(e,t=w.high){var i,o;const s=new Set(e.map(String));let n=0;for(const r of this.queue)s.has(String((i=r._parentFile)==null?void 0:i.fileInfo.id))&&r._priority<t&&(r._priority=t,n++);for(const r of this._activeTasks)s.has(String((o=r._parentFile)==null?void 0:o.fileInfo.id))&&r._priority<t&&(r._priority=t);this._sortQueue(),f.info("[DownloadQueue] Layout files prioritized:",s.size,"files,",n,"tasks boosted to",t)}urgentChunk(e,t,s){const n=`${e}/${t}`,i=this.active.get(n);if(!i)return f.info("[DownloadQueue] urgentChunk: file not active:",n,"chunk",s),!1;if(this._activeTasks.some(a=>a._parentFile===i&&a.chunkIndex===s&&a.state==="downloading")){const a=this._activeTasks.find(u=>u._parentFile===i&&u.chunkIndex===s);return a&&a._priority<w.urgent?(a._priority=w.urgent,f.info(`[DownloadQueue] URGENT: ${n} chunk ${s} (already in-flight, limiting slots)`),!0):(f.info("[DownloadQueue] urgentChunk: already urgent:",n,"chunk",s),!1)}const r=this.queue.findIndex(a=>a!==C&&a._parentFile===i&&a.chunkIndex===s);if(r===-1)return f.info("[DownloadQueue] urgentChunk: chunk not in queue:",n,"chunk",s),!1;const h=this.queue.splice(r,1)[0];return h._priority=w.urgent,this.queue.unshift(h),f.info(`[DownloadQueue] URGENT: ${n} chunk ${s} (moved to front)`),this.processQueue(),!0}processQueue(){var n;if(this.paused)return;const e=this.queue.some(i=>i!==C&&i._priority>=w.urgent)||((n=this._activeTasks)==null?void 0:n.some(i=>i._priority>=w.urgent&&i.state==="downloading")),t=e?qe:this.concurrency,s=e?w.urgent:0;for(;this.running<t&&this.queue.length>0;){const i=this.queue[0];if(i===C){if(this.running>0)break;this.queue.shift();continue}if(i._priority<s||!this._canStartTask(i)){let o=!1;for(let r=1;r<this.queue.length&&this.queue[r]!==C;r++){const h=this.queue[r];if(h._priority>=s&&this._canStartTask(h)){this.queue.splice(r,1),this._startTask(h),o=!0;break}}if(!o)break;continue}this.queue.shift(),this._startTask(i)}this.queue.length===0&&this.running===0&&f.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}`:"";f.info(`[DownloadQueue] Starting: ${t}${s} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(n=>n!==e),f.info(`[DownloadQueue] Fetched: ${t}${s} (${this.running} active, ${this.queue.length} pending)`),this.processQueue(),e._parentFile.onTaskComplete(e))).catch(n=>{this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(i=>i!==e),this.processQueue(),e._parentFile.onTaskFailed(e,n)})}awaitAllPrepared(){return new Promise(e=>{const t=()=>{this._preparingCount===0&&this._prepareQueue.length===0?e():setTimeout(t,50)};t()})}removeCompleted(e){const t=this.active.get(e);t&&(t.state==="complete"||t.state==="failed")&&(this.queue=this.queue.filter(s=>s===C||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(){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=(...n)=>{t(...n),this.off(e,s)};this.on(e,s)}off(e,t){if(!this.events.has(e))return;const s=this.events.get(e),n=s.indexOf(t);n!==-1&&s.splice(n,1)}emit(e,...t){if(!this.events.has(e))return;const s=this.events.get(e).slice();for(const n of s)n(...t)}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}const Me=L("Cache"),Ne="xibo-media-v1",ze=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";class Qe{constructor(){this.dependants=new Map}getCacheKey(e,t,s=null){return`${ze}/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[n,i]of this.dependants)i.delete(t),i.size===0&&(this.dependants.delete(n),s.push(n));return s.length>0&&Me.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(Ne),this.dependants.clear()}}const ot=new Qe,d=L("CacheProxy"),he=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";class ce extends we{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"&&(d.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"){d.info("Using active Service Worker (controller not required)"),this.controller=navigator.serviceWorker.controller||e.active,this.controller.postMessage({type:"PING"}),d.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"}),d.info("Service Worker backend initialized, waiting for fetch readiness...")}else throw new Error("Service Worker not supported")}async getFile(e,t){this.fetchReady||(d.debug(`Waiting for SW fetch handler to be ready before fetching ${e}/${t}...`),await this.fetchReadyPromise,d.debug("SW fetch handler ready, proceeding with fetch"));const s=`${he}/cache/${e}/${t}`;d.debug(`getFile(${e}, ${t}) → fetching ${s}`),d.debug("About to call fetch()...");try{d.debug(`Calling fetch(${s})...`);const n=await fetch(s);if(d.debug("fetch returned, status:",n.status,n.statusText),!n.ok){if(d.debug(`Response not OK (${n.status}), returning null`),n.status===404)return null;throw new Error(`Failed to get file: ${n.status}`)}d.debug("Response OK, getting blob...");const i=await n.blob();return d.debug("Got blob, size:",i.size),i}catch(n){return d.error("getFile EXCEPTION:",n),d.error("Error name:",n.name),d.error("Error message:",n.message),null}}async hasFile(e,t){this.fetchReady||await this.fetchReadyPromise;const s=`${he}/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,n)=>{const i=new MessageChannel;i.port1.onmessage=o=>{const{success:r,error:h,enqueuedCount:a,activeCount:u,queuedCount:c}=o.data;r?(d.info("Download request acknowledged:",a,"files"),d.info("Queue state:",u,"active,",c,"queued"),s()):n(new Error(h||"Service Worker download failed"))},this.controller.postMessage({type:"DOWNLOAD_FILES",data:t},[i.port2])})}async prioritizeDownload(e,t){if(this.controller)return new Promise(s=>{const n=new MessageChannel;n.port1.onmessage=i=>s(i.data),this.controller.postMessage({type:"PRIORITIZE_DOWNLOAD",data:{fileType:e,fileId:t}},[n.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 at extends we{constructor(){super(),this.backend=null,this.backendType="service-worker"}async init(){var n,i;if(!("serviceWorker"in navigator))throw new Error("Service Worker not supported - PWA requires Service Worker");d.debug("Checking Service Worker state..."),d.debug("controller =",navigator.serviceWorker.controller);const e=await navigator.serviceWorker.getRegistration();if(d.debug("registration =",e),d.debug("active =",e==null?void 0:e.active),d.debug("installing =",e==null?void 0:e.installing),d.debug("waiting =",e==null?void 0:e.waiting),e&&e.active&&!e.installing&&!e.waiting){d.info("Active Service Worker found (no updates pending)"),d.debug("SW state =",e.active.state),navigator.serviceWorker.controller||(d.debug("Not controlling yet, waiting 200ms for claim..."),await new Promise(o=>setTimeout(o,200)),d.debug("After wait, controller =",navigator.serviceWorker.controller)),this.backend=new ce,await this.backend.init(),d.info("Service Worker backend ready (fast path)");return}e&&(e.installing||e.waiting)&&(d.info("New Service Worker detected, waiting for it to activate..."),d.debug("installing =",(n=e.installing)==null?void 0:n.state),d.debug("waiting =",(i=e.waiting)==null?void 0:i.state)),d.info("No active Service Worker, waiting for registration...");const t=navigator.serviceWorker.ready,s=new Promise((o,r)=>setTimeout(()=>r(new Error("Service Worker ready timeout after 10s")),1e4));try{await Promise.race([t,s]),d.debug("Service Worker ready promise resolved")}catch(o){throw d.error("Service Worker wait failed:",o),new Error("Service Worker not ready - please reload page")}await new Promise(o=>setTimeout(o,100)),d.debug("After claim wait, controller =",navigator.serviceWorker.controller),this.backend=new ce,await this.backend.init(),d.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:n,files:i}=s.data;e(n?i:[])},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 n=new MessageChannel;n.port1.onmessage=i=>{const{success:o,error:r,deleted:h,total:a}=i.data;o?t({deleted:h,total:a}):s(new Error(r||"Delete failed"))},navigator.serviceWorker.controller.postMessage({type:"DELETE_FILES",data:{files:e}},[n.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(n=>{const i=new MessageChannel;i.port1.onmessage=o=>{const{success:r,warmed:h,total:a}=o.data;n(r?{warmed:h,total:a}:{warmed:0,total:e.length})},t.postMessage({type:"PREWARM_VIDEO_CHUNKS",data:{mediaIds:e}},[i.port2]),setTimeout(()=>n({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:n,progress:i}=s.data;e(n?i:{})},navigator.serviceWorker.controller.postMessage({type:"GET_DOWNLOAD_PROGRESS"},[t.port2]),setTimeout(()=>e({}),1e3)})}}const p=L("Download"),Oe=6,me=50*1024*1024,We=3,He=100*1024*1024,H=3,Ge=500,je=2,ue=6e5,Ye=15e3;function Xe(l){var n,i;const t=(i=(n=(l.path||l.code||"").split(".").pop())==null?void 0:n.split("?")[0])==null?void 0:i.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 m={normal:0,layout:1,high:2,urgent:3},x=Symbol("BARRIER");function A(l){try{const e=l.match(/X-Amz-Expires=(\d+)/);return e?parseInt(e[1],10):1/0}catch{return 1/0}}function ke(l,e=30){const t=A(l);return t===1/0?!1:Date.now()/1e3>=t-e}function _e(l){if(!l.startsWith("http"))return l;const e=typeof self<"u"?self.location:void 0;if(!e||e.hostname!=="localhost")return l;const t=new URL(l),s=t.origin;return`/file-proxy?cms=${encodeURIComponent(s)}&url=${encodeURIComponent(t.pathname+t.search)}`}class G{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=m.normal}getUrl(){const e=this.fileInfo.path;if(ke(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return _e(e)}async start(){this.state="downloading";const e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`);for(let t=1;t<=H;t++){const s=new AbortController,n=setTimeout(()=>s.abort(),ue);try{const i=this.getUrl(),o={signal:s.signal};Object.keys(e).length>0&&(o.headers=e);const r=await fetch(i,o);if(!r.ok&&r.status!==206)throw new Error(`Fetch failed: ${r.status}`);return this.blob=await r.blob(),this.state="complete",this.blob}catch(i){const o=s.signal.aborted?`Timeout after ${ue/1e3}s`:i.message;if(t<H){const r=Ge*t,h=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";p.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${h} attempt ${t}/${H} failed: ${o}. Retrying in ${r/1e3}s...`),await new Promise(a=>setTimeout(a,r))}else throw this.state="failed",s.signal.aborted?new Error(o):i}finally{clearTimeout(n)}}}}class be{constructor(e,t={}){this.fileInfo=e,this.options=t,this.state="pending",this.tasks=[],this.completedChunks=0,this.totalChunks=0,this.totalBytes=0,this.downloadedBytes=0,this.onChunkDownloaded=null,this.skipChunks=e.skipChunks||new Set,this._contentType="application/octet-stream",this._chunkBlobs=new Map,this._runningCount=0,this._resolve=null,this._reject=null,this._promise=new Promise((s,n)=>{this._resolve=s,this._reject=n}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(ke(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return _e(e)}wait(){return this._promise}async prepare(e){try{this.state="preparing";const{id:t,type:s,size:n}=this.fileInfo;if(p.info("[FileDownload] Starting:",`${s}/${t}`),this.totalBytes=n&&n>0?parseInt(n):0,this._contentType=Xe(this.fileInfo),this.totalBytes===0){const o=this.getUrl(),r=new AbortController,h=setTimeout(()=>r.abort(),Ye);try{const a=await fetch(o,{method:"HEAD",signal:r.signal});a.ok&&(this.totalBytes=parseInt(a.headers.get("Content-Length")||"0"),this._contentType=a.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(h)}}p.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const i=this.options.chunkSize||me;if(this.totalBytes>He){const o=[];for(let c=0;c<this.totalBytes;c+=i)o.push({start:c,end:Math.min(c+i-1,this.totalBytes-1),index:o.length});this.totalChunks=o.length;const r=o.filter(c=>!this.skipChunks.has(c.index)),h=o.length-r.length;for(const c of o)this.skipChunks.has(c.index)&&(this.downloadedBytes+=c.end-c.start+1);if(r.length===0){p.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}h>0&&p.info(`[FileDownload] Resuming: ${h} chunks cached, ${r.length} to download`);const a=h>0;if(a){const c=r.sort((g,y)=>g.index-y.index);for(const g of c){const y=new G(this.fileInfo,{chunkIndex:g.index,rangeStart:g.start,rangeEnd:g.end});y._parentFile=this,y._priority=m.normal,this.tasks.push(y)}}else for(const c of r){const g=new G(this.fileInfo,{chunkIndex:c.index,rangeStart:c.start,rangeEnd:c.end});g._parentFile=this,g._priority=c.index===0||c.index===o.length-1?m.high:m.normal,this.tasks.push(g)}const u=this.tasks.filter(c=>c._priority>=m.high).length;p.info(`[FileDownload] ${s}/${t}: ${this.tasks.length} chunks`+(u>0?` (${u} priority)`:"")+(a?" (resume)":""))}else{this.totalChunks=1;const o=new G(this.fileInfo,{});o._parentFile=this,this.tasks.push(o)}e.enqueueChunkTasks(this.tasks),this.state="downloading"}catch(t){p.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){p.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)p.info("[FileDownload] Complete:",`${t}/${s}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)p.info("[FileDownload] Complete:",`${t}/${s}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const n=[];for(let o=0;o<this.totalChunks;o++){const r=this._chunkBlobs.get(o);r&&n.push(r)}const i=new Blob(n,{type:this._contentType});p.info("[FileDownload] Complete:",`${t}/${s}`,`(${i.size} bytes, reassembled)`),this._resolve(i)}this._chunkBlobs.clear()}}onTaskFailed(e,t){var s;if(!(this.state==="complete"||this.state==="failed")){if((s=t.message)!=null&&s.includes("URL expired")){const n=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";p.warn(`[FileDownload] URL expired, dropping${n}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(i=>i!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state="complete",this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}p.error("[FileDownload] Failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}}class lt{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const t=M.stableKey(e);if(this.queue.active.has(t)){const n=this.queue.active.get(t);if(e.path&&e.path!==n.fileInfo.path){const i=A(n.fileInfo.path);A(e.path)>i&&(n.fileInfo.path=e.path)}return n}const s=new be(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(t,s),this._filesToPrepare.push(s),s}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let t=0,s=0;const n=()=>{for(;t<this._maxPreparing&&s<this._filesToPrepare.length;){const i=this._filesToPrepare[s++];t++,i.prepare(this).finally(()=>{t--,s>=this._filesToPrepare.length&&t===0?e():n()})}};this._filesToPrepare.length===0?e():n()})}_sortWithBarriers(){var o;const e=[],t=[],s=[],n=[];for(const r of this._tasks)if(r.chunkIndex==null)e.push(r);else if(r.chunkIndex===0)t.push(r);else{const h=((o=r._parentFile)==null?void 0:o.totalChunks)||0;h>1&&r.chunkIndex===h-1?s.push(r):n.push(r)}e.sort((r,h)=>{var a,u;return(((a=r._parentFile)==null?void 0:a.totalBytes)||0)-(((u=h._parentFile)==null?void 0:u.totalBytes)||0)}),n.sort((r,h)=>r.chunkIndex-h.chunkIndex);const i=[...e,...t,...s];return n.length>0&&i.push(x,...n),i}}class M{constructor(e={}){this.concurrency=e.concurrency||Oe,this.chunkSize=e.chunkSize||me,this.maxChunksPerFile=e.chunksPerFile||We,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=M.stableKey(e);if(this.active.has(t)){const n=this.active.get(t);if(e.path&&e.path!==n.fileInfo.path){const i=A(n.fileInfo.path);A(e.path)>i&&(p.info("[DownloadQueue] Refreshing URL for",t),n.fileInfo.path=e.path)}return n}const s=new be(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(t,s),p.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(),p.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let t=0,s=0;for(const n of e)n===x?(this.queue.push(x),s++):(this.queue.push(n),t++);p.info(`[DownloadQueue] Ordered queue: ${t} tasks, ${s} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,t)=>t._priority-e._priority)}prioritize(e,t){const s=`${e}/${t}`,n=this.active.get(s);if(!n)return p.info("[DownloadQueue] Not found:",s),!1;let i=0;for(const o of this.queue)o._parentFile===n&&o._priority<m.high&&(o._priority=m.high,i++);return this._sortQueue(),p.info("[DownloadQueue] Prioritized:",s,`(${i} tasks boosted)`),!0}prioritizeLayoutFiles(e,t=m.high){var i,o;const s=new Set(e.map(String));let n=0;for(const r of this.queue)s.has(String((i=r._parentFile)==null?void 0:i.fileInfo.id))&&r._priority<t&&(r._priority=t,n++);for(const r of this._activeTasks)s.has(String((o=r._parentFile)==null?void 0:o.fileInfo.id))&&r._priority<t&&(r._priority=t);this._sortQueue(),p.info("[DownloadQueue] Layout files prioritized:",s.size,"files,",n,"tasks boosted to",t)}urgentChunk(e,t,s){const n=`${e}/${t}`,i=this.active.get(n);if(!i)return p.info("[DownloadQueue] urgentChunk: file not active:",n,"chunk",s),!1;if(this._activeTasks.some(a=>a._parentFile===i&&a.chunkIndex===s&&a.state==="downloading")){const a=this._activeTasks.find(u=>u._parentFile===i&&u.chunkIndex===s);return a&&a._priority<m.urgent?(a._priority=m.urgent,p.info(`[DownloadQueue] URGENT: ${n} chunk ${s} (already in-flight, limiting slots)`),!0):(p.info("[DownloadQueue] urgentChunk: already urgent:",n,"chunk",s),!1)}const r=this.queue.findIndex(a=>a!==x&&a._parentFile===i&&a.chunkIndex===s);if(r===-1)return p.info("[DownloadQueue] urgentChunk: chunk not in queue:",n,"chunk",s),!1;const h=this.queue.splice(r,1)[0];return h._priority=m.urgent,this.queue.unshift(h),p.info(`[DownloadQueue] URGENT: ${n} chunk ${s} (moved to front)`),this.processQueue(),!0}processQueue(){var n;if(this.paused)return;const e=this.queue.some(i=>i!==x&&i._priority>=m.urgent)||((n=this._activeTasks)==null?void 0:n.some(i=>i._priority>=m.urgent&&i.state==="downloading")),t=e?je:this.concurrency,s=e?m.urgent:0;for(;this.running<t&&this.queue.length>0;){const i=this.queue[0];if(i===x){if(this.running>0)break;this.queue.shift();continue}if(i._priority<s||!this._canStartTask(i)){let o=!1;for(let r=1;r<this.queue.length&&this.queue[r]!==x;r++){const h=this.queue[r];if(h._priority>=s&&this._canStartTask(h)){this.queue.splice(r,1),this._startTask(h),o=!0;break}}if(!o)break;continue}this.queue.shift(),this._startTask(i)}this.queue.length===0&&this.running===0&&p.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}`:"";p.info(`[DownloadQueue] Starting: ${t}${s} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(n=>n!==e),p.info(`[DownloadQueue] Fetched: ${t}${s} (${this.running} active, ${this.queue.length} pending)`),this.processQueue(),e._parentFile.onTaskComplete(e))).catch(n=>{this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(i=>i!==e),this.processQueue(),e._parentFile.onTaskFailed(e,n)})}awaitAllPrepared(){return new Promise(e=>{const t=()=>{this._preparingCount===0&&this._prepareQueue.length===0?e():setTimeout(t,50)};t()})}removeCompleted(e){const t=this.active.get(e);t&&(t.state==="complete"||t.state==="failed")&&(this.queue=this.queue.filter(s=>s===x||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 ht{constructor(e={}){this.queue=new M(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 v=L("CacheAnalyzer");function D(l){if(l===0)return"0 B";if(!Number.isFinite(l))return"∞";const e=["B","KB","MB","GB","TB"],t=Math.floor(Math.log(l)/Math.log(1024));return`${(l/Math.pow(1024,t)).toFixed(t>0?1:0)} ${e[t]}`}class ct{constructor(e,{threshold:t=80}={}){this.cache=e,this.threshold=t}async analyze(e){const t=await this.cache.getAllFiles(),s=await this._getStorageEstimate(),n=new Set(e.map(a=>String(a.id))),i=[],o=[];for(const a of t)if(n.has(String(a.id)))i.push(a);else if(a.type==="widget"){const u=String(a.id).split("/")[0];n.has(u)?i.push(a):o.push(a)}else o.push(a);o.sort((a,u)=>(a.cachedAt||0)-(u.cachedAt||0));const r=o.reduce((a,u)=>a+(u.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:i.length,orphaned:o.length,total:t.length},orphaned:o.map(a=>({id:a.id,type:a.type,size:a.size||0,cachedAt:a.cachedAt||0})),orphanedSize:r,evicted:[],threshold:this.threshold};if(v.info(`Storage: ${D(s.usage)} / ${D(s.quota)} (${h.storage.percent}%)`),v.info(`Cache: ${i.length} required, ${o.length} orphaned (${D(r)} reclaimable)`),o.length>0)for(const a of o){const u=Date.now()-(a.cachedAt||0),c=Math.floor(u/864e5),g=Math.floor(u%864e5/36e5),y=c>0?`${c}d ago`:`${g}h ago`;v.info(` Orphaned: ${a.type}/${a.id} (${D(a.size||0)}, cached ${y})`)}if(h.storage.percent>this.threshold&&o.length>0){v.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);const a=s.usage-s.quota*this.threshold/100;h.evicted=await this._evict(o,a)}else v.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){v.warn("Storage estimate unavailable:",t.message)}return{usage:0,quota:1/0}}async _evict(e,t){const s=[];let n=0;for(const i of e){if(n>=t)break;s.push(i),n+=i.size||0}if(s.length===0)return[];try{const i=s.map(o=>({type:o.type,id:o.id}));await this.cache.deleteFiles(i);for(const o of s)v.info(` Evicted: ${o.type}/${o.id} (${D(o.size||0)})`);v.info(`Evicted ${s.length} files, freed ${D(n)}`)}catch(i){return v.warn("Eviction failed:",i.message),[]}return s.map(i=>({id:i.id,type:i.type,size:i.size||0,cachedAt:i.cachedAt||0}))}}const k=L("Cache"),Ve="xibo-media-v1",E=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";async function ut(l,e,t,s){const n=`${E}/cache/widget/${l}/${e}/${t}`,i=await caches.open(Ve),o=`<base href="${E}/cache/media/">`;let r=s;s.includes("<base ")||(s.includes("<head>")?r=s.replace("<head>","<head>"+o):s.includes("<HEAD>")?r=s.replace("<HEAD>","<HEAD>"+o):r=o+s);const h=/https?:\/\/[^"'\s)]+(?:xmds\.php|pwa\/file)\?[^"'\s)]*file=([^&"'\s)]+)[^"'\s)]*/g,a=[];r=r.replace(h,(y,b)=>{const $=`${E}/cache/static/${b}`;return a.push({filename:b,originalUrl:y}),k.info(`Rewrote widget URL: ${b} → ${$}`),$});const u="<style>img,video{object-position:center center}</style>";r.includes("object-position:center center")||(r.includes("</head>")?r=r.replace("</head>",u+"</head>"):r.includes("</HEAD>")&&(r=r.replace("</HEAD>",u+"</HEAD>"))),r=r.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${E}/ic"`),k.info("Injected base tag and rewrote CMS/data URLs in widget HTML");const c=new URL(n,window.location.origin),g=new Response(r,{headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":"*"}});if(await i.put(c,g),k.info(`Stored widget HTML at ${n} (${r.length} bytes)`),a.length>0){const b=await caches.open("xibo-static-v1");await Promise.all(a.map(async({filename:$,originalUrl:$e})=>{const N=`${E}/cache/static/${$}`;if(!await b.match(N))try{const T=await fetch($e);if(!T.ok){k.warn(`Failed to fetch static resource: ${$} (HTTP ${T.status})`);return}const X=$.split(".").pop().toLowerCase(),V={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"}[X]||"application/octet-stream";if(X==="css"){let R=await T.text();const z=[],ve=/url\((['"]?)(https?:\/\/[^'")\s]+\?[^'")\s]*file=([^&'")\s]+\.(?:woff2?|ttf|otf|eot|svg))[^'")\s]*)\1\)/gi;R=R.replace(ve,(S,q,U,B)=>(z.push({filename:B,originalUrl:U}),k.info(`Rewrote font URL in CSS: ${B}`),`url(${q}${E}/cache/static/${encodeURIComponent(B)}${q})`)),await b.put(N,new Response(R,{headers:{"Content-Type":"text/css"}})),k.info(`Cached CSS with ${z.length} rewritten font URLs: ${$}`),await Promise.all(z.map(async({filename:S,originalUrl:q})=>{const U=`${E}/cache/static/${encodeURIComponent(S)}`;if(!await b.match(U))try{const I=await fetch(q);if(!I.ok){k.warn(`Failed to fetch font: ${S} (HTTP ${I.status})`);return}const Z=await I.blob(),Ce=S.split(".").pop().toLowerCase(),J={otf:"font/otf",ttf:"font/ttf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",svg:"image/svg+xml"}[Ce]||"application/octet-stream";await b.put(U,new Response(Z,{headers:{"Content-Type":J}})),k.info(`Cached font: ${S} (${J}, ${Z.size} bytes)`)}catch(I){k.warn(`Failed to cache font: ${S}`,I)}}))}else{const R=await T.blob();await b.put(N,new Response(R,{headers:{"Content-Type":V}})),k.info(`Cached static resource: ${$} (${V}, ${R.size} bytes)`)}}catch(T){k.warn(`Failed to cache static resource: ${$}`,T)}}))}return n}export{C as B,ct as C,ht as D,we as E,be as F,it as L,et as a,at as b,Y as c,Qe as d,lt as e,tt as f,ot as g,ut as h,ke as i,pe as r};
|
|
5
|
+
//# sourceMappingURL=widget-html-BzYo0-WO.js.map
|