@xiboplayer/pwa 0.7.20 → 0.7.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/assets/{main-C8f1ieZL.js → main-oacre7st.js} +4 -4
  2. package/dist/assets/{main-C8f1ieZL.js.map → main-oacre7st.js.map} +1 -1
  3. package/dist/assets/main-vwJkNw4Y.js +3 -0
  4. package/dist/assets/{main-BqJjhM5z.js.map → main-vwJkNw4Y.js.map} +1 -1
  5. package/dist/assets/{setup-Dpox3R4b.js → setup-B4gZX38p.js} +2 -2
  6. package/dist/assets/{setup-Dpox3R4b.js.map → setup-B4gZX38p.js.map} +1 -1
  7. package/dist/assets/{src-CIERor10.js → src-B_BNICay.js} +2 -2
  8. package/dist/assets/{src-CIERor10.js.map → src-B_BNICay.js.map} +1 -1
  9. package/dist/assets/{src-GjeUdI7b.js → src-Bjt9ooXK.js} +2 -2
  10. package/dist/assets/{src-GjeUdI7b.js.map → src-Bjt9ooXK.js.map} +1 -1
  11. package/dist/assets/{src-Bzheh5E2.js → src-BtVLiVYZ.js} +2 -2
  12. package/dist/assets/{src-Bzheh5E2.js.map → src-BtVLiVYZ.js.map} +1 -1
  13. package/dist/assets/{src-Cvcg0wpA.js → src-CKpVxGpH.js} +2 -2
  14. package/dist/assets/{src-Cvcg0wpA.js.map → src-CKpVxGpH.js.map} +1 -1
  15. package/dist/assets/{src-DzgDstdA.js → src-CROvYSP8.js} +2 -2
  16. package/dist/assets/{src-DzgDstdA.js.map → src-CROvYSP8.js.map} +1 -1
  17. package/dist/assets/{src-e2yErlKg.js → src-C_Lx4lXp.js} +2 -2
  18. package/dist/assets/{src-e2yErlKg.js.map → src-C_Lx4lXp.js.map} +1 -1
  19. package/dist/assets/{src-B0l-hkrA.js → src-Cx3tXAAu.js} +2 -2
  20. package/dist/assets/{src-B0l-hkrA.js.map → src-Cx3tXAAu.js.map} +1 -1
  21. package/dist/assets/{src-BLwxK97o.js → src-DAB0dqGG.js} +2 -2
  22. package/dist/assets/{src-BLwxK97o.js.map → src-DAB0dqGG.js.map} +1 -1
  23. package/dist/assets/{src-DTJp4-F0.js → src-WDu491CE.js} +2 -2
  24. package/dist/assets/{src-DTJp4-F0.js.map → src-WDu491CE.js.map} +1 -1
  25. package/dist/assets/{src-D_pit2UZ.js → src-cUopH0nN.js} +2 -2
  26. package/dist/assets/{src-D_pit2UZ.js.map → src-cUopH0nN.js.map} +1 -1
  27. package/dist/assets/{sync-manager-B6kqa4bv.js → sync-manager-8Z-qwkod.js} +2 -2
  28. package/dist/assets/{sync-manager-B6kqa4bv.js.map → sync-manager-8Z-qwkod.js.map} +1 -1
  29. package/dist/index.html +1 -1
  30. package/dist/setup.html +3 -3
  31. package/dist/sw-pwa.js +2 -2
  32. package/dist/sw-pwa.js.map +1 -1
  33. package/package.json +13 -13
  34. package/dist/assets/main-BqJjhM5z.js +0 -3
@@ -0,0 +1,3 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./main-oacre7st.js","./chunk-7ZXdHUL4.js","./preload-helper-Chd9yIcd.js","./src-B_BNICay.js","./src-BtVLiVYZ.js","./src-Cx3tXAAu.js","./src-CROvYSP8.js","./src-CKpVxGpH.js"])))=>i.map(i=>d[i]);
2
+ import"./modulepreload-polyfill-Cf3xff8G.js";import{t as e}from"./preload-helper-Chd9yIcd.js";window.__XIBO_REDIRECTING||e(()=>import(`./main-oacre7st.js`),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url);
3
+ //# sourceMappingURL=main-vwJkNw4Y.js.map
@@ -1 +1 @@
1
- {"version":3,"mappings":";8FACS,OAAO,oBACV,aAAO","names":[],"ignoreList":[],"sources":["../../index.html?html-proxy&index=1.js"],"sourcesContent":["\n if (!window.__XIBO_REDIRECTING) {\n import('/src/main.ts');\n }\n "],"file":"main-BqJjhM5z.js"}
1
+ {"version":3,"mappings":";8FACS,OAAO,oBACV,aAAO","names":[],"ignoreList":[],"sources":["../../index.html?html-proxy&index=1.js"],"sourcesContent":["\n if (!window.__XIBO_REDIRECTING) {\n import('/src/main.ts');\n }\n "],"file":"main-vwJkNw4Y.js"}
@@ -1,2 +1,2 @@
1
- import"./modulepreload-polyfill-Cf3xff8G.js";import{i as e}from"./src-Bzheh5E2.js";import{n as t,r as n}from"./src-GjeUdI7b.js";var r=`0.7.20`;document.getElementById(`version-footer`).textContent=`xiboplayer v${r}`;var i=document.getElementById(`setup-form`),a=document.getElementById(`error`),o=document.getElementById(`submit-btn`),s=document.getElementById(`phase-unlock`),c=document.getElementById(`phase-setup`),l=document.getElementById(`phase-waiting`),u=document.getElementById(`countdown`),d=document.getElementById(`waiting-display-name`),f=document.getElementById(`btn-back`),p=document.getElementById(`success-flash`),m=e.hardwareKey;document.getElementById(`hw-key-display`).textContent=m,document.getElementById(`hw-key-waiting`).textContent=m;var h=e.cmsUrl||``,g=null,_=null,v=15,y=null;async function b(){if(y)return y;try{let t=new n(e);await t.registerDisplay(),console.log(`[Setup] Using REST transport`),y=t}catch(n){console.log(`[Setup] REST unavailable, using XMDS/SOAP:`,n.message),y=new t(e)}return y}function x(e){s.classList.remove(`active`),c.classList.remove(`active`),l.classList.remove(`active`),e.classList.add(`active`)}function S(e){a.textContent=e,a.style.display=`block`}function C(){a.style.display=`none`}function w(){let e=v;u.textContent=e,clearInterval(_),_=setInterval(()=>{e--,u.textContent=Math.max(0,e),e<=0&&clearInterval(_)},1e3)}async function T(){if(document.getElementById(`cms-url`).value.trim().replace(/\/$/,``)!==h){console.log(`[Setup] CMS URL changed — wiping cached content`);let e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}p.classList.add(`active`),setTimeout(()=>{window.location.href=`/player/index.html`+window.location.search},800)}async function E(){try{let e=await(await b()).registerDisplay();if(console.log(`[Setup] Poll result:`,e.code,e.message),e.code===`READY`){clearInterval(g),clearInterval(_),T();return}w()}catch(e){console.warn(`[Setup] Poll failed:`,e.message),w()}}function D(e){d.textContent=e,x(l),w(),g=setInterval(E,v*1e3)}function O(){clearInterval(g),clearInterval(_),g=null}async function k(t,n){let r=document.getElementById(`api-client-id`).value.trim(),i=document.getElementById(`api-client-secret`).value.trim();if(!r||!i)return!1;try{let t=await fetch(`/api/authorize/access_token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:r,client_secret:i})});if(!t.ok)throw Error(`OAuth2 failed: ${t.status}`);let{access_token:a}=await t.json(),o=await fetch(`/api/display?hardwareKey=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${a}`}});if(!o.ok)throw Error(`Find display failed: ${o.status}`);let s=await o.json();if(!s.length)return console.log(`[Setup] Display not found via API (may not be registered yet)`),!1;let c=s[0];if(c.licensed===1)return console.log(`[Setup] Display already authorized`),!0;let l=await fetch(`/api/display/authorise/${c.displayId}`,{method:`PUT`,headers:{Authorization:`Bearer ${a}`}});if(!l.ok)throw Error(`Authorize failed: ${l.status}`);return console.log(`[Setup] Display auto-authorized via proxy!`),e.data.apiClientId=r,e.data.apiClientSecret=i,!0}catch(e){return console.warn(`[Setup] Auto-authorize failed:`,e.message),!1}}var A=e.isConfigured()&&e.cmsKey,j=new URLSearchParams(window.location.search).has(`unlocked`),M=document.getElementById(`btn-back-player`);A&&!j&&x(s),(A||j)&&(M.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.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``));function N(){O(),window.location.href=`/player/index.html`+window.location.search}M.addEventListener(`click`,N),(A||j)&&document.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),N())}),document.getElementById(`unlock-form`).addEventListener(`submit`,t=>{t.preventDefault();let 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.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``),x(c)):(n.textContent=`Incorrect CMS key`,n.style.display=`block`)}),!A&&e.isConfigured()&&(document.getElementById(`cms-url`).value=e.cmsUrl,document.getElementById(`cms-key`).value=e.cmsKey,document.getElementById(`display-name`).value=e.displayName,e.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``)),i.addEventListener(`submit`,async t=>{t.preventDefault(),C();let n=document.getElementById(`cms-url`).value.trim().replace(/\/$/,``),r=document.getElementById(`cms-key`).value.trim(),i=document.getElementById(`display-name`).value.trim();try{if(o.textContent=`Saving...`,o.disabled=!0,!(await fetch(`/config`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cmsUrl:n,cmsKey:r,displayName:i})})).ok)throw Error(`Failed to save config`);let t=window.electronAPI||window.parent?.electronAPI;t?.setConfig&&await t.setConfig({cmsUrl:n,cmsKey:r,displayName:i}),e.data.cmsUrl=n,e.data.cmsKey=r,e.data.displayName=i,e.save(),P(e.hardwareKey),o.textContent=`Connecting...`,y=null;let a=await b();if((await a.registerDisplay()).code===`READY`)T();else{if(o.textContent=`Authorizing...`,await k(n,m)&&(e.save(),await fetch(`/config`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({apiClientId:e.data.apiClientId,apiClientSecret:e.data.apiClientSecret})}),t?.setConfig&&await t.setConfig({apiClientId:e.data.apiClientId,apiClientSecret:e.data.apiClientSecret}),(await a.registerDisplay()).code===`READY`)){T();return}D(i)}}catch(e){S(`Connection failed: ${e.message}`),o.textContent=`Connect`,o.disabled=!1}}),f.addEventListener(`click`,()=>{O(),x(c),o.textContent=`Connect`,o.disabled=!1});async function P(e){try{let t=indexedDB.open(`xibo-hw-backup`,1);t.onupgradeneeded=()=>{let e=t.result;e.objectStoreNames.contains(`keys`)||e.createObjectStore(`keys`)},t.onsuccess=()=>{let n=t.result,r=n.transaction(`keys`,`readwrite`);r.objectStore(`keys`).put(e,`hardwareKey`),r.oncomplete=()=>n.close()}}catch(e){console.warn(`[Setup] IndexedDB backup failed:`,e)}}o.disabled=!1,o.textContent=`Connect`,e.isConfigured()&&!A&&(async()=>{try{(await(await b()).registerDisplay()).code===`READY`?window.location.href=`/player/index.html`+window.location.search:D(e.displayName)}catch{console.log(`[Setup] Auto-check failed, showing form`)}})();
2
- //# sourceMappingURL=setup-Dpox3R4b.js.map
1
+ import"./modulepreload-polyfill-Cf3xff8G.js";import{i as e}from"./src-BtVLiVYZ.js";import{n as t,r as n}from"./src-Bjt9ooXK.js";var r=`0.7.21`;document.getElementById(`version-footer`).textContent=`xiboplayer v${r}`;var i=document.getElementById(`setup-form`),a=document.getElementById(`error`),o=document.getElementById(`submit-btn`),s=document.getElementById(`phase-unlock`),c=document.getElementById(`phase-setup`),l=document.getElementById(`phase-waiting`),u=document.getElementById(`countdown`),d=document.getElementById(`waiting-display-name`),f=document.getElementById(`btn-back`),p=document.getElementById(`success-flash`),m=e.hardwareKey;document.getElementById(`hw-key-display`).textContent=m,document.getElementById(`hw-key-waiting`).textContent=m;var h=e.cmsUrl||``,g=null,_=null,v=15,y=null;async function b(){if(y)return y;try{let t=new n(e);await t.registerDisplay(),console.log(`[Setup] Using REST transport`),y=t}catch(n){console.log(`[Setup] REST unavailable, using XMDS/SOAP:`,n.message),y=new t(e)}return y}function x(e){s.classList.remove(`active`),c.classList.remove(`active`),l.classList.remove(`active`),e.classList.add(`active`)}function S(e){a.textContent=e,a.style.display=`block`}function C(){a.style.display=`none`}function w(){let e=v;u.textContent=e,clearInterval(_),_=setInterval(()=>{e--,u.textContent=Math.max(0,e),e<=0&&clearInterval(_)},1e3)}async function T(){if(document.getElementById(`cms-url`).value.trim().replace(/\/$/,``)!==h){console.log(`[Setup] CMS URL changed — wiping cached content`);let e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}p.classList.add(`active`),setTimeout(()=>{window.location.href=`/player/index.html`+window.location.search},800)}async function E(){try{let e=await(await b()).registerDisplay();if(console.log(`[Setup] Poll result:`,e.code,e.message),e.code===`READY`){clearInterval(g),clearInterval(_),T();return}w()}catch(e){console.warn(`[Setup] Poll failed:`,e.message),w()}}function D(e){d.textContent=e,x(l),w(),g=setInterval(E,v*1e3)}function O(){clearInterval(g),clearInterval(_),g=null}async function k(t,n){let r=document.getElementById(`api-client-id`).value.trim(),i=document.getElementById(`api-client-secret`).value.trim();if(!r||!i)return!1;try{let t=await fetch(`/api/authorize/access_token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:r,client_secret:i})});if(!t.ok)throw Error(`OAuth2 failed: ${t.status}`);let{access_token:a}=await t.json(),o=await fetch(`/api/display?hardwareKey=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${a}`}});if(!o.ok)throw Error(`Find display failed: ${o.status}`);let s=await o.json();if(!s.length)return console.log(`[Setup] Display not found via API (may not be registered yet)`),!1;let c=s[0];if(c.licensed===1)return console.log(`[Setup] Display already authorized`),!0;let l=await fetch(`/api/display/authorise/${c.displayId}`,{method:`PUT`,headers:{Authorization:`Bearer ${a}`}});if(!l.ok)throw Error(`Authorize failed: ${l.status}`);return console.log(`[Setup] Display auto-authorized via proxy!`),e.data.apiClientId=r,e.data.apiClientSecret=i,!0}catch(e){return console.warn(`[Setup] Auto-authorize failed:`,e.message),!1}}var A=e.isConfigured()&&e.cmsKey,j=new URLSearchParams(window.location.search).has(`unlocked`),M=document.getElementById(`btn-back-player`);A&&!j&&x(s),(A||j)&&(M.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.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``));function N(){O(),window.location.href=`/player/index.html`+window.location.search}M.addEventListener(`click`,N),(A||j)&&document.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),N())}),document.getElementById(`unlock-form`).addEventListener(`submit`,t=>{t.preventDefault();let 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.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``),x(c)):(n.textContent=`Incorrect CMS key`,n.style.display=`block`)}),!A&&e.isConfigured()&&(document.getElementById(`cms-url`).value=e.cmsUrl,document.getElementById(`cms-key`).value=e.cmsKey,document.getElementById(`display-name`).value=e.displayName,e.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``)),i.addEventListener(`submit`,async t=>{t.preventDefault(),C();let n=document.getElementById(`cms-url`).value.trim().replace(/\/$/,``),r=document.getElementById(`cms-key`).value.trim(),i=document.getElementById(`display-name`).value.trim();try{if(o.textContent=`Saving...`,o.disabled=!0,!(await fetch(`/config`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cmsUrl:n,cmsKey:r,displayName:i})})).ok)throw Error(`Failed to save config`);let t=window.electronAPI||window.parent?.electronAPI;t?.setConfig&&await t.setConfig({cmsUrl:n,cmsKey:r,displayName:i}),e.data.cmsUrl=n,e.data.cmsKey=r,e.data.displayName=i,e.save(),P(e.hardwareKey),o.textContent=`Connecting...`,y=null;let a=await b();if((await a.registerDisplay()).code===`READY`)T();else{if(o.textContent=`Authorizing...`,await k(n,m)&&(e.save(),await fetch(`/config`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({apiClientId:e.data.apiClientId,apiClientSecret:e.data.apiClientSecret})}),t?.setConfig&&await t.setConfig({apiClientId:e.data.apiClientId,apiClientSecret:e.data.apiClientSecret}),(await a.registerDisplay()).code===`READY`)){T();return}D(i)}}catch(e){S(`Connection failed: ${e.message}`),o.textContent=`Connect`,o.disabled=!1}}),f.addEventListener(`click`,()=>{O(),x(c),o.textContent=`Connect`,o.disabled=!1});async function P(e){try{let t=indexedDB.open(`xibo-hw-backup`,1);t.onupgradeneeded=()=>{let e=t.result;e.objectStoreNames.contains(`keys`)||e.createObjectStore(`keys`)},t.onsuccess=()=>{let n=t.result,r=n.transaction(`keys`,`readwrite`);r.objectStore(`keys`).put(e,`hardwareKey`),r.oncomplete=()=>n.close()}}catch(e){console.warn(`[Setup] IndexedDB backup failed:`,e)}}o.disabled=!1,o.textContent=`Connect`,e.isConfigured()&&!A&&(async()=>{try{(await(await b()).registerDisplay()).code===`READY`?window.location.href=`/player/index.html`+window.location.search:D(e.displayName)}catch{console.log(`[Setup] Auto-check failed, showing form`)}})();
2
+ //# sourceMappingURL=setup-B4gZX38p.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"setup-Dpox3R4b.js","names":[],"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 = `xiboplayer 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' + window.location.search;\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 /api/* forward proxy) ──\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('/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 `/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 `/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.data.apiClientId = clientId;\n config.data.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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.apiClientSecret || '';\n }\n }\n\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = '/player/index.html' + window.location.search;\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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.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 // Always POST to proxy — updates in-memory config for REST auth,\n // cache-through, and API forwarding. Works on all players.\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 // Shell persistence (Electron config.json) — optional, on top of proxy\n const electronAPI = window.electronAPI || window.parent?.electronAPI;\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ cmsUrl, cmsKey, displayName });\n }\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 // Persist API client credentials so they survive restarts\n config.save();\n await fetch('/config', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret }),\n });\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret });\n }\n\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' + window.location.search;\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 "],"mappings":"gIAKI,IAAM,EAAA,SACN,SAAS,eAAe,iBAAiB,CAAC,YAAc,eAAe,IA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AAe,EAAkB,EAAK,CACpC,GAAI,CACF,IAAM,EAAM,UAAU,KAAK,iBAAkB,EAAE,CAC/C,EAAI,oBAAwB,CAC1B,IAAM,EAAK,EAAI,OACV,EAAG,iBAAiB,SAAS,OAAO,EACvC,EAAG,kBAAkB,OAAO,EAGhC,EAAI,cAAkB,CACpB,IAAM,EAAK,EAAI,OACT,EAAK,EAAG,YAAY,OAAQ,YAAY,CAC9C,EAAG,YAAY,OAAO,CAAC,IAAI,EAAK,cAAc,CAC9C,EAAG,eAAmB,EAAG,OAAO,QAE3B,EAAG,CACV,QAAQ,KAAK,mCAAoC,EAAE,EAKvD,EAAU,SAAW,GACrB,EAAU,YAAc,UAIpB,EAAO,cAAc,EAAI,CAAC,IAC3B,SAAY,CACX,GAAI,EAEa,MADA,MAAM,GAAc,EACP,iBAAiB,EAClC,OAAS,QAClB,OAAO,SAAS,KAAO,qBAAuB,OAAO,SAAS,OAG9D,EAAa,EAAO,YAAY,MAExB,CAEV,QAAQ,IAAI,0CAA0C,KAEtD"}
1
+ {"version":3,"file":"setup-B4gZX38p.js","names":[],"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 = `xiboplayer 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' + window.location.search;\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 /api/* forward proxy) ──\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('/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 `/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 `/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.data.apiClientId = clientId;\n config.data.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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.apiClientSecret || '';\n }\n }\n\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = '/player/index.html' + window.location.search;\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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.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.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.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 // Always POST to proxy — updates in-memory config for REST auth,\n // cache-through, and API forwarding. Works on all players.\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 // Shell persistence (Electron config.json) — optional, on top of proxy\n const electronAPI = window.electronAPI || window.parent?.electronAPI;\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ cmsUrl, cmsKey, displayName });\n }\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 // Persist API client credentials so they survive restarts\n config.save();\n await fetch('/config', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret }),\n });\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret });\n }\n\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' + window.location.search;\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 "],"mappings":"gIAKI,IAAM,EAAA,SACN,SAAS,eAAe,iBAAiB,CAAC,YAAc,eAAe,IAGvE,IAAM,EAAO,SAAS,eAAe,aAAa,CAC5C,EAAU,SAAS,eAAe,QAAQ,CA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AE,CAC/C,EAAI,oBAAwB,CAC1B,IAAM,EAAK,EAAI,OACV,EAAG,iBAAiB,SAAS,OAAO,EACvC,EAAG,kBAAkB,OAAO,EAGhC,EAAI,cAAkB,CACpB,IAAM,EAAK,EAAI,OACT,EAAK,EAAG,YAAY,OAAQ,YAAY,CAC9C,EAAG,YAAY,OAAO,CAAC,IAAI,EAAK,cAAc,CAC9C,EAAG,eAAmB,EAAG,OAAO,QAE3B,EAAG,CACV,QAAQ,KAAK,mCAAoC,EAAE,EAKvD,EAAU,SAAW,GACrB,EAAU,YAAc,UAIpB,EAAO,cAAc,EAAI,CAAC,IAC3B,SAAY,CACX,GAAI,EAEa,MADA,MAAM,GAAc,EACP,iBAAiB,EAClC,OAAS,QAClB,OAAO,SAAS,KAAO,qBAAuB,OAAO,SAAS,OAG9D,EAAa,EAAO,YAAY,MAExB,CAEV,QAAQ,IAAI,0CAA0C,KAEtD"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-7ZXdHUL4.js";import{t,u as n}from"./src-Bzheh5E2.js";var r={name:`@xiboplayer/cache`,version:`0.7.20`,description:`Offline caching and download management with parallel chunk downloads`,type:`module`,main:`./src/index.js`,types:`./src/index.d.ts`,exports:{".":`./src/index.js`,"./cache":`./src/cache.js`,"./store-client":`./src/store-client.js`,"./download-manager":`./src/download-manager.js`,"./cache-analyzer":`./src/cache-analyzer.js`,"./widget-html":`./src/widget-html.js`},scripts:{test:`vitest run`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`},dependencies:{"@xiboplayer/utils":`workspace:*`,"spark-md5":`^3.0.2`},devDependencies:{jsdom:`^29.0.2`,vitest:`^4.1.2`},keywords:[`xibo`,`digital-signage`,`cache`,`offline`,`download`,`indexeddb`],author:`Pau Aliagas <linuxnow@gmail.com>`,license:`AGPL-3.0-or-later`,repository:{type:`git`,url:`git+https://github.com/xibo-players/xiboplayer.git`,directory:`packages/cache`},homepage:`https://xiboplayer.org`},i=n(`Cache`),a=class{constructor(){this.dependants=new Map}addDependant(e,t){let n=String(e);this.dependants.has(n)||this.dependants.set(n,new Set),this.dependants.get(n).add(String(t))}removeLayoutDependants(e){let t=String(e),n=[];for(let[e,r]of this.dependants)r.delete(t),r.size===0&&(this.dependants.delete(e),n.push(e));return n.length>0&&i.info(`${n.length} media files orphaned after layout ${e} removed:`,n),n}isMediaReferenced(e){let t=this.dependants.get(String(e));return t?t.size>0:!1}async clearAll(){this.dependants.clear()}},o=new a,s=n(`StoreClient`),c=class{async has(e,t){try{let n=await fetch(`/store/${e}/${t}`,{method:`HEAD`});if(n.status===204)return!1;if(n.status===200)return n.headers.get(`X-Store-Complete`)!==`false`;if(n.status===404)return!1;let r=Error(`Store error: ${n.status}`);throw r.status=n.status,s.warn(`has(${e}/${t}): unexpected status ${n.status}`),r}catch(n){throw n.status||n.name===`AbortError`||n.name===`TimeoutError`||s.warn(`has(${e}/${t}): network error — ${n.message}`),n}}async get(e,t){try{let n=await fetch(`/store/${e}/${t}`);if(n.status===204||n.status===404)return n.body?.cancel(),null;if(!n.ok)throw n.body?.cancel(),Error(`Failed to get file: ${n.status}`);return await n.blob()}catch(e){return s.error(`get error:`,e.message),null}}async put(e,t,n,r=`application/octet-stream`){try{let i=await fetch(`/store/${e}/${t}`,{method:`PUT`,headers:{"Content-Type":r},body:n});return i.body?.cancel(),i.ok}catch(e){return s.error(`put error:`,e.message),!1}}async remove(e){try{let t=await(await fetch(`/store/delete`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({files:e})})).json();return{deleted:t.deleted||0,total:t.total||e.length}}catch(t){return s.error(`remove error:`,t.message),{deleted:0,total:e.length}}}async list(){try{return(await(await fetch(`/store/list`)).json()).files||[]}catch(e){return s.error(`list error:`,e.message),[]}}},l={media:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},layout:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},dataset:{maxRetries:4,retryDelayMs:0,retryDelays:[15e3,3e4,6e4,12e4],maxReenqueues:5,reenqueueDelayMs:6e4,skipHead:!0,cacheTtl:300},static:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0}};function u(e){return l[e]||l.media}var d=n(`Download`),f=6,p=50*1024*1024,m=3,h=100*1024*1024,g=2,_=6e5,v=15e3;function y(e){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`}[(e.path||e.code||``).split(`.`).pop()?.split(`?`)[0]?.toLowerCase()]||`application/octet-stream`}var b={normal:0,layout:1,high:2,urgent:3},x=Symbol(`BARRIER`);function S(e){try{let t=new URL(e,`http://localhost`),n=t.searchParams.get(`X-Amz-Date`),r=t.searchParams.get(`X-Amz-Expires`);if(n&&r){let e=n.replace(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/,`$1-$2-$3T$4:$5:$6Z`),t=new Date(e).getTime()/1e3;return isNaN(t)?1/0:t+parseInt(r,10)}return 1/0}catch{return 1/0}}function C(e,t=30){let n=S(e);return n===1/0?!1:Date.now()/1e3>=n-t}var 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=b.normal,this._typeConfig=u(e.type)}getUrl(){let e=this.fileInfo.path;if(C(e))throw Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}async start(){this.state=`downloading`;let e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`),this.chunkIndex!=null&&(e[`X-Store-Chunk-Index`]=String(this.chunkIndex),this._parentFile&&(e[`X-Store-Num-Chunks`]=String(this._parentFile.totalChunks),e[`X-Store-Chunk-Size`]=String(this._parentFile.options.chunkSize||104857600))),this.fileInfo.md5&&(e[`X-Store-MD5`]=this.fileInfo.md5),this.fileInfo.updateInterval&&(e[`X-Cache-TTL`]=String(this.fileInfo.updateInterval)),this.fileInfo.cmsDownloadUrl&&(e[`X-Cms-Download-Url`]=this.fileInfo.cmsDownloadUrl);let t=this._typeConfig.maxRetries;for(let n=1;n<=t;n++){let r=new AbortController,i=setTimeout(()=>r.abort(),_);try{let t=this.getUrl(),n={signal:r.signal};Object.keys(e).length>0&&(n.headers=e);let i=await fetch(t,n);if(!i.ok&&i.status!==206)throw Error(`Fetch failed: ${i.status}`);return this.blob=await i.blob(),this.state=`complete`,this.blob}catch(e){let i=r.signal.aborted?`Timeout after ${_/1e3}s`:e.message;if(n<t){let e=this._typeConfig.retryDelays?.[n-1]??this._typeConfig.retryDelayMs*n,r=this.chunkIndex==null?``:` chunk ${this.chunkIndex}`;d.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${r} attempt ${n}/${t} failed: ${i}. Retrying in ${e/1e3}s...`),await new Promise(t=>setTimeout(t,e))}else throw this.state=`failed`,r.signal.aborted?Error(i):e}finally{clearTimeout(i)}}}},T=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((e,t)=>{this._resolve=e,this._reject=t}),this._promise.catch(()=>{})}getUrl(){let e=this.fileInfo.path;if(C(e))throw Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}wait(){return this._promise}async prepare(e){try{this.state=`preparing`;let{id:t,type:n,size:r}=this.fileInfo;d.info(`[FileDownload] Starting:`,`${n}/${t}`),this.totalBytes=r&&r>0?parseInt(r):0,this._contentType=y(this.fileInfo);let i=u(this.fileInfo.type).skipHead;if(this.totalBytes===0&&!i){let e=this.getUrl(),t=new AbortController,n=setTimeout(()=>t.abort(),v);try{let n=await fetch(e,{method:`HEAD`,signal:t.signal});n.ok&&(this.totalBytes=parseInt(n.headers.get(`Content-Length`)||`0`),this._contentType=n.headers.get(`Content-Type`)||this._contentType)}finally{clearTimeout(n)}}d.info(`[FileDownload] File size:`,(this.totalBytes/1024/1024).toFixed(1),`MB`);let a=this.options.chunkSize||p;if(this.totalBytes>h){let e=[];for(let t=0;t<this.totalBytes;t+=a)e.push({start:t,end:Math.min(t+a-1,this.totalBytes-1),index:e.length});this.totalChunks=e.length;let r=e.filter(e=>!this.skipChunks.has(e.index)),i=e.length-r.length;for(let t of e)this.skipChunks.has(t.index)&&(this.downloadedBytes+=t.end-t.start+1);if(r.length===0){d.info(`[FileDownload] All chunks already cached, nothing to download`),this.state=`complete`,this._resolve(new Blob([],{type:this._contentType}));return}i>0&&d.info(`[FileDownload] Resuming: ${i} chunks cached, ${r.length} to download`);let o=i>0;if(o){let e=r.sort((e,t)=>e.index-t.index);for(let t of e){let e=new w(this.fileInfo,{chunkIndex:t.index,rangeStart:t.start,rangeEnd:t.end});e._parentFile=this,e._priority=b.normal,this.tasks.push(e)}}else for(let t of r){let n=new w(this.fileInfo,{chunkIndex:t.index,rangeStart:t.start,rangeEnd:t.end});n._parentFile=this,n._priority=t.index===0||t.index===e.length-1?b.high:b.normal,this.tasks.push(n)}let s=this.tasks.filter(e=>e._priority>=b.high).length;d.info(`[FileDownload] ${n}/${t}: ${this.tasks.length} chunks`+(s>0?` (${s} priority)`:``)+(o?` (resume)`:``))}else{this.totalChunks=1;let e=new w(this.fileInfo,{});e._parentFile=this,this.tasks.push(e)}e.enqueueChunkTasks(this.tasks),this.state=`downloading`}catch(e){d.error(`[FileDownload] Prepare failed:`,`${this.fileInfo.type}/${this.fileInfo.id}`,e),this.state=`failed`,this._reject(e)}}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(e){d.warn(`[FileDownload] onChunkDownloaded callback error:`,e)}if(this.completedChunks===this.tasks.length&&this.state!==`complete`){this.state=`complete`;let{type:t,id:n}=this.fileInfo;if(e.chunkIndex==null)d.info(`[FileDownload] Complete:`,`${t}/${n}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)d.info(`[FileDownload] Complete:`,`${t}/${n}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{let e=[];for(let t=0;t<this.totalChunks;t++){let n=this._chunkBlobs.get(t);n&&e.push(n)}let r=new Blob(e,{type:this._contentType});d.info(`[FileDownload] Complete:`,`${t}/${n}`,`(${r.size} bytes, reassembled)`),this._resolve(r)}this._chunkBlobs.clear()}}onTaskFailed(e,t){if(!(this.state===`complete`||this.state===`failed`)){if(t.message?.includes(`URL expired`)){let t=e.chunkIndex==null?``:` chunk ${e.chunkIndex}`;d.warn(`[FileDownload] URL expired, dropping${t}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(t=>t!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state=`complete`,this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}d.error(`[FileDownload] Failed:`,`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state=`failed`,this._reject(t)}}},E=class{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){let t=D.stableKey(e);if(this.queue.active.has(t)){let n=this.queue.active.get(t);if(e.path&&e.path!==n.fileInfo.path){let t=S(n.fileInfo.path);S(e.path)>t&&(n.fileInfo.path=e.path)}return n}let n=new T(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(t,n),this._filesToPrepare.push(n),n}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let t=0,n=0,r=()=>{for(;t<this._maxPreparing&&n<this._filesToPrepare.length;){let i=this._filesToPrepare[n++];t++,i.prepare(this).finally(()=>{t--,n>=this._filesToPrepare.length&&t===0?e():r()})}};this._filesToPrepare.length===0?e():r()})}_sortWithBarriers(){let e=[],t=[],n=[],r=[];for(let i of this._tasks)if(i.chunkIndex==null)e.push(i);else if(i.chunkIndex===0)t.push(i);else{let e=i._parentFile?.totalChunks||0;e>1&&i.chunkIndex===e-1?n.push(i):r.push(i)}e.sort((e,t)=>(e._parentFile?.totalBytes||0)-(t._parentFile?.totalBytes||0)),r.sort((e,t)=>e.chunkIndex-t.chunkIndex);let i=[...e,...t,...n];return r.length>0&&i.push(x,...r),i}},D=class e{constructor(e={}){this.concurrency=e.concurrency||f,this.chunkSize=e.chunkSize||p,this.maxChunksPerFile=e.chunksPerFile||m,this.calculateMD5=e.calculateMD5,this.onProgress=e.onProgress,this.queue=[],this.active=new Map,this._activeTasks=[],this.running=0,this._prepareQueue=[],this._preparingCount=0,this._maxPreparing=2,this.paused=!1,this._reenqueueTimers=new Set}static stableKey(e){return`${e.type}/${e.id}`}enqueue(t){let n=e.stableKey(t);if(this.active.has(n)){let e=this.active.get(n);if(t.path&&t.path!==e.fileInfo.path){let r=S(e.fileInfo.path);S(t.path)>r&&(d.info(`[DownloadQueue] Refreshing URL for`,n),e.fileInfo.path=t.path)}return e}let r=new T(t,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(n,r),d.info(`[DownloadQueue] Enqueued:`,n),this._schedulePrepare(r),r}_schedulePrepare(e){this._prepareQueue.push(e),this._processPrepareQueue()}_processPrepareQueue(){for(;this._preparingCount<this._maxPreparing&&this._prepareQueue.length>0;){let e=this._prepareQueue.shift();this._preparingCount++,e.prepare(this).finally(()=>{this._preparingCount--,this._processPrepareQueue()})}}enqueueChunkTasks(e){for(let t of e)this.queue.push(t);this._sortQueue(),d.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let t=0,n=0;for(let r of e)r===x?(this.queue.push(x),n++):(this.queue.push(r),t++);d.info(`[DownloadQueue] Ordered queue: ${t} tasks, ${n} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,t)=>t._priority-e._priority)}prioritizeLayoutFiles(e,t=b.high){let n=new Set(e.map(String)),r=0;for(let e of this.queue){let i=e._parentFile?.fileInfo.saveAs||String(e._parentFile?.fileInfo.id);n.has(i)&&e._priority<t&&(e._priority=t,r++)}for(let e of this._activeTasks){let r=e._parentFile?.fileInfo.saveAs||String(e._parentFile?.fileInfo.id);n.has(r)&&e._priority<t&&(e._priority=t)}this._sortQueue(),d.info(`[DownloadQueue] Layout files prioritized:`,n.size,`files,`,r,`tasks boosted to`,t)}urgentChunk(e,t,n){let r=`${e}/${t}`,i=this.active.get(r);if(!i)return d.info(`[DownloadQueue] urgentChunk: file not active:`,r,`chunk`,n),!1;if(this._activeTasks.some(e=>e._parentFile===i&&e.chunkIndex===n&&e.state===`downloading`)){let e=this._activeTasks.find(e=>e._parentFile===i&&e.chunkIndex===n);return e&&e._priority<b.urgent?(e._priority=b.urgent,d.info(`[DownloadQueue] URGENT: ${r} chunk ${n} (already in-flight, limiting slots)`),!0):(d.info(`[DownloadQueue] urgentChunk: already urgent:`,r,`chunk`,n),!1)}let a=this.queue.findIndex(e=>e!==x&&e._parentFile===i&&e.chunkIndex===n);if(a===-1)return d.info(`[DownloadQueue] urgentChunk: chunk not in queue:`,r,`chunk`,n),!1;let o=this.queue.splice(a,1)[0];return o._priority=b.urgent,this.queue.unshift(o),d.info(`[DownloadQueue] URGENT: ${r} chunk ${n} (moved to front)`),this.processQueue(),!0}processQueue(){if(this.paused)return;let e=this.queue.some(e=>e!==x&&e._priority>=b.urgent)||this._activeTasks?.some(e=>e._priority>=b.urgent&&e.state===`downloading`),t=e?g:this.concurrency,n=e?b.urgent:0;for(;this.running<t&&this.queue.length>0;){let e=this.queue[0];if(e===x){if(this.running>0)break;this.queue.shift();continue}if(e._priority<n||!this._canStartTask(e)){let e=!1;for(let t=1;t<this.queue.length&&this.queue[t]!==x;t++){let r=this.queue[t];if(r._priority>=n&&this._canStartTask(r)){this.queue.splice(t,1),this._startTask(r),e=!0;break}}if(!e)break;continue}this.queue.shift(),this._startTask(e)}this.queue.length===0&&this.running===0&&d.info(`[DownloadQueue] All downloads complete`)}_canStartTask(e){return e._parentFile._runningCount<this.maxChunksPerFile}_startTask(e){this.running++,e._parentFile._runningCount++,this._activeTasks.push(e);let t=`${e.fileInfo.type}/${e.fileInfo.id}`,n=e.chunkIndex==null?``:` chunk ${e.chunkIndex}`;d.info(`[DownloadQueue] Starting: ${t}${n} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(t=>t!==e),d.info(`[DownloadQueue] Fetched: ${t}${n} (${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(t=>t!==e);let{maxReenqueues:r,reenqueueDelayMs:i}=e._typeConfig;if(r>0){if(e._reenqueueCount=(e._reenqueueCount||0)+1,e._reenqueueCount>r){d.error(`[DownloadQueue] ${t} exceeded ${r} re-enqueues, failing permanently`),this.processQueue(),e._parentFile.onTaskFailed(e,n);return}d.warn(`[DownloadQueue] ${t} failed all retries (attempt ${e._reenqueueCount}/${r}), scheduling re-enqueue in ${i/1e3}s`);let a=setTimeout(()=>{this._reenqueueTimers.delete(a),e.state=`pending`,e._parentFile.state=`downloading`,this.queue.push(e),d.info(`[DownloadQueue] ${t} re-enqueued for retry`),this.processQueue()},i);this._reenqueueTimers.add(a),this.processQueue();return}this.processQueue(),e._parentFile.onTaskFailed(e,n)})}removeCompleted(e){let t=this.active.get(e);t&&(t.state===`complete`||t.state===`failed`)&&(this.queue=this.queue.filter(e=>e===x||e._parentFile!==t),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){let e={};for(let[t,n]of this.active.entries())n.state===`complete`||n.state===`failed`||(e[t]={downloaded:n.downloadedBytes,total:n.totalBytes,percent:n.totalBytes>0?(n.downloadedBytes/n.totalBytes*100).toFixed(1):0,state:n.state});return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0;for(let e of this._reenqueueTimers)clearTimeout(e);this._reenqueueTimers.clear()}},O=class{constructor(e={}){this.queue=new D(e)}enqueue(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,n){return this.queue.urgentChunk(e,t,n)}createTaskBuilder(){return new E(this.queue)}enqueueOrderedTasks(e){this.queue.enqueueOrderedTasks(e)}removeCompleted(e){this.queue.removeCompleted(e)}get running(){return this.queue.running}get queued(){return this.queue.queue.length}clear(){this.queue.clear()}},k=n(`CacheAnalyzer`);function A(e){if(e===0)return`0 B`;if(!Number.isFinite(e))return`∞`;let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**n).toFixed(+(n>0))} ${t[n]}`}var j=class{constructor(e,{threshold:t=80}={}){this.cache=e,this.threshold=t}async analyze(e){let t=await this.cache.list(),n=await this._getStorageEstimate(),r=new Set(e.map(e=>String(e.id))),i=[],a=[];for(let e of t)if(r.has(String(e.id)))i.push(e);else if(e.type===`widget`){let t=String(e.id).split(`/`)[0];r.has(t)?i.push(e):a.push(e)}else e.type===`static`?i.push(e):a.push(e);a.sort((e,t)=>(e.cachedAt||0)-(t.cachedAt||0));let o=a.reduce((e,t)=>e+(t.size||0),0),s={timestamp:Date.now(),storage:{usage:n.usage,quota:n.quota,percent:n.quota>0?Math.round(n.usage/n.quota*100):0},files:{required:i.length,orphaned:a.length,total:t.length},orphaned:a.map(e=>({id:e.id,type:e.type,size:e.size||0,cachedAt:e.cachedAt||0})),orphanedSize:o,evicted:[],threshold:this.threshold};if(k.info(`Storage: ${A(n.usage)} / ${A(n.quota)} (${s.storage.percent}%)`),k.info(`Cache: ${i.length} required, ${a.length} orphaned (${A(o)} reclaimable)`),a.length>0)for(let e of a){let t=Date.now()-(e.cachedAt||0),n=Math.floor(t/864e5),r=Math.floor(t%864e5/36e5),i=n>0?`${n}d ago`:`${r}h ago`;k.info(` Orphaned: ${e.type}/${e.id} (${A(e.size||0)}, cached ${i})`)}if(s.storage.percent>this.threshold&&a.length>0){k.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);let e=n.usage-n.quota*this.threshold/100;s.evicted=await this._evict(a,e)}else k.info(`No eviction needed (threshold: ${this.threshold}%)`);return s}async _getStorageEstimate(){try{if(typeof navigator<`u`&&navigator.storage?.estimate){let{usage:e,quota:t}=await navigator.storage.estimate();return{usage:e||0,quota:t||1/0}}}catch(e){k.warn(`Storage estimate unavailable:`,e.message)}return{usage:0,quota:1/0}}async _evict(e,t){let n=[],r=0;for(let i of e){if(r>=t)break;n.push(i),r+=i.size||0}if(n.length===0)return[];try{let e=n.map(e=>({type:e.type,id:e.id}));await this.cache.remove(e);for(let e of n)k.info(` Evicted: ${e.type}/${e.id} (${A(e.size||0)})`);k.info(`Evicted ${n.length} files, freed ${A(r)}`)}catch(e){return k.warn(`Eviction failed:`,e.message),[]}return n.map(e=>({id:e.id,type:e.type,size:e.size||0,cachedAt:e.cachedAt||0}))}},M=n(`Cache`),N=typeof window<`u`&&window.location.pathname.replace(/\/[^/]*$/,``).replace(/\/$/,``)||`/player/pwa`;async function P(e,n,r,i){let a=`${t}/widgets/${e}/${n}/${r}`,o=`<base href="${t}/media/file/">`,s=i;i.includes(`<base `)||(s=i.includes(`<head>`)?i.replace(`<head>`,`<head>`+o):i.includes(`<HEAD>`)?i.replace(`<HEAD>`,`<HEAD>`+o):o+i);let c=`<style>img,video{object-position:center center}</style>`;s.includes(`object-position:center center`)||(s.includes(`</head>`)?s=s.replace(`</head>`,c+`</head>`):s.includes(`</HEAD>`)&&(s=s.replace(`</HEAD>`,c+`</HEAD>`))),s=s.replace(/\[\[ViewPortWidth]]/g,`device-width`),s=s.replace(/https?:\/\/[^\s"')<]+\.m3u8\b/gi,e=>`/stream-proxy?url=`+encodeURIComponent(e));let l=RegExp(`https?://[^"'\\s)]+?(${t.replace(/\//g,`\\/`)}/dependencies/[^"'\\s?)]+)(\\?[^"'\\s)]*)?`,`g`);if(s=s.replace(l,(e,t)=>t),s=s.replace(/(<(?:script|link)\b[^>]*(?:src|href)=")(?!\/|https?:\/\/)(bundle\.min\.js|fonts\.css)(")/g,`$1${t}/dependencies/$2$3`),!s.includes(`xiboICTargetId`)){let e=`<script>var xiboICTargetId = '${r}';<\/script>`;s=s.includes(o)?s.replace(o,o+e):s.includes(`<head>`)?s.replace(`<head>`,`<head>`+e):e+s}return s=s.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${N}/ic"`),M.info(`Injected base tag in widget HTML`),(await fetch(`/store${t}/widgets/${e}/${n}/${r}`,{method:`PUT`,headers:{"Content-Type":`text/html; charset=utf-8`},body:s})).body?.cancel(),M.info(`Stored widget HTML at ${a} (${s.length} bytes)`),{cacheKey:a,html:s}}var F=e({BARRIER:()=>x,CacheAnalyzer:()=>j,CacheManager:()=>a,DownloadManager:()=>O,FILE_TYPES:()=>l,FileDownload:()=>T,LayoutTaskBuilder:()=>E,StoreClient:()=>c,VERSION:()=>I,cacheManager:()=>o,cacheWidgetHtml:()=>P,getFileTypeConfig:()=>u,isUrlExpired:()=>C}),I=r.version;export{O as a,x as i,P as n,c as o,j as r,F as t};
2
- //# sourceMappingURL=src-CIERor10.js.map
1
+ import{n as e}from"./chunk-7ZXdHUL4.js";import{t,u as n}from"./src-BtVLiVYZ.js";var r={name:`@xiboplayer/cache`,version:`0.7.21`,description:`Offline caching and download management with parallel chunk downloads`,type:`module`,main:`./src/index.js`,types:`./src/index.d.ts`,exports:{".":`./src/index.js`,"./cache":`./src/cache.js`,"./store-client":`./src/store-client.js`,"./download-manager":`./src/download-manager.js`,"./cache-analyzer":`./src/cache-analyzer.js`,"./widget-html":`./src/widget-html.js`},scripts:{test:`vitest run`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`},dependencies:{"@xiboplayer/utils":`workspace:*`,"spark-md5":`^3.0.2`},devDependencies:{jsdom:`^29.0.2`,vitest:`^4.1.2`},keywords:[`xibo`,`digital-signage`,`cache`,`offline`,`download`,`indexeddb`],author:`Pau Aliagas <linuxnow@gmail.com>`,license:`AGPL-3.0-or-later`,repository:{type:`git`,url:`git+https://github.com/xibo-players/xiboplayer.git`,directory:`packages/cache`},homepage:`https://xiboplayer.org`},i=n(`Cache`),a=class{constructor(){this.dependants=new Map}addDependant(e,t){let n=String(e);this.dependants.has(n)||this.dependants.set(n,new Set),this.dependants.get(n).add(String(t))}removeLayoutDependants(e){let t=String(e),n=[];for(let[e,r]of this.dependants)r.delete(t),r.size===0&&(this.dependants.delete(e),n.push(e));return n.length>0&&i.info(`${n.length} media files orphaned after layout ${e} removed:`,n),n}isMediaReferenced(e){let t=this.dependants.get(String(e));return t?t.size>0:!1}async clearAll(){this.dependants.clear()}},o=new a,s=n(`StoreClient`),c=class{async has(e,t){try{let n=await fetch(`/store/${e}/${t}`,{method:`HEAD`});if(n.status===204)return!1;if(n.status===200)return n.headers.get(`X-Store-Complete`)!==`false`;if(n.status===404)return!1;let r=Error(`Store error: ${n.status}`);throw r.status=n.status,s.warn(`has(${e}/${t}): unexpected status ${n.status}`),r}catch(n){throw n.status||n.name===`AbortError`||n.name===`TimeoutError`||s.warn(`has(${e}/${t}): network error — ${n.message}`),n}}async get(e,t){try{let n=await fetch(`/store/${e}/${t}`);if(n.status===204||n.status===404)return n.body?.cancel(),null;if(!n.ok)throw n.body?.cancel(),Error(`Failed to get file: ${n.status}`);return await n.blob()}catch(e){return s.error(`get error:`,e.message),null}}async put(e,t,n,r=`application/octet-stream`){try{let i=await fetch(`/store/${e}/${t}`,{method:`PUT`,headers:{"Content-Type":r},body:n});return i.body?.cancel(),i.ok}catch(e){return s.error(`put error:`,e.message),!1}}async remove(e){try{let t=await(await fetch(`/store/delete`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({files:e})})).json();return{deleted:t.deleted||0,total:t.total||e.length}}catch(t){return s.error(`remove error:`,t.message),{deleted:0,total:e.length}}}async list(){try{return(await(await fetch(`/store/list`)).json()).files||[]}catch(e){return s.error(`list error:`,e.message),[]}}},l={media:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},layout:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0},dataset:{maxRetries:4,retryDelayMs:0,retryDelays:[15e3,3e4,6e4,12e4],maxReenqueues:5,reenqueueDelayMs:6e4,skipHead:!0,cacheTtl:300},static:{maxRetries:3,retryDelayMs:500,retryDelays:null,maxReenqueues:0,reenqueueDelayMs:0,skipHead:!1,cacheTtl:1/0}};function u(e){return l[e]||l.media}var d=n(`Download`),f=6,p=50*1024*1024,m=3,h=100*1024*1024,g=2,_=6e5,v=15e3;function y(e){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`}[(e.path||e.code||``).split(`.`).pop()?.split(`?`)[0]?.toLowerCase()]||`application/octet-stream`}var b={normal:0,layout:1,high:2,urgent:3},x=Symbol(`BARRIER`);function S(e){try{let t=new URL(e,`http://localhost`),n=t.searchParams.get(`X-Amz-Date`),r=t.searchParams.get(`X-Amz-Expires`);if(n&&r){let e=n.replace(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/,`$1-$2-$3T$4:$5:$6Z`),t=new Date(e).getTime()/1e3;return isNaN(t)?1/0:t+parseInt(r,10)}return 1/0}catch{return 1/0}}function C(e,t=30){let n=S(e);return n===1/0?!1:Date.now()/1e3>=n-t}var 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=b.normal,this._typeConfig=u(e.type)}getUrl(){let e=this.fileInfo.path;if(C(e))throw Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}async start(){this.state=`downloading`;let e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`),this.chunkIndex!=null&&(e[`X-Store-Chunk-Index`]=String(this.chunkIndex),this._parentFile&&(e[`X-Store-Num-Chunks`]=String(this._parentFile.totalChunks),e[`X-Store-Chunk-Size`]=String(this._parentFile.options.chunkSize||104857600))),this.fileInfo.md5&&(e[`X-Store-MD5`]=this.fileInfo.md5),this.fileInfo.updateInterval&&(e[`X-Cache-TTL`]=String(this.fileInfo.updateInterval)),this.fileInfo.cmsDownloadUrl&&(e[`X-Cms-Download-Url`]=this.fileInfo.cmsDownloadUrl);let t=this._typeConfig.maxRetries;for(let n=1;n<=t;n++){let r=new AbortController,i=setTimeout(()=>r.abort(),_);try{let t=this.getUrl(),n={signal:r.signal};Object.keys(e).length>0&&(n.headers=e);let i=await fetch(t,n);if(!i.ok&&i.status!==206)throw Error(`Fetch failed: ${i.status}`);return this.blob=await i.blob(),this.state=`complete`,this.blob}catch(e){let i=r.signal.aborted?`Timeout after ${_/1e3}s`:e.message;if(n<t){let e=this._typeConfig.retryDelays?.[n-1]??this._typeConfig.retryDelayMs*n,r=this.chunkIndex==null?``:` chunk ${this.chunkIndex}`;d.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${r} attempt ${n}/${t} failed: ${i}. Retrying in ${e/1e3}s...`),await new Promise(t=>setTimeout(t,e))}else throw this.state=`failed`,r.signal.aborted?Error(i):e}finally{clearTimeout(i)}}}},T=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((e,t)=>{this._resolve=e,this._reject=t}),this._promise.catch(()=>{})}getUrl(){let e=this.fileInfo.path;if(C(e))throw Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return e}wait(){return this._promise}async prepare(e){try{this.state=`preparing`;let{id:t,type:n,size:r}=this.fileInfo;d.info(`[FileDownload] Starting:`,`${n}/${t}`),this.totalBytes=r&&r>0?parseInt(r):0,this._contentType=y(this.fileInfo);let i=u(this.fileInfo.type).skipHead;if(this.totalBytes===0&&!i){let e=this.getUrl(),t=new AbortController,n=setTimeout(()=>t.abort(),v);try{let n=await fetch(e,{method:`HEAD`,signal:t.signal});n.ok&&(this.totalBytes=parseInt(n.headers.get(`Content-Length`)||`0`),this._contentType=n.headers.get(`Content-Type`)||this._contentType)}finally{clearTimeout(n)}}d.info(`[FileDownload] File size:`,(this.totalBytes/1024/1024).toFixed(1),`MB`);let a=this.options.chunkSize||p;if(this.totalBytes>h){let e=[];for(let t=0;t<this.totalBytes;t+=a)e.push({start:t,end:Math.min(t+a-1,this.totalBytes-1),index:e.length});this.totalChunks=e.length;let r=e.filter(e=>!this.skipChunks.has(e.index)),i=e.length-r.length;for(let t of e)this.skipChunks.has(t.index)&&(this.downloadedBytes+=t.end-t.start+1);if(r.length===0){d.info(`[FileDownload] All chunks already cached, nothing to download`),this.state=`complete`,this._resolve(new Blob([],{type:this._contentType}));return}i>0&&d.info(`[FileDownload] Resuming: ${i} chunks cached, ${r.length} to download`);let o=i>0;if(o){let e=r.sort((e,t)=>e.index-t.index);for(let t of e){let e=new w(this.fileInfo,{chunkIndex:t.index,rangeStart:t.start,rangeEnd:t.end});e._parentFile=this,e._priority=b.normal,this.tasks.push(e)}}else for(let t of r){let n=new w(this.fileInfo,{chunkIndex:t.index,rangeStart:t.start,rangeEnd:t.end});n._parentFile=this,n._priority=t.index===0||t.index===e.length-1?b.high:b.normal,this.tasks.push(n)}let s=this.tasks.filter(e=>e._priority>=b.high).length;d.info(`[FileDownload] ${n}/${t}: ${this.tasks.length} chunks`+(s>0?` (${s} priority)`:``)+(o?` (resume)`:``))}else{this.totalChunks=1;let e=new w(this.fileInfo,{});e._parentFile=this,this.tasks.push(e)}e.enqueueChunkTasks(this.tasks),this.state=`downloading`}catch(e){d.error(`[FileDownload] Prepare failed:`,`${this.fileInfo.type}/${this.fileInfo.id}`,e),this.state=`failed`,this._reject(e)}}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(e){d.warn(`[FileDownload] onChunkDownloaded callback error:`,e)}if(this.completedChunks===this.tasks.length&&this.state!==`complete`){this.state=`complete`;let{type:t,id:n}=this.fileInfo;if(e.chunkIndex==null)d.info(`[FileDownload] Complete:`,`${t}/${n}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)d.info(`[FileDownload] Complete:`,`${t}/${n}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{let e=[];for(let t=0;t<this.totalChunks;t++){let n=this._chunkBlobs.get(t);n&&e.push(n)}let r=new Blob(e,{type:this._contentType});d.info(`[FileDownload] Complete:`,`${t}/${n}`,`(${r.size} bytes, reassembled)`),this._resolve(r)}this._chunkBlobs.clear()}}onTaskFailed(e,t){if(!(this.state===`complete`||this.state===`failed`)){if(t.message?.includes(`URL expired`)){let t=e.chunkIndex==null?``:` chunk ${e.chunkIndex}`;d.warn(`[FileDownload] URL expired, dropping${t}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(t=>t!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state=`complete`,this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}d.error(`[FileDownload] Failed:`,`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state=`failed`,this._reject(t)}}},E=class{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){let t=D.stableKey(e);if(this.queue.active.has(t)){let n=this.queue.active.get(t);if(e.path&&e.path!==n.fileInfo.path){let t=S(n.fileInfo.path);S(e.path)>t&&(n.fileInfo.path=e.path)}return n}let n=new T(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(t,n),this._filesToPrepare.push(n),n}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let t=0,n=0,r=()=>{for(;t<this._maxPreparing&&n<this._filesToPrepare.length;){let i=this._filesToPrepare[n++];t++,i.prepare(this).finally(()=>{t--,n>=this._filesToPrepare.length&&t===0?e():r()})}};this._filesToPrepare.length===0?e():r()})}_sortWithBarriers(){let e=[],t=[],n=[],r=[];for(let i of this._tasks)if(i.chunkIndex==null)e.push(i);else if(i.chunkIndex===0)t.push(i);else{let e=i._parentFile?.totalChunks||0;e>1&&i.chunkIndex===e-1?n.push(i):r.push(i)}e.sort((e,t)=>(e._parentFile?.totalBytes||0)-(t._parentFile?.totalBytes||0)),r.sort((e,t)=>e.chunkIndex-t.chunkIndex);let i=[...e,...t,...n];return r.length>0&&i.push(x,...r),i}},D=class e{constructor(e={}){this.concurrency=e.concurrency||f,this.chunkSize=e.chunkSize||p,this.maxChunksPerFile=e.chunksPerFile||m,this.calculateMD5=e.calculateMD5,this.onProgress=e.onProgress,this.queue=[],this.active=new Map,this._activeTasks=[],this.running=0,this._prepareQueue=[],this._preparingCount=0,this._maxPreparing=2,this.paused=!1,this._reenqueueTimers=new Set}static stableKey(e){return`${e.type}/${e.id}`}enqueue(t){let n=e.stableKey(t);if(this.active.has(n)){let e=this.active.get(n);if(t.path&&t.path!==e.fileInfo.path){let r=S(e.fileInfo.path);S(t.path)>r&&(d.info(`[DownloadQueue] Refreshing URL for`,n),e.fileInfo.path=t.path)}return e}let r=new T(t,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(n,r),d.info(`[DownloadQueue] Enqueued:`,n),this._schedulePrepare(r),r}_schedulePrepare(e){this._prepareQueue.push(e),this._processPrepareQueue()}_processPrepareQueue(){for(;this._preparingCount<this._maxPreparing&&this._prepareQueue.length>0;){let e=this._prepareQueue.shift();this._preparingCount++,e.prepare(this).finally(()=>{this._preparingCount--,this._processPrepareQueue()})}}enqueueChunkTasks(e){for(let t of e)this.queue.push(t);this._sortQueue(),d.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let t=0,n=0;for(let r of e)r===x?(this.queue.push(x),n++):(this.queue.push(r),t++);d.info(`[DownloadQueue] Ordered queue: ${t} tasks, ${n} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,t)=>t._priority-e._priority)}prioritizeLayoutFiles(e,t=b.high){let n=new Set(e.map(String)),r=0;for(let e of this.queue){let i=e._parentFile?.fileInfo.saveAs||String(e._parentFile?.fileInfo.id);n.has(i)&&e._priority<t&&(e._priority=t,r++)}for(let e of this._activeTasks){let r=e._parentFile?.fileInfo.saveAs||String(e._parentFile?.fileInfo.id);n.has(r)&&e._priority<t&&(e._priority=t)}this._sortQueue(),d.info(`[DownloadQueue] Layout files prioritized:`,n.size,`files,`,r,`tasks boosted to`,t)}urgentChunk(e,t,n){let r=`${e}/${t}`,i=this.active.get(r);if(!i)return d.info(`[DownloadQueue] urgentChunk: file not active:`,r,`chunk`,n),!1;if(this._activeTasks.some(e=>e._parentFile===i&&e.chunkIndex===n&&e.state===`downloading`)){let e=this._activeTasks.find(e=>e._parentFile===i&&e.chunkIndex===n);return e&&e._priority<b.urgent?(e._priority=b.urgent,d.info(`[DownloadQueue] URGENT: ${r} chunk ${n} (already in-flight, limiting slots)`),!0):(d.info(`[DownloadQueue] urgentChunk: already urgent:`,r,`chunk`,n),!1)}let a=this.queue.findIndex(e=>e!==x&&e._parentFile===i&&e.chunkIndex===n);if(a===-1)return d.info(`[DownloadQueue] urgentChunk: chunk not in queue:`,r,`chunk`,n),!1;let o=this.queue.splice(a,1)[0];return o._priority=b.urgent,this.queue.unshift(o),d.info(`[DownloadQueue] URGENT: ${r} chunk ${n} (moved to front)`),this.processQueue(),!0}processQueue(){if(this.paused)return;let e=this.queue.some(e=>e!==x&&e._priority>=b.urgent)||this._activeTasks?.some(e=>e._priority>=b.urgent&&e.state===`downloading`),t=e?g:this.concurrency,n=e?b.urgent:0;for(;this.running<t&&this.queue.length>0;){let e=this.queue[0];if(e===x){if(this.running>0)break;this.queue.shift();continue}if(e._priority<n||!this._canStartTask(e)){let e=!1;for(let t=1;t<this.queue.length&&this.queue[t]!==x;t++){let r=this.queue[t];if(r._priority>=n&&this._canStartTask(r)){this.queue.splice(t,1),this._startTask(r),e=!0;break}}if(!e)break;continue}this.queue.shift(),this._startTask(e)}this.queue.length===0&&this.running===0&&d.info(`[DownloadQueue] All downloads complete`)}_canStartTask(e){return e._parentFile._runningCount<this.maxChunksPerFile}_startTask(e){this.running++,e._parentFile._runningCount++,this._activeTasks.push(e);let t=`${e.fileInfo.type}/${e.fileInfo.id}`,n=e.chunkIndex==null?``:` chunk ${e.chunkIndex}`;d.info(`[DownloadQueue] Starting: ${t}${n} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(t=>t!==e),d.info(`[DownloadQueue] Fetched: ${t}${n} (${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(t=>t!==e);let{maxReenqueues:r,reenqueueDelayMs:i}=e._typeConfig;if(r>0){if(e._reenqueueCount=(e._reenqueueCount||0)+1,e._reenqueueCount>r){d.error(`[DownloadQueue] ${t} exceeded ${r} re-enqueues, failing permanently`),this.processQueue(),e._parentFile.onTaskFailed(e,n);return}d.warn(`[DownloadQueue] ${t} failed all retries (attempt ${e._reenqueueCount}/${r}), scheduling re-enqueue in ${i/1e3}s`);let a=setTimeout(()=>{this._reenqueueTimers.delete(a),e.state=`pending`,e._parentFile.state=`downloading`,this.queue.push(e),d.info(`[DownloadQueue] ${t} re-enqueued for retry`),this.processQueue()},i);this._reenqueueTimers.add(a),this.processQueue();return}this.processQueue(),e._parentFile.onTaskFailed(e,n)})}removeCompleted(e){let t=this.active.get(e);t&&(t.state===`complete`||t.state===`failed`)&&(this.queue=this.queue.filter(e=>e===x||e._parentFile!==t),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){let e={};for(let[t,n]of this.active.entries())n.state===`complete`||n.state===`failed`||(e[t]={downloaded:n.downloadedBytes,total:n.totalBytes,percent:n.totalBytes>0?(n.downloadedBytes/n.totalBytes*100).toFixed(1):0,state:n.state});return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0;for(let e of this._reenqueueTimers)clearTimeout(e);this._reenqueueTimers.clear()}},O=class{constructor(e={}){this.queue=new D(e)}enqueue(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,n){return this.queue.urgentChunk(e,t,n)}createTaskBuilder(){return new E(this.queue)}enqueueOrderedTasks(e){this.queue.enqueueOrderedTasks(e)}removeCompleted(e){this.queue.removeCompleted(e)}get running(){return this.queue.running}get queued(){return this.queue.queue.length}clear(){this.queue.clear()}},k=n(`CacheAnalyzer`);function A(e){if(e===0)return`0 B`;if(!Number.isFinite(e))return`∞`;let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**n).toFixed(+(n>0))} ${t[n]}`}var j=class{constructor(e,{threshold:t=80}={}){this.cache=e,this.threshold=t}async analyze(e){let t=await this.cache.list(),n=await this._getStorageEstimate(),r=new Set(e.map(e=>String(e.id))),i=[],a=[];for(let e of t)if(r.has(String(e.id)))i.push(e);else if(e.type===`widget`){let t=String(e.id).split(`/`)[0];r.has(t)?i.push(e):a.push(e)}else e.type===`static`?i.push(e):a.push(e);a.sort((e,t)=>(e.cachedAt||0)-(t.cachedAt||0));let o=a.reduce((e,t)=>e+(t.size||0),0),s={timestamp:Date.now(),storage:{usage:n.usage,quota:n.quota,percent:n.quota>0?Math.round(n.usage/n.quota*100):0},files:{required:i.length,orphaned:a.length,total:t.length},orphaned:a.map(e=>({id:e.id,type:e.type,size:e.size||0,cachedAt:e.cachedAt||0})),orphanedSize:o,evicted:[],threshold:this.threshold};if(k.info(`Storage: ${A(n.usage)} / ${A(n.quota)} (${s.storage.percent}%)`),k.info(`Cache: ${i.length} required, ${a.length} orphaned (${A(o)} reclaimable)`),a.length>0)for(let e of a){let t=Date.now()-(e.cachedAt||0),n=Math.floor(t/864e5),r=Math.floor(t%864e5/36e5),i=n>0?`${n}d ago`:`${r}h ago`;k.info(` Orphaned: ${e.type}/${e.id} (${A(e.size||0)}, cached ${i})`)}if(s.storage.percent>this.threshold&&a.length>0){k.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);let e=n.usage-n.quota*this.threshold/100;s.evicted=await this._evict(a,e)}else k.info(`No eviction needed (threshold: ${this.threshold}%)`);return s}async _getStorageEstimate(){try{if(typeof navigator<`u`&&navigator.storage?.estimate){let{usage:e,quota:t}=await navigator.storage.estimate();return{usage:e||0,quota:t||1/0}}}catch(e){k.warn(`Storage estimate unavailable:`,e.message)}return{usage:0,quota:1/0}}async _evict(e,t){let n=[],r=0;for(let i of e){if(r>=t)break;n.push(i),r+=i.size||0}if(n.length===0)return[];try{let e=n.map(e=>({type:e.type,id:e.id}));await this.cache.remove(e);for(let e of n)k.info(` Evicted: ${e.type}/${e.id} (${A(e.size||0)})`);k.info(`Evicted ${n.length} files, freed ${A(r)}`)}catch(e){return k.warn(`Eviction failed:`,e.message),[]}return n.map(e=>({id:e.id,type:e.type,size:e.size||0,cachedAt:e.cachedAt||0}))}},M=n(`Cache`),N=typeof window<`u`&&window.location.pathname.replace(/\/[^/]*$/,``).replace(/\/$/,``)||`/player/pwa`;async function P(e,n,r,i){let a=`${t}/widgets/${e}/${n}/${r}`,o=`<base href="${t}/media/file/">`,s=i;i.includes(`<base `)||(s=i.includes(`<head>`)?i.replace(`<head>`,`<head>`+o):i.includes(`<HEAD>`)?i.replace(`<HEAD>`,`<HEAD>`+o):o+i);let c=`<style>img,video{object-position:center center}</style>`;s.includes(`object-position:center center`)||(s.includes(`</head>`)?s=s.replace(`</head>`,c+`</head>`):s.includes(`</HEAD>`)&&(s=s.replace(`</HEAD>`,c+`</HEAD>`))),s=s.replace(/\[\[ViewPortWidth]]/g,`device-width`),s=s.replace(/https?:\/\/[^\s"')<]+\.m3u8\b/gi,e=>`/stream-proxy?url=`+encodeURIComponent(e));let l=RegExp(`https?://[^"'\\s)]+?(${t.replace(/\//g,`\\/`)}/dependencies/[^"'\\s?)]+)(\\?[^"'\\s)]*)?`,`g`);if(s=s.replace(l,(e,t)=>t),s=s.replace(/(<(?:script|link)\b[^>]*(?:src|href)=")(?!\/|https?:\/\/)(bundle\.min\.js|fonts\.css)(")/g,`$1${t}/dependencies/$2$3`),!s.includes(`xiboICTargetId`)){let e=`<script>var xiboICTargetId = '${r}';<\/script>`;s=s.includes(o)?s.replace(o,o+e):s.includes(`<head>`)?s.replace(`<head>`,`<head>`+e):e+s}return s=s.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${N}/ic"`),M.info(`Injected base tag in widget HTML`),(await fetch(`/store${t}/widgets/${e}/${n}/${r}`,{method:`PUT`,headers:{"Content-Type":`text/html; charset=utf-8`},body:s})).body?.cancel(),M.info(`Stored widget HTML at ${a} (${s.length} bytes)`),{cacheKey:a,html:s}}var F=e({BARRIER:()=>x,CacheAnalyzer:()=>j,CacheManager:()=>a,DownloadManager:()=>O,FILE_TYPES:()=>l,FileDownload:()=>T,LayoutTaskBuilder:()=>E,StoreClient:()=>c,VERSION:()=>I,cacheManager:()=>o,cacheWidgetHtml:()=>P,getFileTypeConfig:()=>u,isUrlExpired:()=>C}),I=r.version;export{O as a,x as i,P as n,c as o,j as r,F as t};
2
+ //# sourceMappingURL=src-B_BNICay.js.map