@xiboplayer/pwa 0.5.13 → 0.5.14
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/dist/assets/{index-rMG3kuqV.js → index-Bcgq4p6v.js} +2 -2
- package/dist/assets/{index-rMG3kuqV.js.map → index-Bcgq4p6v.js.map} +1 -1
- package/dist/assets/index-BczIv3fg.js +2 -0
- package/dist/assets/{index-BzTeZiFu.js.map → index-BczIv3fg.js.map} +1 -1
- package/dist/assets/{index-dSvc2qBf.js → index-BeGa2zKC.js} +2 -2
- package/dist/assets/{index-dSvc2qBf.js.map → index-BeGa2zKC.js.map} +1 -1
- package/dist/assets/{index-B9S4-Tg6.js → index-COInxuZI.js} +2 -2
- package/dist/assets/{index-B9S4-Tg6.js.map → index-COInxuZI.js.map} +1 -1
- package/dist/assets/{index-BrJYfvV-.js → index-DAhOdNyB.js} +2 -2
- package/dist/assets/{index-BrJYfvV-.js.map → index-DAhOdNyB.js.map} +1 -1
- package/dist/assets/{index-RNYmTctp.js → index-DBYNSQLp.js} +2 -2
- package/dist/assets/{index-RNYmTctp.js.map → index-DBYNSQLp.js.map} +1 -1
- package/dist/assets/{index-DBeB6nHq.js → index-DgqUapYt.js} +2 -2
- package/dist/assets/{index-DBeB6nHq.js.map → index-DgqUapYt.js.map} +1 -1
- package/dist/assets/{index-DD2ZPwTV.js → index-FlRMd3Sh.js} +2 -2
- package/dist/assets/{index-DD2ZPwTV.js.map → index-FlRMd3Sh.js.map} +1 -1
- package/dist/assets/{index-B39PWpun.js → index-ZD5qisoE.js} +2 -2
- package/dist/assets/{index-B39PWpun.js.map → index-ZD5qisoE.js.map} +1 -1
- package/dist/assets/{main-BJ4a67Bs.js → main-DstA7-TG.js} +3 -3
- package/dist/assets/main-DstA7-TG.js.map +1 -0
- package/dist/assets/{setup-Cal-4t_7.js → setup-CKgHUoum.js} +2 -2
- package/dist/assets/{setup-Cal-4t_7.js.map → setup-CKgHUoum.js.map} +1 -1
- package/dist/index.html +12 -1
- package/dist/setup.html +1 -1
- package/dist/sw-pwa.js +1 -1
- package/package.json +13 -13
- package/dist/assets/index-BzTeZiFu.js +0 -2
- package/dist/assets/main-BJ4a67Bs.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DBYNSQLp.js","./widget-html-DvXXB6at.js","./cms-api-B3gEu-pj.js","./index-DgqUapYt.js","./xmds-client-CX0t7Oes.js","./index-DAhOdNyB.js","./modulepreload-polyfill-B5Qt9EMX.js","./index-Bcgq4p6v.js","./index-ZD5qisoE.js","./index-FlRMd3Sh.js","./index-COInxuZI.js","./index-BeGa2zKC.js","./index-BczIv3fg.js","./sync-manager-DBfiw5Ey.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var Ie=Object.defineProperty;var xe=(y,e,t)=>e in y?Ie(y,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):y[e]=t;var L=(y,e,t)=>xe(y,typeof e!="symbol"?e+"":e,t);import"./modulepreload-polyfill-B5Qt9EMX.js";import{c as R,f as _e,a as Te,b as ke,r as De,i as Ae}from"./cms-api-B3gEu-pj.js";import{c as Me,C as Ee,S as Re,D as Oe}from"./widget-html-DvXXB6at.js";const Pe="modulepreload",Fe=function(y,e){return new URL(y,e).href},ae={},M=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){const s=document.getElementsByTagName("link"),r=document.querySelector("meta[property=csp-nonce]"),l=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));n=Promise.allSettled(t.map(a=>{if(a=Fe(a,i),a in ae)return;ae[a]=!0;const c=a.endsWith(".css"),d=c?'[rel="stylesheet"]':"";if(!!i)for(let p=s.length-1;p>=0;p--){const m=s[p];if(m.href===a&&(!c||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${a}"]${d}`))return;const g=document.createElement("link");if(g.rel=c?"stylesheet":Pe,c||(g.as="script"),g.crossOrigin="",g.href=a,l&&g.setAttribute("nonce",l),document.head.appendChild(g),c)return new Promise((p,m)=>{g.addEventListener("load",p),g.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${a}`)))})}))}function o(s){const r=new Event("vite:preloadError",{cancelable:!0});if(r.payload=s,window.dispatchEvent(r),!r.defaultPrevented)throw s}return n.then(s=>{for(const r of s||[])r.status==="rejected"&&o(r.reason);return e().catch(o)})};let We=()=>({emit(y,...e){for(let t=this.events[y]||[],i=0,n=t.length;i<n;i++)t[i](...e)},events:{},on(y,e){var t;return((t=this.events)[y]||(t[y]=[])).push(e),()=>{var i;this.events[y]=(i=this.events[y])==null?void 0:i.filter(n=>e!==n)}}});class $e{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 i=(...n)=>{t(...n),this.off(e,i)};this.on(e,i)}off(e,t){if(!this.events.has(e))return;const i=this.events.get(e),n=i.indexOf(t);n!==-1&&i.splice(n,1)}emit(e,...t){if(!this.events.has(e))return;const i=this.events.get(e).slice();for(const n of i)n(...t)}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}const B=R("LayoutPool");class K{constructor(e=2){this.layouts=new Map,this.maxSize=e,this.hotLayoutId=null}has(e){return this.layouts.has(e)}get(e){return this.layouts.get(e)}add(e,t){if(this.layouts.has(e)){const i=this.layouts.get(e);Object.assign(i,t),i.lastAccess=Date.now();return}this.layouts.size>=this.maxSize&&this.evictLRU(),t.status="warm",t.lastAccess=Date.now(),this.layouts.set(e,t),B.info(`Added layout ${e} to pool (size: ${this.layouts.size}/${this.maxSize})`)}setHot(e){if(this.hotLayoutId!==null&&this.layouts.has(this.hotLayoutId)&&(this.layouts.get(this.hotLayoutId).status="warm"),this.layouts.has(e)){const t=this.layouts.get(e);t.status="hot",t.lastAccess=Date.now()}this.hotLayoutId=e}evict(e){const t=this.layouts.get(e);if(t){if(B.info(`Evicting layout ${e} from pool`),t.regions)for(const[i,n]of t.regions)n.timer&&(clearTimeout(n.timer),n.timer=null);if(t.container&&K.releaseMediaElements(t.container),t.blobUrls&&t.blobUrls.size>0&&(t.blobUrls.forEach(i=>{URL.revokeObjectURL(i)}),B.info(`Revoked ${t.blobUrls.size} blob URLs for layout ${e}`)),t.mediaUrlCache)for(const[i,n]of t.mediaUrlCache)n&&typeof n=="string"&&n.startsWith("blob:")&&URL.revokeObjectURL(n);t.container&&t.container.parentNode&&t.container.remove(),this.layouts.delete(e),this.hotLayoutId===e&&(this.hotLayoutId=null)}}static releaseMediaElements(e){let t=0,i=0;e.querySelectorAll("video").forEach(n=>{n._hlsInstance&&(n._hlsInstance.destroy(),n._hlsInstance=null,i++),n._mediaStream&&(n._mediaStream.getTracks().forEach(o=>o.stop()),n._mediaStream=null,n.srcObject=null),n.pause(),n.removeAttribute("src"),n.load(),t++}),e.querySelectorAll("audio").forEach(n=>{n.pause(),n.removeAttribute("src"),n.load()}),t>0&&B.info(`Released ${t} video(s)${i?` (${i} HLS)`:""}`)}evictLRU(){let e=null,t=1/0;for(const[i,n]of this.layouts)n.status==="warm"&&n.lastAccess<t&&(e=i,t=n.lastAccess);e!==null&&this.evict(e)}clearWarm(){let e=0;const t=[];for(const[i,n]of this.layouts)n.status==="warm"&&t.push(i);for(const i of t)this.evict(i),e++;return e>0&&B.info(`Cleared ${e} warm layout(s) from pool`),e}clearWarmNotIn(e){let t=0;const i=[];for(const[n,o]of this.layouts)o.status==="warm"&&!e.has(n)&&i.push(n);for(const n of i)this.evict(n),t++;return t>0&&B.info(`Cleared ${t} warm layout(s) no longer in schedule`),t}clear(){const e=Array.from(this.layouts.keys());for(const t of e)this.evict(t);this.hotLayoutId=null}get size(){return this.layouts.size}}const X={fadeIn(y,e){const t=[{opacity:0},{opacity:1}],i={duration:e,easing:"linear",fill:"forwards"};return y.animate(t,i)},fadeOut(y,e){const t=[{opacity:1},{opacity:0}],i={duration:e,easing:"linear",fill:"forwards"};return y.animate(t,i)},getFlyKeyframes(y,e,t,i){const n={N:{x:0,y:i?-t:t},NE:{x:i?e:-e,y:i?-t:t},E:{x:i?e:-e,y:0},SE:{x:i?e:-e,y:i?t:-t},S:{x:0,y:i?t:-t},SW:{x:i?-e:e,y:i?t:-t},W:{x:i?-e:e,y:0},NW:{x:i?-e:e,y:i?-t:t}},o=n[y]||n.N;return i?{from:{transform:`translate(${o.x}px, ${o.y}px)`,opacity:0},to:{transform:"translate(0, 0)",opacity:1}}:{from:{transform:"translate(0, 0)",opacity:1},to:{transform:`translate(${o.x}px, ${o.y}px)`,opacity:0}}},flyIn(y,e,t,i,n){const o=this.getFlyKeyframes(t,i,n,!0),s={duration:e,easing:"ease-out",fill:"forwards"};return y.animate([o.from,o.to],s)},flyOut(y,e,t,i,n){const o=this.getFlyKeyframes(t,i,n,!1),s={duration:e,easing:"ease-in",fill:"forwards"};return y.animate([o.from,o.to],s)},apply(y,e,t,i,n){if(!e||!e.type)return null;const o=e.type.toLowerCase(),s=e.duration||1e3,r=e.direction||"N";switch(o){case"fade":case"fadein":return t?this.fadeIn(y,s):null;case"fadeout":return t?null:this.fadeOut(y,s);case"fly":case"flyin":return t?this.flyIn(y,s,r,i,n):null;case"flyout":return t?null:this.flyOut(y,s,r,i,n);default:return null}}};class Ne{constructor(e,t,i={}){this.config=e,this.container=t,this.options=i,this.log=R("RendererLite",i.logLevel),this.emitter=We(),this.currentLayout=null,this.currentLayoutId=null,this.regions=new Map,this.layoutTimer=null,this.layoutEndEmitted=!1,this._paused=!1,this._layoutTimerStartedAt=null,this._layoutTimerDurationMs=null,this.widgetTimers=new Map,this.mediaUrlCache=new Map,this.layoutBlobUrls=new Map,this.audioOverlays=new Map,this.scaleFactor=1,this.offsetX=0,this.offsetY=0,this.overlayContainer=null,this.activeOverlays=new Map,this._keydownHandler=null,this._keyboardActions=[],this._subPlaylistCycleIndex=new Map,this.layoutPool=new K(2),this.preloadTimer=null,this._preloadRetryTimer=null,this.setupContainer(),this.log.info("Initialized")}setupContainer(){if(this.container.style.position="relative",this.container.style.width="100%",this.container.style.height="100vh",this.container.style.overflow="hidden",typeof ResizeObserver<"u"){let e=null;this.resizeObserver=new ResizeObserver(()=>{e&&clearTimeout(e),e=setTimeout(()=>this.rescaleRegions(),150)}),this.resizeObserver.observe(this.container)}this.overlayContainer=document.createElement("div"),this.overlayContainer.id="overlay-container",this.overlayContainer.style.position="absolute",this.overlayContainer.style.top="0",this.overlayContainer.style.left="0",this.overlayContainer.style.width="100%",this.overlayContainer.style.height="100%",this.overlayContainer.style.zIndex="1000",this.overlayContainer.style.pointerEvents="none",this.container.appendChild(this.overlayContainer)}calculateScale(e){const t=this.container.clientWidth,i=this.container.clientHeight;if(!t||!i)return;const n=t/e.width,o=i/e.height;this.scaleFactor=Math.min(n,o),this.offsetX=(t-e.width*this.scaleFactor)/2,this.offsetY=(i-e.height*this.scaleFactor)/2,this.log.info(`Scale: ${this.scaleFactor.toFixed(3)} (${e.width}x${e.height} → ${t}x${i}, offset ${Math.round(this.offsetX)},${Math.round(this.offsetY)})`)}applyRegionScale(e,t){const i=this.scaleFactor;e.style.left=`${t.left*i+this.offsetX}px`,e.style.top=`${t.top*i+this.offsetY}px`,e.style.width=`${t.width*i}px`,e.style.height=`${t.height*i}px`}rescaleRegions(){if(this.currentLayout){this.calculateScale(this.currentLayout);for(const[e,t]of this.regions)this.applyRegionScale(t.element,t.config),t.width=t.config.width*this.scaleFactor,t.height=t.config.height*this.scaleFactor;for(const[e,t]of this.activeOverlays){this.calculateScale(t.layout);for(const[i,n]of t.regions)this.applyRegionScale(n.element,n.config),n.width=n.config.width*this.scaleFactor,n.height=n.config.height*this.scaleFactor}}}on(e,t){return this.emitter.on(e,t)}emit(e,...t){this.emitter.emit(e,...t)}parseActions(e){const t=[];for(const i of e.children)i.tagName==="action"&&t.push({id:i.getAttribute("id")||"",actionType:i.getAttribute("actionType")||"",triggerType:i.getAttribute("triggerType")||"",triggerCode:i.getAttribute("triggerCode")||"",source:i.getAttribute("source")||"",sourceId:i.getAttribute("sourceId")||"",target:i.getAttribute("target")||"",targetId:i.getAttribute("targetId")||"",widgetId:i.getAttribute("widgetId")||"",layoutCode:i.getAttribute("layoutCode")||"",commandCode:i.getAttribute("commandCode")||""});return t}parseXlf(e){const n=new DOMParser().parseFromString(e,"text/xml").querySelector("layout");if(!n)throw new Error("Invalid XLF: no <layout> element");const o=n.getAttribute("duration"),s={schemaVersion:parseInt(n.getAttribute("schemaVersion")||"1"),width:parseInt(n.getAttribute("width")||"1920"),height:parseInt(n.getAttribute("height")||"1080"),duration:o?parseInt(o):0,bgcolor:n.getAttribute("backgroundColor")||n.getAttribute("bgcolor")||"#000000",background:n.getAttribute("background")||null,enableStat:n.getAttribute("enableStat")!=="0",actions:this.parseActions(n),regions:[]};s.schemaVersion>1&&this.log.debug(`XLF schema version: ${s.schemaVersion}`),o?this.log.info(`Layout duration from XLF: ${s.duration}s`):this.log.info("Layout duration NOT in XLF, will calculate from widgets");const r=n.querySelectorAll(":scope > region, :scope > drawer");for(const l of r){const a=l.tagName==="drawer",c={id:l.getAttribute("id"),width:parseInt(l.getAttribute("width")||"0"),height:parseInt(l.getAttribute("height")||"0"),top:parseInt(l.getAttribute("top")||"0"),left:parseInt(l.getAttribute("left")||"0"),zindex:parseInt(l.getAttribute("zindex")||(a?"2000":"0")),enableStat:l.getAttribute("enableStat")!=="0",actions:this.parseActions(l),exitTransition:null,transitionType:null,transitionDuration:null,transitionDirection:null,loop:!0,isDrawer:a,widgets:[]},d=Array.from(l.children).find(h=>h.tagName==="options");if(d){const h=d.querySelector("exitTransType");if(h&&h.textContent){const m=d.querySelector("exitTransDuration"),w=d.querySelector("exitTransDirection");c.exitTransition={type:h.textContent,duration:parseInt(m&&m.textContent||"1000"),direction:w&&w.textContent||"N"}}const g=d.querySelector("loop");g&&(c.loop=g.textContent!=="0");const p=d.querySelector("transitionType");if(p&&p.textContent){c.transitionType=p.textContent;const m=d.querySelector("transitionDuration"),w=d.querySelector("transitionDirection");c.transitionDuration=parseInt(m&&m.textContent||"1000"),c.transitionDirection=w&&w.textContent||"N"}}for(const h of l.children){if(h.tagName!=="media")continue;const g=this.parseWidget(h);c.widgets.push(g)}s.regions.push(c),a&&this.log.info(`Parsed drawer: id=${c.id} with ${c.widgets.length} widgets`)}if(s.duration===0){let l=0;for(const a of s.regions){if(a.isDrawer)continue;let c=0;for(const d of a.widgets)if(d.duration>0)c+=d.duration;else{c=60;break}l=Math.max(l,c)}s.duration=l>0?l:60,this.log.info(`Calculated layout duration: ${s.duration}s (not specified in XLF)`)}return s}parseWidget(e){const t=e.getAttribute("type"),i=parseInt(e.getAttribute("duration")||"10"),n=parseInt(e.getAttribute("useDuration")||"1"),o=e.getAttribute("id"),s=e.getAttribute("fileId"),r={},l=e.querySelector("options");if(l)for(const $ of l.children)r[$.tagName]=$.textContent;const a=e.querySelector("raw"),c=a?a.textContent:"",d={in:null,out:null};r.transIn&&(d.in={type:r.transIn,duration:parseInt(r.transInDuration||"1000"),direction:r.transInDirection||"N"}),r.transOut&&(d.out={type:r.transOut,duration:parseInt(r.transOutDuration||"1000"),direction:r.transOutDirection||"N"});const h=this.parseActions(e),g=[];for(const $ of e.children)if($.tagName.toLowerCase()==="audio"){const k=$.querySelector("uri");k?g.push({mediaId:k.getAttribute("mediaId")||null,uri:k.textContent||"",volume:parseInt(k.getAttribute("volume")||"100"),loop:k.getAttribute("loop")==="1"}):g.push({mediaId:$.getAttribute("mediaId")||null,uri:$.getAttribute("uri")||"",volume:parseInt($.getAttribute("volume")||"100"),loop:$.getAttribute("loop")==="1"})}const p=[],m=Array.from(e.children).find($=>$.tagName==="commands");if(m)for(const $ of m.children)$.tagName==="command"&&p.push({commandCode:$.getAttribute("commandCode")||"",commandString:$.getAttribute("commandString")||""});const w=e.getAttribute("parentWidgetId")||null,b=parseInt(e.getAttribute("displayOrder")||"0"),I=e.getAttribute("cyclePlayback")==="1",v=parseInt(e.getAttribute("playCount")||"0"),x=e.getAttribute("isRandom")==="1",C=e.getAttribute("fromDt")||e.getAttribute("fromdt")||null,S=e.getAttribute("toDt")||e.getAttribute("todt")||null,T=e.getAttribute("render")||null;return{type:t,duration:i,useDuration:n,id:o,fileId:s,render:T,fromDt:C,toDt:S,enableStat:e.getAttribute("enableStat")!=="0",webhookUrl:r.webhookUrl||null,options:r,raw:c,transitions:d,actions:h,audioNodes:g,commands:p,parentWidgetId:w,displayOrder:b,cyclePlayback:I,playCount:v,isRandom:x}}trackBlobUrl(e){this.currentLayoutId&&(this.layoutBlobUrls.has(this.currentLayoutId)||this.layoutBlobUrls.set(this.currentLayoutId,new Set),this.layoutBlobUrls.get(this.currentLayoutId).add(e))}revokeBlobUrlsForLayout(e){const t=this.layoutBlobUrls.get(e);t&&(t.forEach(i=>{URL.revokeObjectURL(i)}),this.layoutBlobUrls.delete(e),this.log.info(`Revoked ${t.size} blob URLs for layout ${e}`))}updateLayoutDuration(){if(!this.currentLayout)return;let e=0;for(const t of this.currentLayout.regions){if(t.isDrawer)continue;let i=0;for(const n of t.widgets)n.duration>0&&(i+=n.duration);e=Math.max(e,i)}if(e>0&&e>this.currentLayout.duration){const t=this.currentLayout.duration;if(this.currentLayout.duration=e,this.log.info(`Layout duration updated: ${t}s → ${e}s (based on video metadata)`),this.emit("layoutDurationUpdated",this.currentLayoutId,e),this.layoutTimer){clearTimeout(this.layoutTimer);const i=Date.now()-(this._layoutTimerStartedAt||Date.now()),n=Math.max(1e3,this.currentLayout.duration*1e3-i);this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${this.currentLayoutId} duration expired (${this.currentLayout.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},n),this.log.info(`Layout timer adjusted to ${(n/1e3).toFixed(1)}s remaining (elapsed ${(i/1e3).toFixed(1)}s of ${this.currentLayout.duration}s)`)}else this.log.info(`Layout duration updated to ${e}s (timer not yet started, will use new value)`);this._scheduleNextLayoutPreload(this.currentLayout)}}attachActionListeners(e){var n;const t=[];let i=0;for(const o of e.actions||[])o.triggerType==="touch"?(this.attachTouchAction(this.container,o,null,null),i++):(n=o.triggerType)!=null&&n.startsWith("keyboard:")&&t.push(o);for(const o of e.regions){const s=this.regions.get(o.id);if(s){for(const r of o.actions||[])r.triggerType==="touch"?(this.attachTouchAction(s.element,r,o.id,null),i++):r.triggerType.startsWith("keyboard:")&&t.push(r);for(const r of o.widgets){if(!r.actions||r.actions.length===0)continue;const l=s.widgetElements.get(r.id);if(l)for(const a of r.actions)a.triggerType==="touch"?(this.attachTouchAction(l,a,o.id,r.id),i++):a.triggerType.startsWith("keyboard:")&&t.push(a)}}}this.setupKeyboardListener(t),(i>0||t.length>0)&&this.log.info(`Actions attached: ${i} touch, ${t.length} keyboard`)}attachTouchAction(e,t,i,n){e.style.cursor="pointer";const o=s=>{s.stopPropagation();const r=n?`widget ${n}`:`region ${i}`;this.log.info(`Touch action fired on ${r}: ${t.actionType}`),this.emit("action-trigger",{actionType:t.actionType,triggerType:"touch",triggerCode:t.triggerCode,layoutCode:t.layoutCode,targetId:t.targetId,commandCode:t.commandCode,source:{regionId:i,widgetId:n}})};e.addEventListener("click",o),e._actionHandlers||(e._actionHandlers=[]),e._actionHandlers.push(o)}setupKeyboardListener(e){this.removeKeyboardListener(),this._keyboardActions=e,e.length!==0&&(this._keydownHandler=t=>{const i=t.key;for(const n of this._keyboardActions){const o=n.triggerType.substring(9);if(i===o){this.log.info(`Keyboard action (key: ${i}): ${n.actionType}`),this.emit("action-trigger",{actionType:n.actionType,triggerType:n.triggerType,triggerCode:n.triggerCode,layoutCode:n.layoutCode,targetId:n.targetId,commandCode:n.commandCode,source:{key:i}});break}}},document.addEventListener("keydown",this._keydownHandler))}removeKeyboardListener(){this._keydownHandler&&(document.removeEventListener("keydown",this._keydownHandler),this._keydownHandler=null),this._keyboardActions=[]}removeActionListeners(){for(const[,e]of this.regions){this._cleanElementActionHandlers(e.element);for(const[,t]of e.widgetElements)this._cleanElementActionHandlers(t)}this.removeKeyboardListener()}_cleanElementActionHandlers(e){if(e._actionHandlers){for(const t of e._actionHandlers)e.removeEventListener("click",t);delete e._actionHandlers,e.style.cursor=""}}navigateToWidget(e){for(const[t,i]of this.regions){const n=i.widgets.findIndex(o=>o.id===e);if(n!==-1){if(this.log.info(`Navigating to widget ${e} in region ${t} (index ${n})`),i.isDrawer&&i.element.style.display==="none"&&(i.element.style.display="",this.log.info(`Drawer region ${t} revealed`)),i.timer&&(clearTimeout(i.timer),i.timer=null),this.stopWidget(t,i.currentIndex),i.currentIndex=n,this.renderWidget(t,n),i.widgets.length>1){const s=i.widgets[n].duration*1e3;i.timer=setTimeout(()=>{this.stopWidget(t,n);const r=(n+1)%i.widgets.length;i.currentIndex=r,i.isDrawer&&r===0?(i.element.style.display="none",this.log.info(`Drawer region ${t} hidden (cycle complete)`)):this.startRegion(t)},s)}else if(i.isDrawer){const s=i.widgets[n].duration*1e3;i.timer=setTimeout(()=>{this.stopWidget(t,n),i.element.style.display="none",this.log.info(`Drawer region ${t} hidden (single widget done)`)},s)}return}}this.log.warn(`Target widget ${e} not found in any region`)}nextWidget(e){const t=e?this.regions.get(e):this.regions.values().next().value;if(!t||t.widgets.length<=1)return;const i=(t.currentIndex+1)%t.widgets.length,n=t.widgets[i];this.log.info(`nextWidget → index ${i} (widget ${n.id})`),this.navigateToWidget(n.id)}previousWidget(e){const t=e?this.regions.get(e):this.regions.values().next().value;if(!t||t.widgets.length<=1)return;const i=(t.currentIndex-1+t.widgets.length)%t.widgets.length,n=t.widgets[i];this.log.info(`previousWidget → index ${i} (widget ${n.id})`),this.navigateToWidget(n.id)}async renderLayout(e,t){try{if(this.log.info(`Rendering layout ${t}`),this.currentLayoutId===t){this.log.info(`Replaying layout ${t} - reusing elements (no recreation!)`);for(const[o,s]of this.regions)s.timer&&(clearTimeout(s.timer),s.timer=null),s.currentIndex=0;this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.layoutEndEmitted=!1,this.emit("layoutStart",t,this.currentLayout);for(const[o,s]of this.regions)s.isDrawer||this.startRegion(o);this.startLayoutTimerWhenReady(t,this.currentLayout),this.log.info(`Layout ${t} restarted (reused elements)`),this._scheduleNextLayoutPreload(this.currentLayout);return}if(this.layoutPool.has(t)){this.log.info(`Layout ${t} found in preload pool - instant swap!`),await this._swapToPreloadedLayout(t);return}this.log.info(`Switching to new layout ${t}`),this.stopCurrentLayout();const n=this.parseXlf(e);if(this.currentLayout=n,this.currentLayoutId=t,this.calculateScale(n),this.container.style.backgroundColor=n.bgcolor,this.container.style.backgroundImage="",n.background&&this.options.getMediaUrl)try{const o=await this.options.getMediaUrl(parseInt(n.background));o&&(this.container.style.backgroundImage=`url(${o})`,this.container.style.backgroundSize="cover",this.container.style.backgroundPosition="center",this.container.style.backgroundRepeat="no-repeat",this.log.info(`Background image set: ${n.background}`))}catch(o){this.log.warn("Failed to load background image:",o)}if(this.options.getMediaUrl){const o=[];this.mediaUrlCache.clear();for(const s of n.regions)for(const r of s.widgets)if(r.fileId){const l=parseInt(r.fileId||r.id);this.mediaUrlCache.has(l)||o.push(this.options.getMediaUrl(l).then(a=>{this.mediaUrlCache.set(l,a)}).catch(a=>{this.log.warn(`Failed to fetch media ${l}:`,a)}))}o.length>0&&(this.log.info(`Pre-fetching ${o.length} media URLs in parallel...`),await Promise.all(o),this.log.info("All media URLs pre-fetched"))}for(const o of n.regions)await this.createRegion(o);this.log.info("Pre-creating widget elements for instant transitions...");for(const[o,s]of this.regions)for(let r=0;r<s.widgets.length;r++){const l=s.widgets[r];l.layoutId=this.currentLayoutId,l.regionId=o;try{const a=await this.createWidgetElement(l,s);a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="100%",a.style.height="100%",a.style.visibility="hidden",a.style.opacity="0",s.element.appendChild(a),s.widgetElements.set(l.id,a)}catch(a){this.log.error(`Failed to pre-create widget ${l.id}:`,a)}}this.log.info("All widget elements pre-created"),this.attachActionListeners(n),this.emit("layoutStart",t,n);for(const[o,s]of this.regions)s.isDrawer||this.startRegion(o);this.startLayoutTimerWhenReady(t,n),this._scheduleNextLayoutPreload(n),this.log.info(`Layout ${t} started`)}catch(i){throw this.log.error("Error rendering layout:",i),this.emit("error",{type:"layoutError",error:i,layoutId:t}),i}}async createRegion(e){const t=document.createElement("div");t.id=`region_${e.id}`,t.className="renderer-lite-region",t.style.position="absolute",t.style.zIndex=e.zindex,t.style.overflow="hidden",e.isDrawer&&(t.style.display="none"),this.applyRegionScale(t,e),this.container.appendChild(t);let i=e.widgets.filter(o=>this._isWidgetActive(o));i.some(o=>o.cyclePlayback)&&(i=this._applyCyclePlayback(i));const n=this.scaleFactor;this.regions.set(e.id,{element:t,config:e,widgets:i,currentIndex:0,timer:null,width:e.width*n,height:e.height*n,complete:!1,isDrawer:e.isDrawer||!1,widgetElements:new Map})}startRegion(e){const t=this.regions.get(e);this._startRegionCycle(t,e,(i,n)=>this.renderWidget(i,n),(i,n)=>this.stopWidget(i,n),()=>{this.log.info(`Region ${e} completed one full cycle`),this.checkLayoutComplete()})}async createWidgetElement(e,t){if(e.render==="html"&&e.type!=="pdf")return await this.renderGenericWidget(e,t);switch(e.type){case"image":return await this.renderImage(e,t);case"video":return await this.renderVideo(e,t);case"audio":return await this.renderAudio(e,t);case"text":case"ticker":return await this.renderTextWidget(e,t);case"pdf":return await this.renderPdf(e,t);case"webpage":return await this.renderWebpage(e,t);case"localvideo":return await this.renderVideo(e,t);case"videoin":return await this.renderVideoIn(e,t);case"powerpoint":case"flash":return this.log.warn(`Widget type '${e.type}' is not supported on web players (widget ${e.id})`),this._renderUnsupportedPlaceholder(e,t);default:return await this.renderGenericWidget(e,t)}}findMediaElement(e,t){return e.tagName===t?e:e.querySelector(t.toLowerCase())}updateMediaElement(e,t){const i=this.findMediaElement(e,"VIDEO")||this.findMediaElement(e,"AUDIO");if(i){if(i.tagName==="VIDEO"&&i._mediaConstraints&&!i._mediaStream){navigator.mediaDevices.getUserMedia(i._mediaConstraints).then(n=>{i.srcObject=n,i._mediaStream=n,this.log.info(`Webcam stream re-acquired for widget ${t.id}`)}).catch(n=>{this.log.warn("Failed to re-acquire webcam stream:",n.message)});return}this._restartMediaElement(i),this.log.info(`${i.tagName==="VIDEO"?"Video":"Audio"} restarted: ${t.fileId||t.id}`)}}_restartMediaElement(e){e.currentTime=0;const t=()=>{e.removeEventListener("seeked",t),e.play().catch(()=>{})};e.addEventListener("seeked",t),e.currentTime===0&&e.readyState>=2&&(e.removeEventListener("seeked",t),e.play().catch(()=>{}))}waitForWidgetReady(e,t){const n=this.findMediaElement(e,"VIDEO");if(n)return!n.paused&&n.readyState>=3?Promise.resolve():new Promise(r=>{const l=setTimeout(()=>{this.log.warn(`Video ready timeout (10000ms) for widget ${t.id}`),r()},1e4),a=()=>{n.removeEventListener("playing",a),clearTimeout(l),this.log.info(`Video widget ${t.id} ready (playing)`),r()};n.addEventListener("playing",a)});const o=this.findMediaElement(e,"AUDIO");if(o)return!o.paused&&o.readyState>=3?Promise.resolve():new Promise(r=>{const l=setTimeout(()=>{this.log.warn(`Audio ready timeout (10000ms) for widget ${t.id}`),r()},1e4),a=()=>{o.removeEventListener("playing",a),clearTimeout(l),this.log.info(`Audio widget ${t.id} ready (playing)`),r()};o.addEventListener("playing",a)});const s=this.findMediaElement(e,"IMG");return s?s.complete&&s.naturalWidth>0?Promise.resolve():new Promise(r=>{const l=setTimeout(()=>{this.log.warn(`Image ready timeout for widget ${t.id}`),r()},1e4),a=()=>{s.removeEventListener("load",a),clearTimeout(l),r()};s.addEventListener("load",a)}):Promise.resolve()}async startLayoutTimerWhenReady(e,t){if(!t||t.duration<=0)return;const i=[];for(const[o,s]of this.regions){if(s.widgets.length===0)continue;const r=s.widgets[s.currentIndex||0],l=s.widgetElements.get(r.id);l&&i.push(this.waitForWidgetReady(l,r))}if(i.length>0&&(this.log.info(`Waiting for ${i.length} widget(s) to be ready before starting layout timer...`),await Promise.all(i),this.log.info("All widgets ready — starting layout timer")),this.currentLayoutId!==e){this.log.warn(`Layout changed while waiting for widgets — skipping timer for ${e}`);return}const n=t.duration*1e3;this.log.info(`Layout ${e} will end after ${t.duration}s`),this._layoutTimerStartedAt=Date.now(),this._layoutTimerDurationMs=n,this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${e} duration expired (${t.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},n)}async _showWidget(e,t){var o,s;const i=e.widgets[t];if(!i)return null;let n=e.widgetElements.get(i.id);n||(this.log.warn(`Widget ${i.id} not pre-created, creating now`),n=await this.createWidgetElement(i,e),n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",e.widgetElements.set(i.id,n),e.element.appendChild(n));for(const[r,l]of e.widgetElements)r!==i.id&&((o=l.getAnimations)==null||o.call(l).forEach(a=>a.cancel()),l.style.visibility="hidden",l.style.opacity="0");return this.updateMediaElement(n,i),(s=n.getAnimations)==null||s.call(n).forEach(r=>r.cancel()),n.style.visibility="visible",i.transitions.in?X.apply(n,i.transitions.in,!0,e.width,e.height):n.style.opacity="1",this._startAudioOverlays(i),i}_startAudioOverlays(e){if(!e.audioNodes||e.audioNodes.length===0)return;this._stopAudioOverlays(e.id);const t=[];for(const i of e.audioNodes){if(!i.uri)continue;const n=document.createElement("audio");n.autoplay=!0,n.loop=i.loop,n.volume=Math.max(0,Math.min(1,i.volume/100));const o=parseInt(i.mediaId);let s=o?this.mediaUrlCache.get(o):null;!s&&o&&this.options.getMediaUrl?this.options.getMediaUrl(o).then(l=>{n.src=l}).catch(()=>{n.src=`${window.location.origin}/player/cache/media/${i.uri}`}):s?n.src=s:n.src=`${window.location.origin}/player/cache/media/${i.uri}`,n.style.display="none",this.container.appendChild(n);const r=n.play();r&&r.catch&&r.catch(()=>{}),t.push(n),this.log.info(`Audio overlay started for widget ${e.id}: ${i.uri} (loop=${i.loop}, vol=${i.volume})`)}t.length>0&&this.audioOverlays.set(e.id,t)}_stopAudioOverlays(e){const t=this.audioOverlays.get(e);if(t){for(const i of t)i.pause(),i.removeAttribute("src"),i.load(),i.parentNode&&i.parentNode.removeChild(i);this.audioOverlays.delete(e),this.log.info(`Audio overlays stopped for widget ${e}`)}}_hideWidget(e,t){const i=e.widgets[t];if(!i)return{widget:null,animPromise:null};const n=e.widgetElements.get(i.id);if(!n)return{widget:null,animPromise:null};let o=null;if(i.transitions.out){const l=X.apply(n,i.transitions.out,!1,e.width,e.height);l&&(o=new Promise(a=>{l.onfinish=a}))}const s=n.querySelector("video");s&&i.options.loop!=="1"&&s.pause(),s!=null&&s._mediaStream&&(s._mediaStream.getTracks().forEach(l=>l.stop()),s._mediaStream=null,s.srcObject=null);const r=n.querySelector("audio");return r&&i.options.loop!=="1"&&r.pause(),this._stopAudioOverlays(i.id),{widget:i,animPromise:o}}_isWidgetActive(e){const t=new Date;if(e.fromDt){const i=new Date(e.fromDt);if(t<i)return!1}if(e.toDt){const i=new Date(e.toDt);if(t>i)return!1}return!0}_parseDurationComments(e,t){const i=e.match(/<!--\s*DURATION=(\d+)\s*-->/);if(i){const o=parseInt(i[1],10);if(o>0){this.log.info(`Widget ${t.id}: DURATION comment overrides duration ${t.duration}→${o}s`),t.duration=o;return}}const n=e.match(/<!--\s*NUMITEMS=(\d+)\s*-->/);if(n){const o=parseInt(n[1],10);if(o>0&&t.duration>0){const s=o*t.duration;this.log.info(`Widget ${t.id}: NUMITEMS=${o} × ${t.duration}s = ${s}s`),t.duration=s}}}_applyCyclePlayback(e){this._subPlaylistCycleIndex||(this._subPlaylistCycleIndex=new Map);const t=new Map,i=[];for(const n of e)n.parentWidgetId&&n.cyclePlayback?(t.has(n.parentWidgetId)||t.set(n.parentWidgetId,[]),t.get(n.parentWidgetId).push(n)):i.push({type:"direct",widget:n});for(const[n,o]of t){o.sort((r,l)=>r.displayOrder-l.displayOrder);let s;if(o.some(r=>r.isRandom)){const r=Math.floor(Math.random()*o.length);s=o[r]}else{const r=this._subPlaylistCycleIndex.get(n)||0;s=o[r%o.length],this._subPlaylistCycleIndex.set(n,r+1)}this.log.info(`Sub-playlist cycle: group ${n} selected widget ${s.id} (${o.length} in group)`),i.push({type:"direct",widget:s})}return i.map(n=>n.widget)}_startRegionCycle(e,t,i,n,o){if(!e||e.widgets.length===0)return;if(e.widgets.length===1){i(t,0);return}const s=()=>{const r=e.currentIndex,l=e.widgets[r];i(t,r);const a=l.duration*1e3;e.timer=setTimeout(()=>{this._handleWidgetCycleEnd(l,e,t,r,i,n,o,s)},a)};s()}_handleWidgetCycleEnd(e,t,i,n,o,s,r,l){var c;e.webhookUrl&&this.emit("widgetAction",{type:"durationEnd",widgetId:e.id,layoutId:this.currentLayoutId,regionId:i,url:e.webhookUrl}),s(i,n);const a=(t.currentIndex+1)%t.widgets.length;if(a===0&&!t.complete&&(t.complete=!0,r==null||r()),a===0&&((c=t.config)==null?void 0:c.loop)===!1){o(i,t.widgets.length-1);return}t.currentIndex=a,l()}async renderWidget(e,t){var n;const i=this.regions.get(e);if(i)try{const o=await this._showWidget(i,t);if(o&&(this.log.info(`Showing widget ${o.type} (${o.id}) in region ${e}`),this.emit("widgetStart",{widgetId:o.id,regionId:e,layoutId:this.currentLayoutId,mediaId:parseInt(o.fileId||o.id)||null,type:o.type,duration:o.duration,enableStat:o.enableStat}),o.commands&&o.commands.length>0))for(const s of o.commands)this.emit("widgetCommand",{commandCode:s.commandCode,commandString:s.commandString,widgetId:o.id,regionId:e,layoutId:this.currentLayoutId})}catch(o){this.log.error("Error rendering widget:",o),this.emit("error",{type:"widgetError",error:o,widgetId:(n=i.widgets[t])==null?void 0:n.id,regionId:e})}}async stopWidget(e,t){const i=this.regions.get(e);if(!i)return;const{widget:n,animPromise:o}=this._hideWidget(i,t);o&&await o,n&&this.emit("widgetEnd",{widgetId:n.id,regionId:e,layoutId:this.currentLayoutId,mediaId:parseInt(n.fileId||n.id)||null,type:n.type,enableStat:n.enableStat})}async renderImage(e,t){const i=document.createElement("img");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%";const n=e.options.scaleType,o={stretch:"fill",center:"contain",fit:"cover"};i.style.objectFit=o[n]||"contain";const s={left:"left",center:"center",right:"right"},r={top:"top",middle:"center",bottom:"bottom"},l=s[e.options.alignId]||"center",a=r[e.options.valignId]||"center";i.style.objectPosition=`${l} ${a}`,i.style.opacity="0";const c=parseInt(e.fileId||e.id);let d=this.mediaUrlCache.get(c);return!d&&this.options.getMediaUrl?d=await this.options.getMediaUrl(c):d||(d=`${window.location.origin}/player/cache/media/${e.options.uri}`),i.src=d,i}async renderVideo(e,t){const i=document.createElement("video");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%";const n=e.options.scaleType,o={stretch:"fill",center:"none",fit:"contain"};i.style.objectFit=o[n]||"contain",i.style.opacity="1",i.autoplay=!0,i.preload="auto",i.muted=e.options.mute==="1",i.loop=!1,i.controls=!1,i.playsInline=!0,i.addEventListener("ended",()=>{e.options.loop==="1"?(i.currentTime=0,this.log.info(`Video ${s} ended - reset to start, waiting for widget cycle to replay`)):this.log.info(`Video ${s} ended - paused on last frame`)});const s=parseInt(e.fileId||e.id);let r=this.mediaUrlCache.get(s);if(!r&&this.options.getMediaUrl?r=await this.options.getMediaUrl(s):r||(r=`${window.location.origin}/player/cache/media/${s}`),r.includes(".m3u8"))if(i.canPlayType("application/vnd.apple.mpegurl"))this.log.info(`HLS stream (native): ${s}`),i.src=r;else try{const{default:c}=await M(async()=>{const{default:d}=await import("hls.js");return{default:d}},[],import.meta.url);if(c.isSupported()){const d=new c({enableWorker:!0,lowLatencyMode:!0});d.loadSource(r),d.attachMedia(i),i._hlsInstance=d,d.on(c.Events.ERROR,(h,g)=>{g.fatal&&(this.log.error(`HLS fatal error: ${g.type}`,g.details),d.destroy(),i._hlsInstance=null)}),this.log.info(`HLS stream (hls.js): ${s}`)}else this.log.warn(`HLS not supported on this browser for ${s}`),i.src=r}catch(c){this.log.warn(`hls.js not available, falling back to native: ${c.message}`),i.src=r}else i.src=r;const a=this.currentLayoutId;return i.addEventListener("loadedmetadata",()=>{const c=Math.floor(i.duration);this.log.info(`Video ${s} duration detected: ${c}s`),(e.duration===0||e.useDuration===0)&&(e.duration=c,this.log.info(`Updated widget ${e.id} duration to ${c}s (useDuration=0)`),this.currentLayoutId===a?this.updateLayoutDuration():this.log.info(`Video ${s} duration set but layout timer not updated (preloaded for layout ${a}, current is ${this.currentLayoutId})`))}),i.addEventListener("loadeddata",()=>{this.log.info("Video loaded and ready:",s)}),i.addEventListener("error",c=>{const d=i.error,h=d==null?void 0:d.code,g=(d==null?void 0:d.message)||"Unknown error";this.log.warn(`Video error (non-fatal, logged only): ${s}, code: ${h}, time: ${i.currentTime.toFixed(1)}s, message: ${g}`)}),i.addEventListener("playing",()=>{this.log.info("Video playing:",s)}),this.log.info("Video element created:",s,i.src),i}async renderVideoIn(e,t){const i=document.createElement("video");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.objectFit=e.options.showFullScreen==="1"?"cover":"contain",i.autoplay=!0,i.playsInline=!0,i.controls=!1,i.muted=e.options.mute!=="0",e.options.mirror==="1"&&(i.style.transform="scaleX(-1)");const n={width:{ideal:t.width},height:{ideal:t.height}},o=e.options.sourceId||e.options.deviceId;o?n.deviceId={exact:o}:n.facingMode=e.options.facingMode||"environment";const s={video:n,audio:e.options.captureAudio==="1"};i._mediaConstraints=s;try{const r=await navigator.mediaDevices.getUserMedia(s);i.srcObject=r,i._mediaStream=r,this.log.info(`Webcam stream acquired for widget ${e.id} (tracks: ${r.getTracks().length})`)}catch(r){return this.log.warn(`getUserMedia failed for widget ${e.id}: ${r.message}`),this._renderUnsupportedPlaceholder({...e,type:"Camera unavailable"},t)}return i}async renderAudio(e,t){const i=document.createElement("div");i.className="renderer-lite-widget audio-widget",i.style.width="100%",i.style.height="100%",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.background="linear-gradient(135deg, #667eea 0%, #764ba2 100%)",i.style.opacity="0";const n=document.createElement("audio");n.autoplay=!0,n.loop=e.options.loop==="1",n.volume=parseFloat(e.options.volume||"100")/100;const o=parseInt(e.fileId||e.id);let s=this.mediaUrlCache.get(o);!s&&this.options.getMediaUrl?s=await this.options.getMediaUrl(o):s||(s=`${window.location.origin}/player/cache/media/${o}`),n.src=s,n.addEventListener("ended",()=>{e.options.loop==="1"?(n.currentTime=0,this.log.info(`Audio ${o} ended - reset to start, waiting for widget cycle to replay`)):this.log.info(`Audio ${o} ended - playback complete`)});const r=this.currentLayoutId;n.addEventListener("loadedmetadata",()=>{const d=Math.floor(n.duration);this.log.info(`Audio ${o} duration detected: ${d}s`),(e.duration===0||e.useDuration===0)&&(e.duration=d,this.log.info(`Updated widget ${e.id} duration to ${d}s (useDuration=0)`),this.currentLayoutId===r?this.updateLayoutDuration():this.log.info(`Audio ${o} duration set but layout timer not updated (preloaded for layout ${r}, current is ${this.currentLayoutId})`))}),n.addEventListener("error",()=>{const d=n.error;this.log.warn(`Audio error (non-fatal): ${o}, code: ${d==null?void 0:d.code}, message: ${(d==null?void 0:d.message)||"Unknown"}`)});const l=document.createElement("div");l.innerHTML="♪",l.style.fontSize="120px",l.style.color="white",l.style.marginBottom="20px";const a=document.createElement("div");a.style.color="white",a.style.fontSize="24px",a.textContent="Playing Audio";const c=document.createElement("div");return c.style.color="rgba(255,255,255,0.7)",c.style.fontSize="16px",c.style.marginTop="10px",c.textContent=e.options.uri,i.appendChild(n),i.appendChild(l),i.appendChild(a),i.appendChild(c),i}async renderTextWidget(e,t){const i=document.createElement("iframe");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.opacity="0";let n=e.raw;if(this.options.getWidgetHtml){const r=await this.options.getWidgetHtml(e);if(r&&typeof r=="object"&&r.url){if(i.src=r.url,r.fallback){const l=this;i.addEventListener("load",function(){var a;try{if(!((a=i.contentDocument)!=null&&a.querySelector("base"))){l.log.warn("Cache URL failed (hard reload?), using original CMS URLs");const c=new Blob([r.fallback],{type:"text/html"}),d=URL.createObjectURL(c);l.trackBlobUrl(d),i.src=d}}catch{}},{once:!0})}return r.fallback&&this._parseDurationComments(r.fallback,e),i}n=r}n&&this._parseDurationComments(n,e);const o=new Blob([n],{type:"text/html"}),s=URL.createObjectURL(o);return i.src=s,this.trackBlobUrl(s),i}async renderPdf(e,t){const i=document.createElement("div");if(i.className="renderer-lite-widget pdf-widget",i.style.width="100%",i.style.height="100%",i.style.backgroundColor="#525659",i.style.opacity="0",i.style.position="relative",typeof window.pdfjsLib>"u")try{const s=await M(()=>import("./pdf-BnPRJEQ6.js"),[],import.meta.url);window.pdfjsLib=s;const r=window.location.pathname.replace(/\/[^/]*$/,"/");window.pdfjsLib.GlobalWorkerOptions.workerSrc=`${window.location.origin}${r}pdf.worker.min.mjs`}catch(s){return this.log.error("PDF.js not available:",s),i.innerHTML='<div style="color:white;padding:20px;text-align:center;">PDF viewer unavailable</div>',i.style.opacity="1",i}const n=parseInt(e.fileId||e.id);let o=this.mediaUrlCache.get(n);!o&&this.options.getMediaUrl?o=await this.options.getMediaUrl(n):o||(o=`${window.location.origin}/player/cache/media/${e.options.uri}`);try{const l=await(await window.pdfjsLib.getDocument(o).promise).getPage(1),a=l.getViewport({scale:1}),c=Math.min(t.width/a.width,t.height/a.height),d=l.getViewport({scale:c}),h=document.createElement("canvas");h.width=d.width,h.height=d.height,h.style.display="block",h.style.margin="auto";const g=h.getContext("2d");await l.render({canvasContext:g,viewport:d}).promise,i.appendChild(h)}catch(s){this.log.error("PDF render failed:",s),i.innerHTML='<div style="color:white;padding:20px;text-align:center;">Failed to load PDF</div>'}return i.style.opacity="1",i}async renderWebpage(e,t){if(parseInt(e.options.modeId||"1")===0)return await this.renderGenericWidget(e,t);const n=document.createElement("iframe");return n.className="renderer-lite-widget",n.style.width="100%",n.style.height="100%",n.style.border="none",n.style.opacity="0",n.src=e.options.uri,n}async renderGenericWidget(e,t){const i=document.createElement("iframe");i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.opacity="0";let n=e.raw;if(this.options.getWidgetHtml){const o=await this.options.getWidgetHtml(e);if(o&&typeof o=="object"&&o.url){if(i.src=o.url,o.fallback){const s=this;i.addEventListener("load",function(){var r;try{if(!((r=i.contentDocument)!=null&&r.querySelector("base"))){s.log.warn("Cache URL failed (hard reload?), using original CMS URLs");const l=new Blob([o.fallback],{type:"text/html"}),a=URL.createObjectURL(l);s.trackBlobUrl(a),i.src=a}}catch{}},{once:!0})}return o.fallback&&this._parseDurationComments(o.fallback,e),i}n=o}if(n){this._parseDurationComments(n,e);const o=new Blob([n],{type:"text/html"}),s=URL.createObjectURL(o);i.src=s,this.trackBlobUrl(s)}else this.log.warn(`No HTML for widget ${e.id}`),i.srcdoc='<div style="padding:20px;">Widget content unavailable</div>';return i}_renderUnsupportedPlaceholder(e,t){const i=document.createElement("div");return i.className="renderer-lite-widget",i.style.width="100%",i.style.height="100%",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.backgroundColor="#111",i.style.color="#666",i.style.fontSize="14px",i.textContent=`Unsupported: ${e.type}`,i}_scheduleNextLayoutPreload(e){this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null);const t=e.duration||60,i=t*1e3*.75,n=t*1e3*.9;this.log.info(`Scheduling next layout preload in ${(i/1e3).toFixed(1)}s (75% of ${t}s)`),this.preloadTimer=setTimeout(()=>{this.preloadTimer=null,this.emit("request-next-layout-preload")},i),this._preloadRetryTimer=setTimeout(()=>{this._preloadRetryTimer=null,this.emit("request-next-layout-preload")},n)}async preloadLayout(e,t){if(this.layoutPool.has(t))return this.log.info(`Layout ${t} already in preload pool, skipping`),!0;if(this.currentLayoutId===t)return this.log.info(`Layout ${t} is current, skipping preload`),!0;try{this.log.info(`Preloading layout ${t} into pool...`);const i=this.parseXlf(e);this.calculateScale(i);const n=document.createElement("div");if(n.id=`preload_layout_${t}`,n.className="renderer-lite-preload-wrapper",n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",n.style.visibility="hidden",n.style.zIndex="-1",n.style.backgroundColor=i.bgcolor,i.background&&this.options.getMediaUrl)try{const g=await this.options.getMediaUrl(parseInt(i.background));g&&(n.style.backgroundImage=`url(${g})`,n.style.backgroundSize="cover",n.style.backgroundPosition="center",n.style.backgroundRepeat="no-repeat")}catch(g){this.log.warn("Preload: Failed to load background image:",g)}const o=new Map;if(this.options.getMediaUrl){const g=[];for(const p of i.regions)for(const m of p.widgets)if(m.fileId){const w=parseInt(m.fileId||m.id);o.has(w)||g.push(this.options.getMediaUrl(w).then(b=>{o.set(w,b)}).catch(b=>{this.log.warn(`Preload: Failed to fetch media ${w}:`,b)}))}g.length>0&&(this.log.info(`Preload: fetching ${g.length} media URLs...`),await Promise.all(g))}const s=this.mediaUrlCache,r=this.currentLayoutId;this.mediaUrlCache=o;const l=new Map,a=this.scaleFactor;for(const g of i.regions){const p=document.createElement("div");p.id=`preload_region_${t}_${g.id}`,p.className="renderer-lite-region",p.style.position="absolute",p.style.zIndex=g.zindex,p.style.overflow="hidden",this.applyRegionScale(p,g),n.appendChild(p);const m={element:p,config:g,widgets:g.widgets,currentIndex:0,timer:null,width:g.width*a,height:g.height*a,complete:!1,widgetElements:new Map};l.set(g.id,m)}const c=new Set,d=this.layoutBlobUrls;this.layoutBlobUrls=new Map,this.layoutBlobUrls.set(t,c),this.currentLayoutId=t;for(const[g,p]of l)for(let m=0;m<p.widgets.length;m++){const w=p.widgets[m];w.layoutId=t,w.regionId=g;try{const b=await this.createWidgetElement(w,p);b.style.position="absolute",b.style.top="0",b.style.left="0",b.style.width="100%",b.style.height="100%",b.style.visibility="hidden",b.style.opacity="0",p.element.appendChild(b),p.widgetElements.set(w.id,b)}catch(b){this.log.error(`Preload: Failed to create widget ${w.id}:`,b)}}return this.mediaUrlCache=s,this.currentLayoutId=r,n.querySelectorAll("video").forEach(g=>g.pause()),(this.layoutBlobUrls.get(t)||new Set).forEach(g=>c.add(g)),this.layoutBlobUrls=d,this.container.appendChild(n),this.layoutPool.add(t,{container:n,layout:i,regions:l,blobUrls:c,mediaUrlCache:o}),this.log.info(`Layout ${t} preloaded into pool (${l.size} regions, ${o.size} media)`),!0}catch(i){return this.log.error(`Preload failed for layout ${t}:`,i),!1}}async _swapToPreloadedLayout(e){const t=this.layoutPool.get(e);if(!t){this.log.error(`Cannot swap: layout ${e} not in pool`);return}this.removeActionListeners(),this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null);const i=this.currentLayoutId;if(i&&this.layoutPool.has(i))this.layoutPool.evict(i);else{for(const[n,o]of this.regions)if(o.timer&&(clearTimeout(o.timer),o.timer=null),K.releaseMediaElements(o.element),o.config&&o.config.exitTransition){const s=X.apply(o.element,o.config.exitTransition,!1,o.width,o.height);if(s){const r=o.element;s.onfinish=()=>r.remove()}else o.element.remove()}else o.element.remove();i&&this.revokeBlobUrlsForLayout(i);for(const[n,o]of this.mediaUrlCache)o&&typeof o=="string"&&o.startsWith("blob:")&&URL.revokeObjectURL(o)}i&&!this.layoutEndEmitted&&this.emit("layoutEnd",i),this.regions.clear(),this.mediaUrlCache.clear(),t.container.style.visibility="visible",t.container.style.zIndex="0",this.layoutPool.setHot(e),this.currentLayout=t.layout,this.currentLayoutId=e,this.regions=t.regions,this.mediaUrlCache=t.mediaUrlCache||new Map,this.layoutEndEmitted=!1,this.container.style.backgroundColor=t.layout.bgcolor,t.container.style.backgroundImage?(this.container.style.backgroundImage=t.container.style.backgroundImage,this.container.style.backgroundSize=t.container.style.backgroundSize,this.container.style.backgroundPosition=t.container.style.backgroundPosition,this.container.style.backgroundRepeat=t.container.style.backgroundRepeat):this.container.style.backgroundImage="",this.calculateScale(t.layout),this.attachActionListeners(t.layout),this.emit("layoutStart",e,t.layout);for(const[n,o]of this.regions)o.currentIndex=0,o.complete=!1,this.startRegion(n);this.updateLayoutDuration(),this.startLayoutTimerWhenReady(e,t.layout),this._scheduleNextLayoutPreload(t.layout),this.log.info(`Swapped to preloaded layout ${e} (instant transition)`)}checkLayoutComplete(){let e=!0;for(const[t,i]of this.regions)if(i.widgets.length>1&&!i.complete){e=!1;break}e&&this.currentLayoutId&&this.log.info("All multi-widget regions completed one cycle")}stopCurrentLayout(){if(this.currentLayout){if(this.log.info(`Stopping layout ${this.currentLayoutId}`),this.removeActionListeners(),this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null),this.currentLayoutId&&this.layoutPool.has(this.currentLayoutId))this.layoutPool.evict(this.currentLayoutId);else{this.currentLayoutId&&this.revokeBlobUrlsForLayout(this.currentLayoutId);for(const[e,t]of this.regions)if(t.timer&&(clearTimeout(t.timer),t.timer=null),t.widgets.length>0&&this.stopWidget(e,t.currentIndex),K.releaseMediaElements(t.element),t.config&&t.config.exitTransition){const i=X.apply(t.element,t.config.exitTransition,!1,t.width,t.height);if(i){const n=t.element;i.onfinish=()=>n.remove()}else t.element.remove()}else t.element.remove();for(const[e,t]of this.mediaUrlCache)t&&t.startsWith("blob:")&&URL.revokeObjectURL(t)}this.regions.clear(),this.mediaUrlCache.clear(),this.currentLayoutId&&!this.layoutEndEmitted&&this.emit("layoutEnd",this.currentLayoutId),this.layoutEndEmitted=!1,this.currentLayout=null,this.currentLayoutId=null}}async renderOverlay(e,t,i=0){try{if(this.log.info(`Rendering overlay ${t} (priority ${i})`),this.activeOverlays.has(t)){this.log.warn(`Overlay ${t} already active, skipping`);return}const n=this.parseXlf(e),o=document.createElement("div");if(o.id=`overlay_${t}`,o.className="renderer-lite-overlay",o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="100%",o.style.height="100%",o.style.zIndex=String(1e3+i),o.style.pointerEvents="auto",o.style.backgroundColor=n.bgcolor,this.options.getMediaUrl){const l=[];for(const a of n.regions)for(const c of a.widgets)if(c.fileId){const d=parseInt(c.fileId||c.id);this.mediaUrlCache.has(d)||l.push(this.options.getMediaUrl(d).then(h=>{this.mediaUrlCache.set(d,h)}).catch(h=>{this.log.warn(`Failed to fetch overlay media ${d}:`,h)}))}l.length>0&&(this.log.info(`Pre-fetching ${l.length} overlay media URLs...`),await Promise.all(l))}this.calculateScale(n);const s=new Map,r=this.scaleFactor;for(const l of n.regions){const a=document.createElement("div");a.id=`overlay_${t}_region_${l.id}`,a.className="renderer-lite-region overlay-region",a.style.position="absolute",a.style.zIndex=String(l.zindex),a.style.overflow="hidden",this.applyRegionScale(a,l),o.appendChild(a),s.set(l.id,{element:a,config:l,widgets:l.widgets,currentIndex:0,timer:null,width:l.width*r,height:l.height*r,complete:!1,widgetElements:new Map})}for(const[l,a]of s)for(const c of a.widgets){c.layoutId=t,c.regionId=l;try{const d=await this.createWidgetElement(c,a);d.style.visibility="hidden",d.style.opacity="0",a.element.appendChild(d),a.widgetElements.set(c.id,d)}catch(d){this.log.error(`Failed to pre-create overlay widget ${c.id}:`,d)}}this.overlayContainer.appendChild(o),this.activeOverlays.set(t,{container:o,layout:n,regions:s,timer:null,priority:i}),this.emit("overlayStart",t,n);for(const[l,a]of s)this.startOverlayRegion(t,l);if(n.duration>0){const l=n.duration*1e3,a=this.activeOverlays.get(t);a&&(a.timer=setTimeout(()=>{this.log.info(`Overlay ${t} duration expired (${n.duration}s)`),this.emit("overlayEnd",t)},l))}this.log.info(`Overlay ${t} started`)}catch(n){throw this.log.error("Error rendering overlay:",n),this.emit("error",{type:"overlayError",error:n,layoutId:t}),n}}startOverlayRegion(e,t){const i=this.activeOverlays.get(e);if(!i)return;const n=i.regions.get(t);this._startRegionCycle(n,t,(o,s)=>this.renderOverlayWidget(e,o,s),(o,s)=>this.stopOverlayWidget(e,o,s),()=>this.log.info(`Overlay ${e} region ${t} completed one full cycle`))}async renderOverlayWidget(e,t,i){var s;const n=this.activeOverlays.get(e);if(!n)return;const o=n.regions.get(t);if(o)try{const r=await this._showWidget(o,i);r&&(this.log.info(`Showing overlay widget ${r.type} (${r.id}) in overlay ${e} region ${t}`),this.emit("overlayWidgetStart",{overlayId:e,widgetId:r.id,regionId:t,type:r.type,duration:r.duration}))}catch(r){this.log.error("Error rendering overlay widget:",r),this.emit("error",{type:"overlayWidgetError",error:r,widgetId:(s=o.widgets[i])==null?void 0:s.id,regionId:t,overlayId:e})}}async stopOverlayWidget(e,t,i){const n=this.activeOverlays.get(e);if(!n)return;const o=n.regions.get(t);if(!o)return;const{widget:s,animPromise:r}=this._hideWidget(o,i);r&&await r,s&&this.emit("overlayWidgetEnd",{overlayId:e,widgetId:s.id,regionId:t,type:s.type})}stopOverlay(e){const t=this.activeOverlays.get(e);if(!t){this.log.warn(`Overlay ${e} not active`);return}this.log.info(`Stopping overlay ${e}`),t.timer&&(clearTimeout(t.timer),t.timer=null);for(const[i,n]of t.regions)n.timer&&(clearTimeout(n.timer),n.timer=null),n.widgets.length>0&&this.stopOverlayWidget(e,i,n.currentIndex);t.container&&t.container.remove(),this.revokeBlobUrlsForLayout(e),this.activeOverlays.delete(e),this.emit("overlayEnd",e),this.log.info(`Overlay ${e} stopped`)}stopAllOverlays(){const e=Array.from(this.activeOverlays.keys());for(const t of e)this.stopOverlay(t);this.log.info("All overlays stopped")}getActiveOverlays(){return Array.from(this.activeOverlays.keys())}pause(){if(!this._paused){this._paused=!0;for(const[,e]of this.regions)e.timer&&(clearTimeout(e.timer),e.timer=null);this._forEachMedia(e=>e.pause()),this.emit("paused"),this.log.info("Playback paused (layout timer continues)")}}isPaused(){return this._paused}resume(){if(this._paused){this._paused=!1,this._forEachMedia(e=>e.play().catch(()=>{}));for(const[e]of this.regions)this.startRegion(e);this.emit("resumed"),this.log.info("Playback resumed")}}_forEachMedia(e){var t;for(const[,i]of this.regions)(t=i.element)==null||t.querySelectorAll("video, audio").forEach(e)}cleanup(){this.stopAllOverlays(),this.stopCurrentLayout();for(const e of this.audioOverlays.keys())this._stopAudioOverlays(e);this.layoutPool.clear(),this.preloadTimer&&(clearTimeout(this.preloadTimer),this.preloadTimer=null),this._preloadRetryTimer&&(clearTimeout(this._preloadRetryTimer),this._preloadRetryTimer=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.container.innerHTML="",this.log.info("Cleaned up")}}const N=R("Layout");class dt{constructor(e){this.xmds=e}async translateXLF(e,t){const n=new DOMParser().parseFromString(t,"text/xml"),o=n.querySelector("layout");if(!o)throw new Error("Invalid XLF: no <layout> element");const s=parseInt(o.getAttribute("width")||"1920"),r=parseInt(o.getAttribute("height")||"1080"),l=o.getAttribute("bgcolor")||"#000000",a=[];for(const c of n.querySelectorAll("region"))a.push(await this.translateRegion(e,c));return this.generateHTML(s,r,l,a)}async translateRegion(e,t){const i=t.getAttribute("id"),n=parseInt(t.getAttribute("width")),o=parseInt(t.getAttribute("height")),s=parseInt(t.getAttribute("top")),r=parseInt(t.getAttribute("left")),l=parseInt(t.getAttribute("zindex")||"0"),a=[];for(const c of t.querySelectorAll("media"))a.push(await this.translateMedia(e,i,c));return{id:i,width:n,height:o,top:s,left:r,zindex:l,media:a}}async translateMedia(e,t,i){const n=i.getAttribute("type"),o=parseInt(i.getAttribute("duration")||"10"),s=i.getAttribute("id"),r=i.querySelector("options"),l=i.querySelector("raw"),a={};if(r)for(const v of r.children)a[v.tagName]=v.textContent;const c={in:null,out:null},d=i.querySelector("options > transIn"),h=i.querySelector("options > transOut"),g=i.querySelector("options > transInDuration"),p=i.querySelector("options > transOutDuration"),m=i.querySelector("options > transInDirection"),w=i.querySelector("options > transOutDirection");d&&d.textContent&&(c.in={type:d.textContent,duration:parseInt((g==null?void 0:g.textContent)||"1000"),direction:(m==null?void 0:m.textContent)||"N"}),h&&h.textContent&&(c.out={type:h.textContent,duration:parseInt((p==null?void 0:p.textContent)||"1000"),direction:(w==null?void 0:w.textContent)||"N"});let b=l?l.textContent:"";if(["clock","clock-digital","clock-analogue","calendar","weather","currencies","stocks","twitter","global","embedded","text","ticker"].some(v=>n.includes(v))){let v=3,x=null;for(let C=1;C<=v;C++)try{N.info(`Fetching resource for ${n} widget (layout=${e}, region=${t}, media=${s}) - attempt ${C}/${v}`),b=await this.xmds.getResource(e,t,s),N.info(`Got resource HTML (${b.length} chars)`);const S=await Me(e,t,s,b);a.widgetCacheKey=S;break}catch(S){if(x=S,N.warn(`Failed to get resource (attempt ${C}/${v}):`,S.message),C<v){const T=C*2e3;N.info(`Retrying in ${T}ms...`),await new Promise($=>setTimeout($,T))}}if(!b&&x){N.warn("All retries failed, checking for cached widget HTML...");try{const C=await fetch(`/store/widget/${e}/${t}/${s}`);C.ok?(b=await C.text(),a.widgetCacheKey=`/cache/widget/${e}/${t}/${s}`,N.info(`Using stored widget HTML (${b.length} chars) - CMS update pending`)):(N.error(`No stored version available for widget ${s}`),b='<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;font-size:18px;">Content updating...</div>')}catch(C){N.error("Store fallback failed:",C),b='<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;font-size:18px;">Content updating...</div>'}}}return{type:n,duration:o,id:s,options:a,raw:b,transitions:c}}generateHTML(e,t,i,n){const o=n.map(r=>this.generateRegionHTML(r)).join(`
|
|
3
3
|
`),s=n.map(r=>this.generateRegionJS(r)).join(`,
|
|
4
4
|
`);return`<!DOCTYPE html>
|
|
@@ -720,5 +720,5 @@ ${t.join(`
|
|
|
720
720
|
border: none;
|
|
721
721
|
background: #1D1D1D;
|
|
722
722
|
display: none;
|
|
723
|
-
`,this.iframe.addEventListener("load",()=>{var o,s;try{if((((s=(o=this.iframe.contentWindow)==null?void 0:o.location)==null?void 0:s.href)||"").includes("index.html")){this.hide(),window.location.reload();return}const l=this.iframe.contentDocument;if(!l)return;l.addEventListener("keydown",a=>{a.key==="Escape"&&(a.preventDefault(),this.hide())})}catch{}}),this.backdrop.appendChild(this.cancelBtn),this.backdrop.appendChild(this.gateCard),this.backdrop.appendChild(this.iframe),document.body.appendChild(this.backdrop);const e=this.gateCard.querySelector("#gate-form"),t=this.gateCard.querySelector("#gate-key"),i=this.gateCard.querySelector("#gate-error"),n=this.gateCard.querySelector("#gate-cancel");t.addEventListener("focus",()=>{t.style.borderColor="#0097D8"}),t.addEventListener("blur",()=>{t.style.borderColor="#3A3A3A"}),e.addEventListener("submit",o=>{o.preventDefault(),t.value.trim()===ke.cmsKey?this.showSetup():(i.textContent="Incorrect CMS key",i.style.display="block",t.focus(),t.select())}),n.addEventListener("click",()=>this.hide()),this.backdrop.addEventListener("keydown",o=>{o.key==="Escape"&&(o.preventDefault(),this.hide()),o.stopPropagation()})}}const u=R("PWA"),z=new URL("./",window.location.href).pathname.replace(/\/$/,"");let ge,U,_,fe,ie,ye,A,q,pe,me,we,ve,be,Le;const F={};class st{constructor(){L(this,"renderer");L(this,"core");L(this,"xmds");L(this,"downloadOverlay",null);L(this,"timelineOverlay",null);L(this,"setupOverlay",null);L(this,"statsCollector",null);L(this,"logReporter",null);L(this,"displaySettings",null);L(this,"currentScheduleId",-1);L(this,"scheduledLayoutIds",new Set);L(this,"preparingLayoutId",null);L(this,"_pendingRetryLayoutId",null);L(this,"_screenshotInterval",null);L(this,"_screenshotMethod",null);L(this,"_screenshotInFlight",!1);L(this,"_html2canvasMod",null);L(this,"_wakeLock",null);L(this,"syncManager",null);L(this,"_currentLayoutEnableStat",!0);L(this,"_probeTimer",null);L(this,"_pendingFollowerStats",null);L(this,"_pendingFollowerLogs",null);L(this,"_iframeObserver",null);L(this,"_swIcHandler",null);L(this,"_swFileCachedHandler",null)}async init(){if(u.info("Initializing player with RendererLite + PlayerCore..."),await this.loadCoreModules(),"serviceWorker"in navigator)try{const i=await navigator.serviceWorker.register(`${z}/sw-pwa.js?v=${Date.now()}`,{scope:`${z}/`,type:"module",updateViaCache:"none"});u.info("Service Worker registered for offline mode:",i.scope),navigator.storage&&navigator.storage.persist&&(await navigator.storage.persist()?u.info("Persistent storage granted - cache won't be evicted"):u.warn("Persistent storage denied - cache may be evicted"))}catch(i){u.warn("Service Worker registration failed:",i)}u.info("Initializing cache clients..."),A=new Re,q=new Oe,await q.init(),u.info("Cache clients ready — StoreClient + DownloadClient");const e=document.getElementById("player-container");if(!e)throw new Error("No #player-container found");this.renderer=new Ne({cmsUrl:_.cmsUrl,hardwareKey:_.hardwareKey},e,{getMediaUrl:async i=>{if(u.debug(`getMediaUrl called for media ${i}`),!await A.has("media",String(i)))return u.warn(`Media ${i} not in cache`),"";const o=`${z}/cache/media/${i}`;return u.debug(`Using streaming URL for media ${i}: ${o}`),o},getWidgetHtml:async i=>{const n=`widget/${i.layoutId}/${i.regionId}/${i.id}`,o=`${z}/cache/widget/${i.layoutId}/${i.regionId}/${i.id}`;u.debug(`Looking for widget HTML at: ${n}`,i);try{if(await A.has("widget",`${i.layoutId}/${i.regionId}/${i.id}`))return u.debug(`Widget HTML found in store: ${n}, using cache URL for iframe`),{url:o,fallback:i.raw||""};u.warn(`No widget HTML found in store: ${n}`)}catch(s){u.error(`Failed to check widget HTML for ${i.id}:`,s)}return u.warn(`Using widget.raw fallback for ${i.id}`),i.raw||""}}),this.core=new it({config:_,xmds:this.xmds,cache:A,schedule:U,renderer:this.renderer,xmrWrapper:ye,statsCollector:this.statsCollector,displaySettings:this.displaySettings}),this.setupCoreEventHandlers(),this.setupRendererEventHandlers(),this.setupServiceWorkerEventHandlers(),this.setupInteractiveControl(),this.setupRemoteControls(),this.core.on("register-complete",i=>{var s,r;const n=parseFloat((s=i==null?void 0:i.settings)==null?void 0:s.latitude),o=parseFloat((r=i==null?void 0:i.settings)==null?void 0:r.longitude);n&&o&&!isNaN(n)&&!isNaN(o)?(u.info(`Display location from CMS: ${n.toFixed(4)}, ${o.toFixed(4)}`),U!=null&&U.setLocation&&U.setLocation(n,o)):this.core.requestGeoLocation&&(u.info("No CMS coordinates, requesting browser geolocation..."),this.core.requestGeoLocation())}),this.updateConfigDisplay(),window.addEventListener("online",()=>{u.info("Browser reports online — triggering immediate collection"),this.updateStatus("Back online, syncing..."),this.removeOfflineIndicator(),this.core.collectNow().catch(i=>{u.error("Failed to collect after coming online:",i)})}),window.addEventListener("offline",()=>{u.warn("Browser reports offline — continuing playback with cached data"),this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()});const t=de();t.enabled&&(this.downloadOverlay=new te(t),u.info("Download overlay enabled (hover bottom-right corner)")),nt()&&(this.timelineOverlay=new ue(!0,i=>this.skipToLayout(i))),await this.requestWakeLock(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.requestWakeLock()}),await this.core.collect(),u.info("Player initialized successfully")}async requestWakeLock(){if(!("wakeLock"in navigator)){u.debug("Wake Lock API not supported");return}try{this._wakeLock=await navigator.wakeLock.request("screen"),u.info("Screen Wake Lock acquired — display will stay on"),this._wakeLock.addEventListener("release",()=>{u.debug("Screen Wake Lock released"),this._wakeLock=null})}catch(e){u.warn("Wake Lock request failed:",e==null?void 0:e.message)}}async loadCoreModules(){var e,t,i;try{const n=await M(()=>import("./index-RNYmTctp.js"),__vite__mapDeps([0,1,2]),import.meta.url),o=await M(()=>import("./index-DBeB6nHq.js"),__vite__mapDeps([3,4,2]),import.meta.url),s=await M(()=>import("./index-BrJYfvV-.js"),__vite__mapDeps([5,6,2,1]),import.meta.url),r=await M(()=>import("./index-rMG3kuqV.js"),__vite__mapDeps([7,2,6,1]),import.meta.url),l=await M(()=>import("./index-B39PWpun.js"),__vite__mapDeps([8,2]),import.meta.url),a=await M(()=>import("./index-DD2ZPwTV.js"),__vite__mapDeps([9,2]),import.meta.url),c=await M(()=>import("./index-B9S4-Tg6.js"),__vite__mapDeps([10,2,6,1]),import.meta.url),d=await M(()=>import("./index-dSvc2qBf.js"),__vite__mapDeps([11,2,6,1]),import.meta.url),h=await M(()=>import("./index-BzTeZiFu.js"),__vite__mapDeps([12,6,2,1]),import.meta.url),g=await M(()=>import("./sync-manager-DBfiw5Ey.js"),__vite__mapDeps([13,2]),import.meta.url);if(ge=n.cacheWidgetHtml,Le=g.SyncManager,U=s.scheduleManager,_=r.config,fe=o.RestClient,ie=o.XmdsClient,ye=l.XmrWrapper,pe=a.StatsCollector,me=a.formatStats,we=a.LogReporter,ve=a.formatLogs,be=c.DisplaySettings,F.core=d.VERSION||"?",F.cache=n.VERSION||"?",F.renderer=h.VERSION||"?",F.schedule=s.VERSION||"?",F.xmds=o.VERSION||"?",F.xmr=l.VERSION||"?",F.utils=r.VERSION||"?",F.stats=a.VERSION||"?",F.settings=c.VERSION||"?",(e=window.electronAPI)!=null&&e.getSystemInfo)try{const S=await window.electronAPI.getSystemInfo();S.macAddress&&(_.macAddress=S.macAddress)}catch{}if(z.includes("pwa-xmds")||new URLSearchParams(window.location.search).get("transport")==="xmds")u.info("Using XMDS/SOAP transport (forced)"),this.xmds=new ie(_);else{this.xmds=new fe(_);try{await this.xmds.registerDisplay(),u.info("Using REST transport")}catch(S){u.warn("REST unavailable, falling back to XMDS/SOAP:",S.message),this.xmds=new ie(_)}}this.statsCollector=new pe,await this.statsCollector.init(),u.info("Stats collector initialized"),this.logReporter=new we,await this.logReporter.init(),u.info("Log reporter initialized"),De(({level:S,name:T,args:$})=>{if(!this.logReporter)return;const k=$.map(W=>typeof W=="string"?W:JSON.stringify(W)).join(" ");this.logReporter.log(S,`[${T}] ${k}`,"PLAYER").catch(()=>{})}),this.displaySettings=new be,u.info("Display settings manager initialized");const m="2026-02-26T23:56:26.484Z",w="0.5.13";u.info(`v${w} built ${m}`);const b=Object.entries(F).map(([S,T])=>`${S}=${T}`).join(" ");u.info(`SDK: ${b}`);const I=!!window.electronAPI,v=I?((t=navigator.userAgent.match(/Electron\/([\d.]+)/))==null?void 0:t[1])||"?":null,x=((i=navigator.userAgent.match(/Chrome\/([\d.]+)/))==null?void 0:i[1])||"?",C=I?`Electron ${v} / Chrome ${x}`:`Chrome ${x}`;u.info(`Env: PWA v${w} | ${C} | ${navigator.platform} | ${screen.width}x${screen.height}`),u.info("Core modules loaded")}catch(n){throw u.error("Failed to load core modules:",n),n}}setupCoreEventHandlers(){this.core.on("collection-start",()=>{this.updateStatus("Collecting data from CMS...")}),this.core.on("register-complete",e=>{var i;const t=((i=this.displaySettings)==null?void 0:i.getDisplayName())||e.displayName||_.hardwareKey;this.updateStatus(`Registered: ${t}`),this.displaySettings&&(document.title=`Xibo Player - ${this.displaySettings.getDisplayName()}`)}),this.core.on("sync-config",e=>{this.syncManager&&this.syncManager.stop(),this.syncManager=new Le({displayId:_.hardwareKey,syncConfig:e,onLayoutChange:async t=>{var i;u.info(`[Sync] Loading layout ${t} (waiting for show signal)`),await this.prepareAndRenderLayout(parseInt(t,10)),(i=this.syncManager)==null||i.reportReady(t)},onLayoutShow:t=>{u.info(`[Sync] Show signal for layout ${t}`)},onVideoStart:(t,i)=>{var n,o;u.info(`[Sync] Video start: layout ${t} region ${i}`),(o=(n=this.renderer).resumeRegionMedia)==null||o.call(n,i)},onStatsReport:async(t,i,n)=>{u.info(`[Sync] Submitting stats for follower ${t}`);try{await this.xmds.submitStats(i,t)&&n()}catch(o){u.warn(`[Sync] Stats submission failed for follower ${t}:`,o)}},onLogsReport:async(t,i,n)=>{u.info(`[Sync] Submitting logs for follower ${t}`);try{await this.xmds.submitLog(i,t)&&n()}catch(o){u.warn(`[Sync] Log submission failed for follower ${t}:`,o)}},onStatsAck:async t=>{u.info("[Sync] Lead confirmed stats submission"),this._pendingFollowerStats&&this.statsCollector&&(await this.statsCollector.clearSubmittedStats(this._pendingFollowerStats),this._pendingFollowerStats=null)},onLogsAck:async t=>{u.info("[Sync] Lead confirmed logs submission"),this._pendingFollowerLogs&&this.logReporter&&(await this.logReporter.clearSubmittedLogs(this._pendingFollowerLogs),this._pendingFollowerLogs=null)}}),this.core.setSyncManager(this.syncManager),this.syncManager.start(),u.info(`[Sync] SyncManager started as ${e.isLead?"LEAD":"FOLLOWER"}`)}),this.core.on("files-received",e=>{this.updateStatus(`Downloading ${e.length} files...`)}),this.core.on("offline-mode",e=>{e?(this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()):(this.updateStatus("Back online"),this.removeOfflineIndicator())}),this.core.on("purge-request",async e=>{try{const t=await A.remove(e);u.info(`Purge complete: ${t.deleted}/${t.total} files deleted`)}catch(t){u.warn("Purge failed:",t)}}),this.core.on("download-request",async e=>{var t;(t=this.downloadOverlay)==null||t.startUpdating();try{await q.download(e),u.info("Download request complete")}catch(i){u.error("Download request failed:",i),this.updateStatus("Download failed: "+i,"error")}}),this.core.on("schedule-received",e=>{var t;if(this.updateStatus("Processing schedule..."),e.layouts&&e.layouts.length>0?this.currentScheduleId=parseInt(e.layouts[0].scheduleid)||-1:e.campaigns&&e.campaigns.length>0&&(this.currentScheduleId=parseInt(e.campaigns[0].scheduleid)||-1),(t=this.renderer)!=null&&t.layoutPool){const i=new Set;if(e.layouts)for(const o of e.layouts){const s=parseInt(String(o.file||o.id||o).replace(".xlf",""),10);s&&i.add(s)}if(e.campaigns){for(const o of e.campaigns)if(o.layouts)for(const s of o.layouts){const r=parseInt(String(s.file||s.id||s).replace(".xlf",""),10);r&&i.add(r)}}const n=this.renderer.layoutPool.clearWarmNotIn(i);n>0&&u.info(`Cleared ${n} preloaded layout(s) no longer in schedule`),this.scheduledLayoutIds=i}u.debug("Current scheduleId for stats:",this.currentScheduleId)}),this.core.on("layout-prepare-request",async e=>{await this.prepareAndRenderLayout(e)}),this.core.on("no-layouts-scheduled",()=>{this.updateStatus("No layouts scheduled")}),this.core.on("collection-complete",()=>{const e=this.core.getCurrentLayoutId();e?this.updateStatus(`Playing layout ${e}`):this.preparingLayoutId&&this.updateStatus(`Downloading layout ${this.preparingLayoutId}...`),this.probeLayoutDurations().catch(t=>{u.debug("Duration probe failed (non-blocking):",t)})}),this.core.on("collection-error",e=>{var t;this.updateStatus(`Collection error: ${e}`,"error"),(t=this.logReporter)==null||t.reportFault("COLLECTION_FAILED",`Collection cycle failed: ${(e==null?void 0:e.message)||e}`),this.submitFault("COLLECTION_FAILED",`Collection cycle failed: ${(e==null?void 0:e.message)||e}`)}),this.core.on("xmr-connected",e=>{u.info("XMR connected:",e)}),this.core.on("xmr-misconfigured",e=>{u.warn(`XMR misconfigured (${e.reason}): ${e.message}`),u.warn(`XMR misconfigured: ${e.message}`)}),this.core.on("log-level-changed",()=>{const e=Ae();u.info(`Log level changed, debug=${e}`),e&&!this.downloadOverlay?(this.downloadOverlay=new te(de()),u.info("Download overlay enabled (log level → DEBUG)")):!e&&this.downloadOverlay&&(this.downloadOverlay.destroy(),this.downloadOverlay=null,u.info("Download overlay disabled (log level above DEBUG)"))}),this.core.on("overlay-layout-request",async e=>{u.info("Overlay layout requested:",e),await this.prepareAndRenderLayout(e)}),this.core.on("revert-to-schedule",()=>{u.info("Reverting to scheduled content"),this.updateStatus("Reverting to schedule...")}),this.core.on("purge-all-request",async()=>{u.info("Purging all cached content..."),this.updateStatus("Purging cache...");try{const e=await A.list();if(e.length>0){const i=await A.remove(e);u.info(`Purged ${i.deleted} files from ContentStore`)}const t=await caches.keys();t.length>0&&(await Promise.all(t.map(i=>caches.delete(i))),u.info(`Purged ${t.length} legacy caches`))}catch(e){u.error("Cache purge failed:",e)}}),this.core.on("command-result",e=>{var t;u.info("Command result:",e),e.success||((t=this.logReporter)==null||t.reportFault("COMMAND_FAILED",`Command ${e.code} failed: ${e.reason||"unknown"}`),this.submitFault("COMMAND_FAILED",`Command ${e.code} failed: ${e.reason||"unknown"}`))}),this.core.on("scheduled-command",e=>{u.info(`Scheduled command: ${e.code}`),this.core.executeCommand(e.code)}),this.displaySettings&&(this.displaySettings.on("interval-changed",e=>{u.info(`Collection interval changed to ${e}s`)}),this.displaySettings.on("settings-applied",(e,t)=>{t.length>0&&u.info("Settings updated from CMS:",t.join(", ")),this._screenshotInterval||this.startScreenshotInterval()})),this.core.on("submit-stats-request",async()=>{await this.submitStats()}),this.core.on("submit-logs-request",async()=>{await this.submitLogs()}),this.core.on("screenshot-request",async()=>{await this.captureAndSubmitScreenshot()}),this.core.on("check-pending-layout",async e=>{await this.prepareAndRenderLayout(e)}),this.core.on("timeline-updated",e=>{var t;(t=this.timelineOverlay)==null||t.update(e,this.core.getCurrentLayoutId())})}setupInteractiveControl(){var e;this._swIcHandler=t=>{var a,c;if(((a=t.data)==null?void 0:a.type)!=="INTERACTIVE_CONTROL")return;const{method:i,path:n,search:o,body:s}=t.data,r=(c=t.ports)==null?void 0:c[0];if(!r)return;const l=this.handleInteractiveControl(i,n,o,s);r.postMessage(l)},(e=navigator.serviceWorker)==null||e.addEventListener("message",this._swIcHandler)}setupRemoteControls(){window.addEventListener("blur",()=>{setTimeout(()=>window.focus(),200)});const e=t=>{const i=()=>{var n;try{const o=t.contentDocument||((n=t.contentWindow)==null?void 0:n.document);if(!o||t.__keyForwarderAttached)return;t.__keyForwarderAttached=!0,o.addEventListener("keydown",s=>{const r=new KeyboardEvent("keydown",{key:s.key,code:s.code,keyCode:s.keyCode,ctrlKey:s.ctrlKey,shiftKey:s.shiftKey,altKey:s.altKey,metaKey:s.metaKey,bubbles:!0,cancelable:!0});document.dispatchEvent(r)||s.preventDefault()})}catch{}};t.addEventListener("load",i),i()};Array.from(document.querySelectorAll("iframe")).forEach(t=>e(t)),this._iframeObserver=new MutationObserver(t=>{for(const i of t)for(const n of i.addedNodes)n instanceof HTMLIFrameElement&&e(n),n instanceof HTMLElement&&n.querySelectorAll("iframe").forEach(o=>e(o))}),this._iframeObserver.observe(document.body,{childList:!0,subtree:!0}),document.addEventListener("keydown",t=>{switch(t.key){case"t":case"T":this.timelineOverlay||(this.timelineOverlay=new ue(!0,i=>this.skipToLayout(i))),this.timelineOverlay.toggle();break;case"d":case"D":this.downloadOverlay||(this.downloadOverlay=new te({enabled:!0,autoHide:!1})),this.downloadOverlay.toggle();break;case"v":case"V":{const i=document.querySelectorAll("video"),n=i.length>0&&!i[0].controls;i.forEach(o=>o.controls=n);break}case"ArrowRight":case"PageDown":u.info("[Remote] Next layout (keyboard)"),this.core.advanceToNextLayout(),t.preventDefault();break;case"ArrowLeft":case"PageUp":u.info("[Remote] Previous layout (keyboard)"),this.core.advanceToPreviousLayout(),t.preventDefault();break;case" ":u.info("[Remote] Toggle pause (keyboard)"),this.renderer.isPaused()?this.renderer.resume():this.renderer.pause(),t.preventDefault();break;case"r":case"R":this.core.isLayoutOverridden()&&(u.info("[Remote] Revert to schedule (keyboard)"),this.core.revertToSchedule());break;case"s":case"S":this.setupOverlay||(this.setupOverlay=new ot),this.setupOverlay.toggle(),t.preventDefault();break}}),"mediaSession"in navigator&&(navigator.mediaSession.setActionHandler("nexttrack",()=>{u.info("[Remote] Next layout (MediaSession)"),this.core.advanceToNextLayout()}),navigator.mediaSession.setActionHandler("previoustrack",()=>{u.info("[Remote] Previous layout (MediaSession)"),this.core.advanceToPreviousLayout()}),navigator.mediaSession.setActionHandler("pause",()=>{u.info("[Remote] Pause (MediaSession)"),this.renderer.pause()}),navigator.mediaSession.setActionHandler("play",()=>{u.info("[Remote] Resume (MediaSession)"),this.renderer.resume()})),u.info("Remote controls initialized (keyboard + MediaSession)")}skipToLayout(e){u.info(`Skipping to layout ${e} (timeline click)`),this.core.changeLayout(e)}parseBody(e){try{return e?JSON.parse(e):{}}catch{return{}}}handleInteractiveControl(e,t,i,n){var o;switch(u.debug("IC request:",e,t,i),t){case"/info":return{status:200,body:JSON.stringify({hardwareKey:_.hardwareKey,displayName:_.displayName,playerType:"pwa",currentLayoutId:this.core.getCurrentLayoutId()})};case"/trigger":{const s=this.parseBody(n);return this.renderer.emit("interactiveTrigger",{targetId:s.id,triggerCode:s.trigger}),s.trigger&&this.core.handleTrigger(s.trigger),{status:200,body:"OK"}}case"/duration/expire":{const s=this.parseBody(n);return u.info("IC: Widget duration expire requested for",s.id),this.renderer.emit("widgetExpire",{widgetId:s.id}),{status:200,body:"OK"}}case"/duration/extend":{const s=this.parseBody(n);return u.info("IC: Widget duration extend by",s.duration,"for",s.id),this.renderer.emit("widgetExtendDuration",{widgetId:s.id,duration:parseInt(s.duration)}),{status:200,body:"OK"}}case"/duration/set":{const s=this.parseBody(n);return u.info("IC: Widget duration set to",s.duration,"for",s.id),this.renderer.emit("widgetSetDuration",{widgetId:s.id,duration:parseInt(s.duration)}),{status:200,body:"OK"}}case"/fault":{const s=this.parseBody(n);return(o=this.logReporter)==null||o.reportFault(s.code||"WIDGET_FAULT",s.reason||"Widget reported fault"),this.submitFault(s.code||"WIDGET_FAULT",s.reason||"Widget reported fault",{layoutId:s.layoutId,regionId:s.regionId,widgetId:s.widgetId}),{status:200,body:"OK"}}case"/realtime":{const r=new URLSearchParams(i).get("dataKey");if(u.debug("IC: Realtime data request for key:",r),!r)return{status:400,body:JSON.stringify({error:"Missing dataKey parameter"})};const a=this.core.getDataConnectorManager().getData(r);return a===null?{status:404,body:JSON.stringify({error:`No data available for key: ${r}`})}:{status:200,body:typeof a=="string"?a:JSON.stringify(a)}}case"/criteria":return{status:200,body:JSON.stringify({displayId:_.displayId,hardwareKey:_.hardwareKey,displayName:_.displayName,width:window.innerWidth,height:window.innerHeight,latitude:_.latitude||null,longitude:_.longitude||null,playerType:"pwa"})};default:return{status:404,body:JSON.stringify({error:"Unknown IC route"})}}}setupServiceWorkerEventHandlers(){navigator.serviceWorker&&(this._swFileCachedHandler=e=>{const{type:t,fileId:i,fileType:n}=e.data;t==="FILE_CACHED"&&(u.debug(`Service Worker cached ${n}/${i}`),(n==="media"||n==="layout")&&this.core.notifyMediaReady(parseInt(i),n),this._probeTimer&&clearTimeout(this._probeTimer),this._probeTimer=setTimeout(()=>{this._probeTimer=null,this.probeLayoutDurations().catch(()=>{})},3e3))},navigator.serviceWorker.addEventListener("message",this._swFileCachedHandler))}setupRendererEventHandlers(){this.renderer.on("layoutStart",(e,t)=>{var i;u.info("Layout started:",e),this.updateStatus(`Playing layout ${e}`),this.core.setCurrentLayout(e),this._currentLayoutEnableStat=(t==null?void 0:t.enableStat)!==!1,(i=this.timelineOverlay)==null||i.update(null,e),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.startLayout(e,this.currentScheduleId).catch(n=>{u.error("Failed to start layout stat:",n)})}),this.renderer.on("layoutEnd",e=>{u.info("Layout ended:",e),U==null||U.recordPlay(e.toString()),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.endLayout(e,this.currentScheduleId).catch(i=>{u.error("Failed to end layout stat:",i)}),this.core.notifyLayoutStatus(e),this.core.clearCurrentLayout();const t=this.core.getPendingLayouts();if(t.length>0){u.info(`Layout ${t[0]} pending download, skipping advance`);return}u.info("Layout cycle completed, advancing to next layout..."),this.core.advanceToNextLayout()}),this.renderer.on("widgetStart",e=>{const{widgetId:t,layoutId:i,mediaId:n}=e;u.debug("Widget started:",e.type,t,"media:",n),this.statsCollector&&n&&e.enableStat!==!1&&this.statsCollector.startWidget(n,i,this.currentScheduleId).catch(o=>{u.error("Failed to start widget stat:",o)})}),this.renderer.on("widgetEnd",e=>{const{widgetId:t,layoutId:i,mediaId:n}=e;u.debug("Widget ended:",e.type,t,"media:",n),this.statsCollector&&n&&e.enableStat!==!1&&this.statsCollector.endWidget(n,i,this.currentScheduleId).catch(o=>{u.error("Failed to end widget stat:",o)})}),this.renderer.on("error",e=>{var t;u.error("Renderer error:",e),this.updateStatus(`Error: ${e.type}`,"error"),(t=this.logReporter)==null||t.reportFault(e.type||"RENDERER_ERROR",`Renderer error: ${e.message||e.type} (layout ${e.layoutId||"unknown"})`),this.submitFault(e.type||"RENDERER_ERROR",`Renderer error: ${e.message||e.type}`,{layoutId:e.layoutId,regionId:e.regionId,widgetId:e.widgetId})}),this.renderer.on("action-trigger",e=>{var r,l;const{actionType:t,triggerCode:i,layoutCode:n,targetId:o,commandCode:s}=e;switch(u.info("Action trigger:",t,e),t){case"navLayout":case"navigateToLayout":i?this.core.handleTrigger(i):n&&this.core.changeLayout(n);break;case"navWidget":case"navigateToWidget":i?this.core.handleTrigger(i):o&&this.renderer.navigateToWidget(o);break;case"previousWidget":this.renderer.previousWidget((r=e.source)==null?void 0:r.regionId);break;case"nextWidget":this.renderer.nextWidget((l=e.source)==null?void 0:l.regionId);break;case"command":s&&this.core.executeCommand(s);break;default:u.warn("Unknown action type:",t)}this.statsCollector&&this.statsCollector.recordEvent("touch",this.core.getCurrentLayoutId(),e.targetId||null,this.currentScheduleId)}),this.renderer.on("widgetAction",e=>{e.type==="durationEnd"&&e.url&&(u.info(`Widget ${e.widgetId} duration ended, calling webhook: ${e.url}`),this.statsCollector&&this.statsCollector.recordEvent("webhook",e.layoutId,e.widgetId,this.currentScheduleId),fetch(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({widgetId:e.widgetId,layoutId:e.layoutId,regionId:e.regionId,event:"durationEnd",timestamp:new Date().toISOString()})}).catch(t=>u.warn("Webhook failed (non-critical):",t)))}),this.renderer.on("layoutDurationUpdated",(e,t)=>{this.core.recordLayoutDuration(String(e),t)}),this.renderer.on("request-next-layout-preload",async()=>{try{const e=this.core.peekNextLayout();if(!e){u.debug("No next layout to preload (single layout schedule or same layout)");return}const t=e.layoutId;if(this.renderer.layoutPool.has(t)){u.debug(`Layout ${t} already in preload pool`);return}u.info(`Preloading next layout ${t}...`);const i=await A.get("layout",t);if(!i){u.debug(`Layout ${t} XLF not cached, skipping preload`);return}const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(!await this.checkAllMediaCached(o)){u.debug(`Media not fully cached for layout ${t}, skipping preload`);return}await this.fetchWidgetHtml(n,t),await this.renderer.preloadLayout(n,t)?u.info(`Layout ${t} preloaded successfully`):u.warn(`Layout ${t} preload failed (will fall back to normal render)`)}catch(e){u.warn("Layout preload failed (non-blocking):",e)}})}async prepareAndRenderLayout(e){var t;if(this.core.getCurrentLayoutId()===e){u.debug(`Layout ${e} already playing, skipping duplicate prepare`);return}if(this.preparingLayoutId===e){u.debug(`Layout ${e} preparation in progress, will retry after it completes`),this._pendingRetryLayoutId=e;return}this.preparingLayoutId=e;try{const i=await A.get("layout",e);if(!i){u.info("Layout not in cache yet, marking as pending:",e),this.core.setPendingLayout(e,[e]),this.updateStatus(`Downloading layout ${e}...`);return}const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(!await this.checkAllMediaCached(o)){q.prioritizeLayout(o.map(String)),u.info(`Waiting for media to finish downloading for layout ${e}`),this.updateStatus(`Preparing layout ${e}...`),this.core.setPendingLayout(e,o);return}await this.fetchWidgetHtml(n,e),await this.renderer.renderLayout(n,e),this.updateStatus(`Playing layout ${e}`)}catch(i){u.error("Failed to prepare layout:",e,i),this.updateStatus(`Failed to load layout ${e}`,"error"),(t=this.logReporter)==null||t.reportFault("LAYOUT_LOAD_FAILED",`Failed to prepare layout ${e}: ${(i==null?void 0:i.message)||i}`),this.submitFault("LAYOUT_LOAD_FAILED",`Failed to prepare layout ${e}: ${(i==null?void 0:i.message)||i}`,{layoutId:e})}finally{this.preparingLayoutId=null;const i=this._pendingRetryLayoutId;this._pendingRetryLayoutId=null,i!=null&&this.core.getCurrentLayoutId()!==i&&(u.debug(`Retrying preparation for layout ${i} after 500ms`),setTimeout(()=>this.prepareAndRenderLayout(i),500))}}getMediaIds(e){var r;const i=new DOMParser().parseFromString(e,"text/xml"),n=[],o=[];i.querySelectorAll("media[fileId]").forEach(l=>{const a=l.getAttribute("fileId");if(a){const c=parseInt(a,10);n.push(c),l.getAttribute("type")==="video"&&o.push(c)}});const s=(r=i.querySelector("layout"))==null?void 0:r.getAttribute("background");if(s){const l=parseInt(s,10);!isNaN(l)&&!n.includes(l)&&n.push(l)}return{allMedia:n,videoMedia:o}}async checkAllMediaCached(e){for(const t of e)try{if(!await A.has("media",String(t)))return u.debug(`Media ${t} not yet cached`),!1;u.debug(`Media ${t} cached`)}catch{u.warn(`Unable to verify media ${t}, assuming cached (offline mode)`)}return!0}async fetchWidgetHtml(e,t){const n=new DOMParser().parseFromString(e,"text/xml"),o=[];for(const s of n.querySelectorAll("region")){const r=s.getAttribute("id");for(const l of s.querySelectorAll("media")){const a=l.getAttribute("type"),c=l.getAttribute("id");l.getAttribute("render")==="html"&&o.push((async()=>{try{const h=`${t}/${r}/${c}`;let g=null;const p=await A.get("widget",h);p&&(g=await p.text(),u.debug(`Found cached widget HTML for ${a} ${c}`)),g||(g=await this.xmds.getResource(t,r,c),u.debug(`Retrieved widget HTML for ${a} ${c} from CMS`)),await ge(t,r,c,g);const m=await A.get("widget",h);m&&(g=await m.text());const w=l.querySelector("raw");if(w)w.textContent=g;else{const b=n.createElement("raw");b.textContent=g,l.appendChild(b)}}catch(h){u.warn(`Failed to get widget HTML for ${a} ${c}:`,h)}})())}}o.length>0&&(u.info(`Fetching ${o.length} widget HTML resources in parallel...`),await Promise.all(o),u.debug("All widget HTML fetched"))}async probeLayoutDurations(){if(this.scheduledLayoutIds.size!==0)for(const e of this.scheduledLayoutIds)try{const t=await A.get("layout",e);if(!t)continue;const i=await t.text(),{videoMedia:n}=this.getMediaIds(i);if(n.length===0)continue;const s=new DOMParser().parseFromString(i,"text/xml"),r=new Map;for(const a of s.querySelectorAll('media[type="video"]')){if(a.getAttribute("useDuration")==="1")continue;const d=a.getAttribute("fileId");if(!d||!await A.has("media",d))continue;const g=await this.probeVideoDuration(`${z}/cache/media/${d}`);g>0&&r.set(d,g)}if(r.size===0)continue;let l=0;for(const a of s.querySelectorAll("region")){if(a.getAttribute("type")==="drawer")continue;let c=0;for(const d of a.querySelectorAll("media")){const h=parseInt(d.getAttribute("duration")||"0",10),g=parseInt(d.getAttribute("useDuration")||"1",10),p=d.getAttribute("fileId")||"",m=r.get(p);m!==void 0?c+=m:h>0&&g!==0&&(c+=h)}l=Math.max(l,c)}l>0&&this.core.recordLayoutDuration(String(e),l)}catch(t){u.debug(`Duration probe failed for layout ${e}:`,t)}}probeVideoDuration(e){return new Promise(t=>{const i=document.createElement("video");i.preload="metadata",i.muted=!0;const n=()=>{i.removeAttribute("src"),i.load()};i.addEventListener("loadedmetadata",()=>{const o=Math.floor(i.duration);n(),t(o)},{once:!0}),i.addEventListener("error",()=>{n(),t(0)},{once:!0}),setTimeout(()=>{n(),t(0)},5e3),i.src=e})}updateConfigDisplay(){const e=document.getElementById("config-info");if(e){const t="0.5.13",i="2026-02-26T23:56:26.484Z".replace("T"," ").replace(/\.\d+Z$/,""),n=i?`v${t} (${i})`:`v${t}`;e.textContent=`${n} | CMS: ${_.cmsUrl} | Display: ${_.displayName||"Unknown"} | HW: ${_.hardwareKey}`}}async submitStats(){var e;if(!this.statsCollector){u.warn("Stats collector not initialized");return}if(this._pendingFollowerStats!==null){u.debug("Stats delegation in-flight, skipping");return}try{const i=(((e=this.displaySettings)==null?void 0:e.getSetting("aggregationLevel"))||"Individual")==="Aggregate"?await this.statsCollector.getAggregatedStatsForSubmission(50):await this.statsCollector.getStatsForSubmission(50);if(i.length===0){u.debug("No stats to submit");return}const n=me(i);if(this.syncManager&&!this.syncManager.isLead&&this._syncLeadAlive()){u.info(`[Sync] Delegating ${i.length} stats to lead`),this._pendingFollowerStats=i,this.syncManager.reportStats(n);return}this.syncManager&&!this.syncManager.isLead&&u.warn("[Sync] Lead not alive, submitting stats directly"),u.info(`Submitting ${i.length} proof of play stats...`),await this.xmds.submitStats(n)?(u.info("Stats submitted successfully"),await this.statsCollector.clearSubmittedStats(i),u.debug(`Cleared ${i.length} submitted stats from database`)):u.warn("Stats submission failed (CMS returned false)")}catch(t){u.error("Failed to submit stats:",t)}}async submitLogs(){if(this.logReporter){if(this._pendingFollowerLogs!==null){u.debug("Logs delegation in-flight, skipping");return}try{const e=await this.logReporter.getLogsForSubmission();if(e.length===0){u.debug("No logs to submit");return}const t=ve(e);if(this.syncManager&&!this.syncManager.isLead&&this._syncLeadAlive()){u.info(`[Sync] Delegating ${e.length} logs to lead`),this._pendingFollowerLogs=e,this.syncManager.reportLogs(t);return}this.syncManager&&!this.syncManager.isLead&&u.warn("[Sync] Lead not alive, submitting logs directly"),u.info(`Submitting ${e.length} logs to CMS...`),await this.xmds.submitLog(t)?(u.info("Logs submitted successfully"),await this.logReporter.clearSubmittedLogs(e)):u.warn("Log submission failed (CMS returned false)")}catch(e){u.error("Failed to submit logs:",e)}}}submitFault(e,t,i){if(!this.xmds)return;const n=JSON.stringify([{code:e,reason:t,date:new Date().toISOString().replace("T"," ").substring(0,19),...i}]);this.xmds.reportFaults(n).catch(o=>{u.debug("reportFaults failed (non-critical):",o)})}async captureAndSubmitScreenshot(){var e;if(this._screenshotInFlight){u.debug("Screenshot capture already in progress, skipping");return}this._screenshotInFlight=!0;try{let t;if(this._screenshotMethod==="electron"||this._screenshotMethod===null&&((e=window.electronAPI)!=null&&e.captureScreenshot)){const n=await window.electronAPI.captureScreenshot();if(n)this._screenshotMethod="electron",t=n;else{u.debug("Electron screenshot not ready yet, will retry next interval");return}}else t=await this.captureWithBrowserMethods();await this.xmds.submitScreenShot(t)?u.info(`Screenshot submitted (${this._screenshotMethod})`):u.warn("Screenshot submission failed")}catch(t){u.error("Failed to capture screenshot:",t)}finally{this._screenshotInFlight=!1}}async captureWithBrowserMethods(){return this._screenshotMethod="html2canvas",this.captureHtml2Canvas()}async captureHtml2Canvas(){const e=document.createElement("canvas");e.width=window.innerWidth,e.height=window.innerHeight;const t=e.getContext("2d");t.fillStyle="#000",t.fillRect(0,0,e.width,e.height);const i=document.getElementById("player-container");if(!i)return e.toDataURL("image/jpeg",.8).split(",")[1];const n=i.getBoundingClientRect(),o=getComputedStyle(i),s=o.backgroundColor;s&&s!=="transparent"&&s!=="rgba(0, 0, 0, 0)"&&(t.fillStyle=s,t.fillRect(n.left,n.top,n.width,n.height));const r=o.backgroundImage;if(r&&r!=="none"){const c=r.match(/url\(["']?(.*?)["']?\)/);if(c)try{const d=new Image;d.crossOrigin="anonymous",await new Promise(h=>{d.onload=()=>h(),d.onerror=()=>h(),setTimeout(()=>h(),2e3),d.src=c[1]}),d.naturalWidth&&t.drawImage(d,n.left,n.top,n.width,n.height)}catch{}}this._html2canvasMod||(this._html2canvasMod=(await M(async()=>{const{default:c}=await import("./html2canvas.esm-CBrSDip1.js");return{default:c}},[],import.meta.url)).default);const l=i.querySelectorAll("img, video, iframe, canvas");let a=0;for(const c of l){const d=c;if(d.style.visibility==="hidden"||d.style.display==="none")continue;const h=c.getBoundingClientRect();if(!(h.width===0||h.height===0))try{if(c instanceof HTMLImageElement){if(!c.complete||!c.naturalWidth)continue;if(getComputedStyle(c).objectFit==="contain"&&c.naturalWidth&&c.naturalHeight){const p=this.containedRect(c.naturalWidth,c.naturalHeight,h);t.drawImage(c,p.x,p.y,p.w,p.h)}else t.drawImage(c,h.left,h.top,h.width,h.height);a++}else if(c instanceof HTMLVideoElement){if(c.readyState<2)continue;if(getComputedStyle(c).objectFit==="contain"&&c.videoWidth&&c.videoHeight){const p=this.containedRect(c.videoWidth,c.videoHeight,h);t.drawImage(c,p.x,p.y,p.w,p.h)}else t.drawImage(c,h.left,h.top,h.width,h.height);a++}else if(c instanceof HTMLCanvasElement)t.drawImage(c,h.left,h.top,h.width,h.height),a++;else if(c instanceof HTMLIFrameElement){const g=c.contentDocument;if(!(g!=null&&g.body))continue;const p=document.createElement("div");p.style.cssText=`position:fixed;left:-9999px;top:0;width:${h.width}px;height:${h.height}px;overflow:hidden;`;const m=[];for(const v of g.querySelectorAll("style"))p.appendChild(v.cloneNode(!0));for(const v of g.querySelectorAll('link[rel="stylesheet"]')){const x=document.createElement("link");x.rel="stylesheet",x.href=new URL(v.getAttribute("href")||"",g.baseURI).href,p.appendChild(x),m.push(new Promise(C=>{x.onload=()=>C(),x.onerror=()=>C()}))}p.appendChild(g.body.cloneNode(!0)),document.body.appendChild(p);const w=g.querySelectorAll("img"),b=new Map;w.forEach((v,x)=>{v.naturalWidth&&v.naturalHeight&&b.set(String(x),{nw:v.naturalWidth,nh:v.naturalHeight})}),m.length>0&&await Promise.race([Promise.all(m),new Promise(v=>setTimeout(v,500))]);const I=await this._html2canvasMod(p,{useCORS:!0,allowTaint:!0,logging:!1,backgroundColor:null,width:h.width,height:h.height,onclone:v=>{const x=v.createElement("style");x.textContent="*, *::before, *::after { animation: none !important; transition: none !important; opacity: 1 !important; }",v.head.appendChild(x),v.querySelectorAll("img").forEach((S,T)=>{var se,re;const $=(se=v.defaultView)==null?void 0:se.getComputedStyle(S);if(!$||$.objectFit!=="contain")return;const k=b.get(String(T));if(!k)return;const W=S.clientWidth||parseFloat($.width)||0,V=S.clientHeight||parseFloat($.height)||0;if(!W||!V)return;const Q=k.nw/k.nh,Ce=W/V;let Y,Z;Q>Ce?(Y=W,Z=W/Q):(Z=V,Y=V*Q);const ee=v.createElement("div");ee.style.cssText=`width:${W}px;height:${V}px;display:flex;align-items:center;justify-content:center;overflow:hidden;`,S.style.objectFit="fill",S.style.width=`${Y}px`,S.style.height=`${Z}px`,(re=S.parentNode)==null||re.insertBefore(ee,S),ee.appendChild(S)})}});document.body.removeChild(p),t.drawImage(I,h.left,h.top,h.width,h.height),a++}}catch(g){u.warn("Screenshot: failed to draw element",c.tagName,g)}}return u.debug(`Screenshot: composed ${a}/${l.length} elements`),e.toDataURL("image/jpeg",.8).split(",")[1]}containedRect(e,t,i){const n=e/t,o=i.width/i.height;let s,r;return n>o?(s=i.width,r=i.width/n):(r=i.height,s=i.height*n),{x:i.left+(i.width-s)/2,y:i.top+(i.height-r)/2,w:s,h:r}}startScreenshotInterval(){var i;const e=((i=this.displaySettings)==null?void 0:i.getSetting("screenshotInterval"))||0;if(!e||e<=0)return;this._html2canvasMod||M(()=>import("./html2canvas.esm-CBrSDip1.js"),[],import.meta.url).then(n=>{this._html2canvasMod=n.default});const t=e*1e3;u.info(`Starting periodic screenshots every ${e}s`),this._screenshotInterval=setInterval(()=>{this.captureAndSubmitScreenshot()},t)}updateStatus(e,t="info"){const i=document.getElementById("status");i&&(i.textContent=e,i.className=`status status-${t}`),t==="error"?u.error("Status:",e):u.info("Status:",e)}showOfflineIndicator(){var e;(e=this.timelineOverlay)==null||e.setOffline(!0)}removeOfflineIndicator(){var e;(e=this.timelineOverlay)==null||e.setOffline(!1)}_syncLeadAlive(){if(!this.syncManager)return!1;for(const[,e]of this.syncManager.followers)if(e.role==="lead"&&Date.now()-e.lastSeen<15e3)return!0;return!1}cleanup(){var e;this.core.cleanup(),this.renderer.cleanup(),this._screenshotInterval&&(clearInterval(this._screenshotInterval),this._screenshotInterval=null),this._wakeLock&&(this._wakeLock.release(),this._wakeLock=null),this.downloadOverlay&&this.downloadOverlay.destroy(),this.timelineOverlay&&this.timelineOverlay.destroy(),this._iframeObserver&&(this._iframeObserver.disconnect(),this._iframeObserver=null),navigator.serviceWorker&&(this._swIcHandler&&(navigator.serviceWorker.removeEventListener("message",this._swIcHandler),this._swIcHandler=null),this._swFileCachedHandler&&(navigator.serviceWorker.removeEventListener("message",this._swFileCachedHandler),this._swFileCachedHandler=null)),(e=q==null?void 0:q.cleanup)==null||e.call(q),this._probeTimer&&(clearTimeout(this._probeTimer),this._probeTimer=null)}}function Se(){const y=new st;y.init().catch(e=>{u.error("Failed to initialize:",e),u.warn("Redirecting to setup screen..."),window.location.href="./setup.html"}),window.addEventListener("beforeunload",()=>{y.cleanup()})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Se):Se();export{Ze as D,$e as E,ht as I,K as L,Ye as O,it as P,Ne as R,Qe as S,dt as a,Je as b,Ve as c,Be as p,ut as s};
|
|
724
|
-
//# sourceMappingURL=main-
|
|
723
|
+
`,this.iframe.addEventListener("load",()=>{var o,s;try{if((((s=(o=this.iframe.contentWindow)==null?void 0:o.location)==null?void 0:s.href)||"").includes("index.html")){this.hide(),window.location.reload();return}const l=this.iframe.contentDocument;if(!l)return;l.addEventListener("keydown",a=>{a.key==="Escape"&&(a.preventDefault(),this.hide())})}catch{}}),this.backdrop.appendChild(this.cancelBtn),this.backdrop.appendChild(this.gateCard),this.backdrop.appendChild(this.iframe),document.body.appendChild(this.backdrop);const e=this.gateCard.querySelector("#gate-form"),t=this.gateCard.querySelector("#gate-key"),i=this.gateCard.querySelector("#gate-error"),n=this.gateCard.querySelector("#gate-cancel");t.addEventListener("focus",()=>{t.style.borderColor="#0097D8"}),t.addEventListener("blur",()=>{t.style.borderColor="#3A3A3A"}),e.addEventListener("submit",o=>{o.preventDefault(),t.value.trim()===ke.cmsKey?this.showSetup():(i.textContent="Incorrect CMS key",i.style.display="block",t.focus(),t.select())}),n.addEventListener("click",()=>this.hide()),this.backdrop.addEventListener("keydown",o=>{o.key==="Escape"&&(o.preventDefault(),this.hide()),o.stopPropagation()})}}const u=R("PWA"),z=new URL("./",window.location.href).pathname.replace(/\/$/,"");let ge,U,_,fe,ie,ye,A,q,pe,me,we,ve,be,Le;const F={};class st{constructor(){L(this,"renderer");L(this,"core");L(this,"xmds");L(this,"downloadOverlay",null);L(this,"timelineOverlay",null);L(this,"setupOverlay",null);L(this,"statsCollector",null);L(this,"logReporter",null);L(this,"displaySettings",null);L(this,"currentScheduleId",-1);L(this,"scheduledLayoutIds",new Set);L(this,"preparingLayoutId",null);L(this,"_pendingRetryLayoutId",null);L(this,"_screenshotInterval",null);L(this,"_screenshotMethod",null);L(this,"_screenshotInFlight",!1);L(this,"_html2canvasMod",null);L(this,"_wakeLock",null);L(this,"syncManager",null);L(this,"_currentLayoutEnableStat",!0);L(this,"_probeTimer",null);L(this,"_pendingFollowerStats",null);L(this,"_pendingFollowerLogs",null);L(this,"_iframeObserver",null);L(this,"_swIcHandler",null);L(this,"_swFileCachedHandler",null)}async init(){if(u.info("Initializing player with RendererLite + PlayerCore..."),await this.loadCoreModules(),"serviceWorker"in navigator)try{const i=await navigator.serviceWorker.register(`${z}/sw-pwa.js?v=${Date.now()}`,{scope:`${z}/`,type:"module",updateViaCache:"none"});u.info("Service Worker registered for offline mode:",i.scope),navigator.storage&&navigator.storage.persist&&(await navigator.storage.persist()?u.info("Persistent storage granted - cache won't be evicted"):u.warn("Persistent storage denied - cache may be evicted"))}catch(i){u.warn("Service Worker registration failed:",i)}u.info("Initializing cache clients..."),A=new Re,q=new Oe,await q.init(),u.info("Cache clients ready — StoreClient + DownloadClient");const e=document.getElementById("player-container");if(!e)throw new Error("No #player-container found");this.renderer=new Ne({cmsUrl:_.cmsUrl,hardwareKey:_.hardwareKey},e,{getMediaUrl:async i=>{if(u.debug(`getMediaUrl called for media ${i}`),!await A.has("media",String(i)))return u.warn(`Media ${i} not in cache`),"";const o=`${z}/cache/media/${i}`;return u.debug(`Using streaming URL for media ${i}: ${o}`),o},getWidgetHtml:async i=>{const n=`widget/${i.layoutId}/${i.regionId}/${i.id}`,o=`${z}/cache/widget/${i.layoutId}/${i.regionId}/${i.id}`;u.debug(`Looking for widget HTML at: ${n}`,i);try{if(await A.has("widget",`${i.layoutId}/${i.regionId}/${i.id}`))return u.debug(`Widget HTML found in store: ${n}, using cache URL for iframe`),{url:o,fallback:i.raw||""};u.warn(`No widget HTML found in store: ${n}`)}catch(s){u.error(`Failed to check widget HTML for ${i.id}:`,s)}return u.warn(`Using widget.raw fallback for ${i.id}`),i.raw||""}}),this.core=new it({config:_,xmds:this.xmds,cache:A,schedule:U,renderer:this.renderer,xmrWrapper:ye,statsCollector:this.statsCollector,displaySettings:this.displaySettings}),this.setupCoreEventHandlers(),this.setupRendererEventHandlers(),this.setupServiceWorkerEventHandlers(),this.setupInteractiveControl(),this.setupRemoteControls(),this.core.on("register-complete",i=>{var s,r;const n=parseFloat((s=i==null?void 0:i.settings)==null?void 0:s.latitude),o=parseFloat((r=i==null?void 0:i.settings)==null?void 0:r.longitude);n&&o&&!isNaN(n)&&!isNaN(o)?(u.info(`Display location from CMS: ${n.toFixed(4)}, ${o.toFixed(4)}`),U!=null&&U.setLocation&&U.setLocation(n,o)):this.core.requestGeoLocation&&(u.info("No CMS coordinates, requesting browser geolocation..."),this.core.requestGeoLocation())}),this.updateConfigDisplay(),window.addEventListener("online",()=>{u.info("Browser reports online — triggering immediate collection"),this.updateStatus("Back online, syncing..."),this.removeOfflineIndicator(),this.core.collectNow().catch(i=>{u.error("Failed to collect after coming online:",i)})}),window.addEventListener("offline",()=>{u.warn("Browser reports offline — continuing playback with cached data"),this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()});const t=de();t.enabled&&(this.downloadOverlay=new te(t),u.info("Download overlay enabled (hover bottom-right corner)")),nt()&&(this.timelineOverlay=new ue(!0,i=>this.skipToLayout(i))),await this.requestWakeLock(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.requestWakeLock()}),await this.core.collect(),u.info("Player initialized successfully")}async requestWakeLock(){if(!("wakeLock"in navigator)){u.debug("Wake Lock API not supported");return}try{this._wakeLock=await navigator.wakeLock.request("screen"),u.info("Screen Wake Lock acquired — display will stay on"),this._wakeLock.addEventListener("release",()=>{u.debug("Screen Wake Lock released"),this._wakeLock=null})}catch(e){u.warn("Wake Lock request failed:",e==null?void 0:e.message)}}async loadCoreModules(){var e,t,i;try{const n=await M(()=>import("./index-DBYNSQLp.js"),__vite__mapDeps([0,1,2]),import.meta.url),o=await M(()=>import("./index-DgqUapYt.js"),__vite__mapDeps([3,4,2]),import.meta.url),s=await M(()=>import("./index-DAhOdNyB.js"),__vite__mapDeps([5,6,2,1]),import.meta.url),r=await M(()=>import("./index-Bcgq4p6v.js"),__vite__mapDeps([7,2,6,1]),import.meta.url),l=await M(()=>import("./index-ZD5qisoE.js"),__vite__mapDeps([8,2]),import.meta.url),a=await M(()=>import("./index-FlRMd3Sh.js"),__vite__mapDeps([9,2]),import.meta.url),c=await M(()=>import("./index-COInxuZI.js"),__vite__mapDeps([10,2,6,1]),import.meta.url),d=await M(()=>import("./index-BeGa2zKC.js"),__vite__mapDeps([11,2,6,1]),import.meta.url),h=await M(()=>import("./index-BczIv3fg.js"),__vite__mapDeps([12,6,2,1]),import.meta.url),g=await M(()=>import("./sync-manager-DBfiw5Ey.js"),__vite__mapDeps([13,2]),import.meta.url);if(ge=n.cacheWidgetHtml,Le=g.SyncManager,U=s.scheduleManager,_=r.config,fe=o.RestClient,ie=o.XmdsClient,ye=l.XmrWrapper,pe=a.StatsCollector,me=a.formatStats,we=a.LogReporter,ve=a.formatLogs,be=c.DisplaySettings,F.core=d.VERSION||"?",F.cache=n.VERSION||"?",F.renderer=h.VERSION||"?",F.schedule=s.VERSION||"?",F.xmds=o.VERSION||"?",F.xmr=l.VERSION||"?",F.utils=r.VERSION||"?",F.stats=a.VERSION||"?",F.settings=c.VERSION||"?",(e=window.electronAPI)!=null&&e.getSystemInfo)try{const S=await window.electronAPI.getSystemInfo();S.macAddress&&(_.macAddress=S.macAddress)}catch{}if(z.includes("pwa-xmds")||new URLSearchParams(window.location.search).get("transport")==="xmds")u.info("Using XMDS/SOAP transport (forced)"),this.xmds=new ie(_);else{this.xmds=new fe(_);try{await this.xmds.registerDisplay(),u.info("Using REST transport")}catch(S){u.warn("REST unavailable, falling back to XMDS/SOAP:",S.message),this.xmds=new ie(_)}}this.statsCollector=new pe,await this.statsCollector.init(),u.info("Stats collector initialized"),this.logReporter=new we,await this.logReporter.init(),u.info("Log reporter initialized"),De(({level:S,name:T,args:$})=>{if(!this.logReporter)return;const k=$.map(W=>typeof W=="string"?W:JSON.stringify(W)).join(" ");this.logReporter.log(S,`[${T}] ${k}`,"PLAYER").catch(()=>{})}),this.displaySettings=new be,u.info("Display settings manager initialized");const m="2026-02-27T12:48:50.017Z",w="0.5.14";u.info(`v${w} built ${m}`);const b=Object.entries(F).map(([S,T])=>`${S}=${T}`).join(" ");u.info(`SDK: ${b}`);const I=!!window.electronAPI,v=I?((t=navigator.userAgent.match(/Electron\/([\d.]+)/))==null?void 0:t[1])||"?":null,x=((i=navigator.userAgent.match(/Chrome\/([\d.]+)/))==null?void 0:i[1])||"?",C=I?`Electron ${v} / Chrome ${x}`:`Chrome ${x}`;u.info(`Env: PWA v${w} | ${C} | ${navigator.platform} | ${screen.width}x${screen.height}`),u.info("Core modules loaded")}catch(n){throw u.error("Failed to load core modules:",n),n}}setupCoreEventHandlers(){this.core.on("collection-start",()=>{this.updateStatus("Collecting data from CMS...")}),this.core.on("register-complete",e=>{var i;const t=((i=this.displaySettings)==null?void 0:i.getDisplayName())||e.displayName||_.hardwareKey;this.updateStatus(`Registered: ${t}`),this.displaySettings&&(document.title=`Xibo Player - ${this.displaySettings.getDisplayName()}`)}),this.core.on("sync-config",e=>{this.syncManager&&this.syncManager.stop(),this.syncManager=new Le({displayId:_.hardwareKey,syncConfig:e,onLayoutChange:async t=>{var i;u.info(`[Sync] Loading layout ${t} (waiting for show signal)`),await this.prepareAndRenderLayout(parseInt(t,10)),(i=this.syncManager)==null||i.reportReady(t)},onLayoutShow:t=>{u.info(`[Sync] Show signal for layout ${t}`)},onVideoStart:(t,i)=>{var n,o;u.info(`[Sync] Video start: layout ${t} region ${i}`),(o=(n=this.renderer).resumeRegionMedia)==null||o.call(n,i)},onStatsReport:async(t,i,n)=>{u.info(`[Sync] Submitting stats for follower ${t}`);try{await this.xmds.submitStats(i,t)&&n()}catch(o){u.warn(`[Sync] Stats submission failed for follower ${t}:`,o)}},onLogsReport:async(t,i,n)=>{u.info(`[Sync] Submitting logs for follower ${t}`);try{await this.xmds.submitLog(i,t)&&n()}catch(o){u.warn(`[Sync] Log submission failed for follower ${t}:`,o)}},onStatsAck:async t=>{u.info("[Sync] Lead confirmed stats submission"),this._pendingFollowerStats&&this.statsCollector&&(await this.statsCollector.clearSubmittedStats(this._pendingFollowerStats),this._pendingFollowerStats=null)},onLogsAck:async t=>{u.info("[Sync] Lead confirmed logs submission"),this._pendingFollowerLogs&&this.logReporter&&(await this.logReporter.clearSubmittedLogs(this._pendingFollowerLogs),this._pendingFollowerLogs=null)}}),this.core.setSyncManager(this.syncManager),this.syncManager.start(),u.info(`[Sync] SyncManager started as ${e.isLead?"LEAD":"FOLLOWER"}`)}),this.core.on("files-received",e=>{this.updateStatus(`Downloading ${e.length} files...`)}),this.core.on("offline-mode",e=>{e?(this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()):(this.updateStatus("Back online"),this.removeOfflineIndicator())}),this.core.on("purge-request",async e=>{try{const t=await A.remove(e);u.info(`Purge complete: ${t.deleted}/${t.total} files deleted`)}catch(t){u.warn("Purge failed:",t)}}),this.core.on("download-request",async e=>{var t;(t=this.downloadOverlay)==null||t.startUpdating();try{await q.download(e),u.info("Download request complete")}catch(i){u.error("Download request failed:",i),this.updateStatus("Download failed: "+i,"error")}}),this.core.on("schedule-received",e=>{var t;if(this.updateStatus("Processing schedule..."),e.layouts&&e.layouts.length>0?this.currentScheduleId=parseInt(e.layouts[0].scheduleid)||-1:e.campaigns&&e.campaigns.length>0&&(this.currentScheduleId=parseInt(e.campaigns[0].scheduleid)||-1),(t=this.renderer)!=null&&t.layoutPool){const i=new Set;if(e.layouts)for(const o of e.layouts){const s=parseInt(String(o.file||o.id||o).replace(".xlf",""),10);s&&i.add(s)}if(e.campaigns){for(const o of e.campaigns)if(o.layouts)for(const s of o.layouts){const r=parseInt(String(s.file||s.id||s).replace(".xlf",""),10);r&&i.add(r)}}const n=this.renderer.layoutPool.clearWarmNotIn(i);n>0&&u.info(`Cleared ${n} preloaded layout(s) no longer in schedule`),this.scheduledLayoutIds=i}u.debug("Current scheduleId for stats:",this.currentScheduleId)}),this.core.on("layout-prepare-request",async e=>{await this.prepareAndRenderLayout(e)}),this.core.on("no-layouts-scheduled",()=>{this.updateStatus("No layouts scheduled")}),this.core.on("collection-complete",()=>{const e=this.core.getCurrentLayoutId();e?this.updateStatus(`Playing layout ${e}`):this.preparingLayoutId&&this.updateStatus(`Downloading layout ${this.preparingLayoutId}...`),this.probeLayoutDurations().catch(t=>{u.debug("Duration probe failed (non-blocking):",t)})}),this.core.on("collection-error",e=>{var t;this.updateStatus(`Collection error: ${e}`,"error"),(t=this.logReporter)==null||t.reportFault("COLLECTION_FAILED",`Collection cycle failed: ${(e==null?void 0:e.message)||e}`),this.submitFault("COLLECTION_FAILED",`Collection cycle failed: ${(e==null?void 0:e.message)||e}`)}),this.core.on("xmr-connected",e=>{u.info("XMR connected:",e)}),this.core.on("xmr-misconfigured",e=>{u.warn(`XMR misconfigured (${e.reason}): ${e.message}`),u.warn(`XMR misconfigured: ${e.message}`)}),this.core.on("log-level-changed",()=>{const e=Ae();u.info(`Log level changed, debug=${e}`),e&&!this.downloadOverlay?(this.downloadOverlay=new te(de()),u.info("Download overlay enabled (log level → DEBUG)")):!e&&this.downloadOverlay&&(this.downloadOverlay.destroy(),this.downloadOverlay=null,u.info("Download overlay disabled (log level above DEBUG)"))}),this.core.on("overlay-layout-request",async e=>{u.info("Overlay layout requested:",e),await this.prepareAndRenderLayout(e)}),this.core.on("revert-to-schedule",()=>{u.info("Reverting to scheduled content"),this.updateStatus("Reverting to schedule...")}),this.core.on("purge-all-request",async()=>{u.info("Purging all cached content..."),this.updateStatus("Purging cache...");try{const e=await A.list();if(e.length>0){const i=await A.remove(e);u.info(`Purged ${i.deleted} files from ContentStore`)}const t=await caches.keys();t.length>0&&(await Promise.all(t.map(i=>caches.delete(i))),u.info(`Purged ${t.length} legacy caches`))}catch(e){u.error("Cache purge failed:",e)}}),this.core.on("command-result",e=>{var t;u.info("Command result:",e),e.success||((t=this.logReporter)==null||t.reportFault("COMMAND_FAILED",`Command ${e.code} failed: ${e.reason||"unknown"}`),this.submitFault("COMMAND_FAILED",`Command ${e.code} failed: ${e.reason||"unknown"}`))}),this.core.on("scheduled-command",e=>{u.info(`Scheduled command: ${e.code}`),this.core.executeCommand(e.code)}),this.displaySettings&&(this.displaySettings.on("interval-changed",e=>{u.info(`Collection interval changed to ${e}s`)}),this.displaySettings.on("settings-applied",(e,t)=>{t.length>0&&u.info("Settings updated from CMS:",t.join(", ")),this._screenshotInterval||this.startScreenshotInterval()})),this.core.on("submit-stats-request",async()=>{await this.submitStats()}),this.core.on("submit-logs-request",async()=>{await this.submitLogs()}),this.core.on("screenshot-request",async()=>{await this.captureAndSubmitScreenshot()}),this.core.on("check-pending-layout",async e=>{await this.prepareAndRenderLayout(e)}),this.core.on("timeline-updated",e=>{var t;(t=this.timelineOverlay)==null||t.update(e,this.core.getCurrentLayoutId())})}setupInteractiveControl(){var e;this._swIcHandler=t=>{var a,c;if(((a=t.data)==null?void 0:a.type)!=="INTERACTIVE_CONTROL")return;const{method:i,path:n,search:o,body:s}=t.data,r=(c=t.ports)==null?void 0:c[0];if(!r)return;const l=this.handleInteractiveControl(i,n,o,s);r.postMessage(l)},(e=navigator.serviceWorker)==null||e.addEventListener("message",this._swIcHandler)}setupRemoteControls(){window.addEventListener("blur",()=>{setTimeout(()=>window.focus(),200)});const e=l=>{const a=()=>{var c;try{const d=l.contentDocument||((c=l.contentWindow)==null?void 0:c.document);if(!d||l.__keyForwarderAttached)return;l.__keyForwarderAttached=!0,d.addEventListener("keydown",h=>{const g=new KeyboardEvent("keydown",{key:h.key,code:h.code,keyCode:h.keyCode,ctrlKey:h.ctrlKey,shiftKey:h.shiftKey,altKey:h.altKey,metaKey:h.metaKey,bubbles:!0,cancelable:!0});document.dispatchEvent(g)||h.preventDefault()})}catch{}};l.addEventListener("load",a),a()};Array.from(document.querySelectorAll("iframe")).forEach(l=>e(l)),this._iframeObserver=new MutationObserver(l=>{for(const a of l)for(const c of a.addedNodes)c instanceof HTMLIFrameElement&&e(c),c instanceof HTMLElement&&c.querySelectorAll("iframe").forEach(d=>e(d))}),this._iframeObserver.observe(document.body,{childList:!0,subtree:!0});const t=this.getControls(),{keyboard:i={}}=t,n=i.debugOverlays===!0,o=i.setupKey===!0,s=i.playbackControl===!0,r=i.videoControls===!0;document.addEventListener("keydown",l=>{switch(l.key){case"t":case"T":if(!n)break;this.timelineOverlay||(this.timelineOverlay=new ue(!0,a=>this.skipToLayout(a))),this.timelineOverlay.toggle();break;case"d":case"D":if(!n)break;this.downloadOverlay||(this.downloadOverlay=new te({enabled:!0,autoHide:!1})),this.downloadOverlay.toggle();break;case"v":case"V":{if(!r)break;const a=document.querySelectorAll("video"),c=a.length>0&&!a[0].controls;a.forEach(d=>d.controls=c);break}case"ArrowRight":case"PageDown":if(!s)break;u.info("[Remote] Next layout (keyboard)"),this.core.advanceToNextLayout(),l.preventDefault();break;case"ArrowLeft":case"PageUp":if(!s)break;u.info("[Remote] Previous layout (keyboard)"),this.core.advanceToPreviousLayout(),l.preventDefault();break;case" ":if(!s)break;u.info("[Remote] Toggle pause (keyboard)"),this.renderer.isPaused()?this.renderer.resume():this.renderer.pause(),l.preventDefault();break;case"r":case"R":if(!s)break;this.core.isLayoutOverridden()&&(u.info("[Remote] Revert to schedule (keyboard)"),this.core.revertToSchedule());break;case"s":case"S":if(!o)break;this.setupOverlay||(this.setupOverlay=new ot),this.setupOverlay.toggle(),l.preventDefault();break}}),s&&"mediaSession"in navigator&&(navigator.mediaSession.setActionHandler("nexttrack",()=>{u.info("[Remote] Next layout (MediaSession)"),this.core.advanceToNextLayout()}),navigator.mediaSession.setActionHandler("previoustrack",()=>{u.info("[Remote] Previous layout (MediaSession)"),this.core.advanceToPreviousLayout()}),navigator.mediaSession.setActionHandler("pause",()=>{u.info("[Remote] Pause (MediaSession)"),this.renderer.pause()}),navigator.mediaSession.setActionHandler("play",()=>{u.info("[Remote] Resume (MediaSession)"),this.renderer.resume()})),u.info("Remote controls initialized (keyboard + MediaSession)")}getControls(){try{return JSON.parse(localStorage.getItem("xibo_config")||"{}").controls||{}}catch{return{}}}skipToLayout(e){u.info(`Skipping to layout ${e} (timeline click)`),this.core.changeLayout(e)}parseBody(e){try{return e?JSON.parse(e):{}}catch{return{}}}handleInteractiveControl(e,t,i,n){var o;switch(u.debug("IC request:",e,t,i),t){case"/info":return{status:200,body:JSON.stringify({hardwareKey:_.hardwareKey,displayName:_.displayName,playerType:"pwa",currentLayoutId:this.core.getCurrentLayoutId()})};case"/trigger":{const s=this.parseBody(n);return this.renderer.emit("interactiveTrigger",{targetId:s.id,triggerCode:s.trigger}),s.trigger&&this.core.handleTrigger(s.trigger),{status:200,body:"OK"}}case"/duration/expire":{const s=this.parseBody(n);return u.info("IC: Widget duration expire requested for",s.id),this.renderer.emit("widgetExpire",{widgetId:s.id}),{status:200,body:"OK"}}case"/duration/extend":{const s=this.parseBody(n);return u.info("IC: Widget duration extend by",s.duration,"for",s.id),this.renderer.emit("widgetExtendDuration",{widgetId:s.id,duration:parseInt(s.duration)}),{status:200,body:"OK"}}case"/duration/set":{const s=this.parseBody(n);return u.info("IC: Widget duration set to",s.duration,"for",s.id),this.renderer.emit("widgetSetDuration",{widgetId:s.id,duration:parseInt(s.duration)}),{status:200,body:"OK"}}case"/fault":{const s=this.parseBody(n);return(o=this.logReporter)==null||o.reportFault(s.code||"WIDGET_FAULT",s.reason||"Widget reported fault"),this.submitFault(s.code||"WIDGET_FAULT",s.reason||"Widget reported fault",{layoutId:s.layoutId,regionId:s.regionId,widgetId:s.widgetId}),{status:200,body:"OK"}}case"/realtime":{const r=new URLSearchParams(i).get("dataKey");if(u.debug("IC: Realtime data request for key:",r),!r)return{status:400,body:JSON.stringify({error:"Missing dataKey parameter"})};const a=this.core.getDataConnectorManager().getData(r);return a===null?{status:404,body:JSON.stringify({error:`No data available for key: ${r}`})}:{status:200,body:typeof a=="string"?a:JSON.stringify(a)}}case"/criteria":return{status:200,body:JSON.stringify({displayId:_.displayId,hardwareKey:_.hardwareKey,displayName:_.displayName,width:window.innerWidth,height:window.innerHeight,latitude:_.latitude||null,longitude:_.longitude||null,playerType:"pwa"})};default:return{status:404,body:JSON.stringify({error:"Unknown IC route"})}}}setupServiceWorkerEventHandlers(){navigator.serviceWorker&&(this._swFileCachedHandler=e=>{const{type:t,fileId:i,fileType:n}=e.data;t==="FILE_CACHED"&&(u.debug(`Service Worker cached ${n}/${i}`),(n==="media"||n==="layout")&&this.core.notifyMediaReady(parseInt(i),n),this._probeTimer&&clearTimeout(this._probeTimer),this._probeTimer=setTimeout(()=>{this._probeTimer=null,this.probeLayoutDurations().catch(()=>{})},3e3))},navigator.serviceWorker.addEventListener("message",this._swFileCachedHandler))}setupRendererEventHandlers(){this.renderer.on("layoutStart",(e,t)=>{var i;u.info("Layout started:",e),this.updateStatus(`Playing layout ${e}`),this.core.setCurrentLayout(e),this._currentLayoutEnableStat=(t==null?void 0:t.enableStat)!==!1,(i=this.timelineOverlay)==null||i.update(null,e),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.startLayout(e,this.currentScheduleId).catch(n=>{u.error("Failed to start layout stat:",n)})}),this.renderer.on("layoutEnd",e=>{u.info("Layout ended:",e),U==null||U.recordPlay(e.toString()),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.endLayout(e,this.currentScheduleId).catch(i=>{u.error("Failed to end layout stat:",i)}),this.core.notifyLayoutStatus(e),this.core.clearCurrentLayout();const t=this.core.getPendingLayouts();if(t.length>0){u.info(`Layout ${t[0]} pending download, skipping advance`);return}u.info("Layout cycle completed, advancing to next layout..."),this.core.advanceToNextLayout()}),this.renderer.on("widgetStart",e=>{const{widgetId:t,layoutId:i,mediaId:n}=e;u.debug("Widget started:",e.type,t,"media:",n),this.statsCollector&&n&&e.enableStat!==!1&&this.statsCollector.startWidget(n,i,this.currentScheduleId).catch(o=>{u.error("Failed to start widget stat:",o)})}),this.renderer.on("widgetEnd",e=>{const{widgetId:t,layoutId:i,mediaId:n}=e;u.debug("Widget ended:",e.type,t,"media:",n),this.statsCollector&&n&&e.enableStat!==!1&&this.statsCollector.endWidget(n,i,this.currentScheduleId).catch(o=>{u.error("Failed to end widget stat:",o)})}),this.renderer.on("error",e=>{var t;u.error("Renderer error:",e),this.updateStatus(`Error: ${e.type}`,"error"),(t=this.logReporter)==null||t.reportFault(e.type||"RENDERER_ERROR",`Renderer error: ${e.message||e.type} (layout ${e.layoutId||"unknown"})`),this.submitFault(e.type||"RENDERER_ERROR",`Renderer error: ${e.message||e.type}`,{layoutId:e.layoutId,regionId:e.regionId,widgetId:e.widgetId})}),this.renderer.on("action-trigger",e=>{var r,l;const{actionType:t,triggerCode:i,layoutCode:n,targetId:o,commandCode:s}=e;switch(u.info("Action trigger:",t,e),t){case"navLayout":case"navigateToLayout":i?this.core.handleTrigger(i):n&&this.core.changeLayout(n);break;case"navWidget":case"navigateToWidget":i?this.core.handleTrigger(i):o&&this.renderer.navigateToWidget(o);break;case"previousWidget":this.renderer.previousWidget((r=e.source)==null?void 0:r.regionId);break;case"nextWidget":this.renderer.nextWidget((l=e.source)==null?void 0:l.regionId);break;case"command":s&&this.core.executeCommand(s);break;default:u.warn("Unknown action type:",t)}this.statsCollector&&this.statsCollector.recordEvent("touch",this.core.getCurrentLayoutId(),e.targetId||null,this.currentScheduleId)}),this.renderer.on("widgetAction",e=>{e.type==="durationEnd"&&e.url&&(u.info(`Widget ${e.widgetId} duration ended, calling webhook: ${e.url}`),this.statsCollector&&this.statsCollector.recordEvent("webhook",e.layoutId,e.widgetId,this.currentScheduleId),fetch(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({widgetId:e.widgetId,layoutId:e.layoutId,regionId:e.regionId,event:"durationEnd",timestamp:new Date().toISOString()})}).catch(t=>u.warn("Webhook failed (non-critical):",t)))}),this.renderer.on("layoutDurationUpdated",(e,t)=>{this.core.recordLayoutDuration(String(e),t)}),this.renderer.on("request-next-layout-preload",async()=>{try{const e=this.core.peekNextLayout();if(!e){u.debug("No next layout to preload (single layout schedule or same layout)");return}const t=e.layoutId;if(this.renderer.layoutPool.has(t)){u.debug(`Layout ${t} already in preload pool`);return}u.info(`Preloading next layout ${t}...`);const i=await A.get("layout",t);if(!i){u.debug(`Layout ${t} XLF not cached, skipping preload`);return}const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(!await this.checkAllMediaCached(o)){u.debug(`Media not fully cached for layout ${t}, skipping preload`);return}await this.fetchWidgetHtml(n,t),await this.renderer.preloadLayout(n,t)?u.info(`Layout ${t} preloaded successfully`):u.warn(`Layout ${t} preload failed (will fall back to normal render)`)}catch(e){u.warn("Layout preload failed (non-blocking):",e)}})}async prepareAndRenderLayout(e){var t;if(this.core.getCurrentLayoutId()===e){u.debug(`Layout ${e} already playing, skipping duplicate prepare`);return}if(this.preparingLayoutId===e){u.debug(`Layout ${e} preparation in progress, will retry after it completes`),this._pendingRetryLayoutId=e;return}this.preparingLayoutId=e;try{const i=await A.get("layout",e);if(!i){u.info("Layout not in cache yet, marking as pending:",e),this.core.setPendingLayout(e,[e]),this.updateStatus(`Downloading layout ${e}...`);return}const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(!await this.checkAllMediaCached(o)){q.prioritizeLayout(o.map(String)),u.info(`Waiting for media to finish downloading for layout ${e}`),this.updateStatus(`Preparing layout ${e}...`),this.core.setPendingLayout(e,o);return}await this.fetchWidgetHtml(n,e),await this.renderer.renderLayout(n,e),this.updateStatus(`Playing layout ${e}`)}catch(i){u.error("Failed to prepare layout:",e,i),this.updateStatus(`Failed to load layout ${e}`,"error"),(t=this.logReporter)==null||t.reportFault("LAYOUT_LOAD_FAILED",`Failed to prepare layout ${e}: ${(i==null?void 0:i.message)||i}`),this.submitFault("LAYOUT_LOAD_FAILED",`Failed to prepare layout ${e}: ${(i==null?void 0:i.message)||i}`,{layoutId:e})}finally{this.preparingLayoutId=null;const i=this._pendingRetryLayoutId;this._pendingRetryLayoutId=null,i!=null&&this.core.getCurrentLayoutId()!==i&&(u.debug(`Retrying preparation for layout ${i} after 500ms`),setTimeout(()=>this.prepareAndRenderLayout(i),500))}}getMediaIds(e){var r;const i=new DOMParser().parseFromString(e,"text/xml"),n=[],o=[];i.querySelectorAll("media[fileId]").forEach(l=>{const a=l.getAttribute("fileId");if(a){const c=parseInt(a,10);n.push(c),l.getAttribute("type")==="video"&&o.push(c)}});const s=(r=i.querySelector("layout"))==null?void 0:r.getAttribute("background");if(s){const l=parseInt(s,10);!isNaN(l)&&!n.includes(l)&&n.push(l)}return{allMedia:n,videoMedia:o}}async checkAllMediaCached(e){for(const t of e)try{if(!await A.has("media",String(t)))return u.debug(`Media ${t} not yet cached`),!1;u.debug(`Media ${t} cached`)}catch{u.warn(`Unable to verify media ${t}, assuming cached (offline mode)`)}return!0}async fetchWidgetHtml(e,t){const n=new DOMParser().parseFromString(e,"text/xml"),o=[];for(const s of n.querySelectorAll("region")){const r=s.getAttribute("id");for(const l of s.querySelectorAll("media")){const a=l.getAttribute("type"),c=l.getAttribute("id");l.getAttribute("render")==="html"&&o.push((async()=>{try{const h=`${t}/${r}/${c}`;let g=null;const p=await A.get("widget",h);p&&(g=await p.text(),u.debug(`Found cached widget HTML for ${a} ${c}`)),g||(g=await this.xmds.getResource(t,r,c),u.debug(`Retrieved widget HTML for ${a} ${c} from CMS`)),await ge(t,r,c,g);const m=await A.get("widget",h);m&&(g=await m.text());const w=l.querySelector("raw");if(w)w.textContent=g;else{const b=n.createElement("raw");b.textContent=g,l.appendChild(b)}}catch(h){u.warn(`Failed to get widget HTML for ${a} ${c}:`,h)}})())}}o.length>0&&(u.info(`Fetching ${o.length} widget HTML resources in parallel...`),await Promise.all(o),u.debug("All widget HTML fetched"))}async probeLayoutDurations(){if(this.scheduledLayoutIds.size!==0)for(const e of this.scheduledLayoutIds)try{const t=await A.get("layout",e);if(!t)continue;const i=await t.text(),{videoMedia:n}=this.getMediaIds(i);if(n.length===0)continue;const s=new DOMParser().parseFromString(i,"text/xml"),r=new Map;for(const a of s.querySelectorAll('media[type="video"]')){if(a.getAttribute("useDuration")==="1")continue;const d=a.getAttribute("fileId");if(!d||!await A.has("media",d))continue;const g=await this.probeVideoDuration(`${z}/cache/media/${d}`);g>0&&r.set(d,g)}if(r.size===0)continue;let l=0;for(const a of s.querySelectorAll("region")){if(a.getAttribute("type")==="drawer")continue;let c=0;for(const d of a.querySelectorAll("media")){const h=parseInt(d.getAttribute("duration")||"0",10),g=parseInt(d.getAttribute("useDuration")||"1",10),p=d.getAttribute("fileId")||"",m=r.get(p);m!==void 0?c+=m:h>0&&g!==0&&(c+=h)}l=Math.max(l,c)}l>0&&this.core.recordLayoutDuration(String(e),l)}catch(t){u.debug(`Duration probe failed for layout ${e}:`,t)}}probeVideoDuration(e){return new Promise(t=>{const i=document.createElement("video");i.preload="metadata",i.muted=!0;const n=()=>{i.removeAttribute("src"),i.load()};i.addEventListener("loadedmetadata",()=>{const o=Math.floor(i.duration);n(),t(o)},{once:!0}),i.addEventListener("error",()=>{n(),t(0)},{once:!0}),setTimeout(()=>{n(),t(0)},5e3),i.src=e})}updateConfigDisplay(){const e=document.getElementById("config-info");if(e){const t="0.5.14",i="2026-02-27T12:48:50.017Z".replace("T"," ").replace(/\.\d+Z$/,""),n=i?`v${t} (${i})`:`v${t}`;e.textContent=`${n} | CMS: ${_.cmsUrl} | Display: ${_.displayName||"Unknown"} | HW: ${_.hardwareKey}`}}async submitStats(){var e;if(!this.statsCollector){u.warn("Stats collector not initialized");return}if(this._pendingFollowerStats!==null){u.debug("Stats delegation in-flight, skipping");return}try{const i=(((e=this.displaySettings)==null?void 0:e.getSetting("aggregationLevel"))||"Individual")==="Aggregate"?await this.statsCollector.getAggregatedStatsForSubmission(50):await this.statsCollector.getStatsForSubmission(50);if(i.length===0){u.debug("No stats to submit");return}const n=me(i);if(this.syncManager&&!this.syncManager.isLead&&this._syncLeadAlive()){u.info(`[Sync] Delegating ${i.length} stats to lead`),this._pendingFollowerStats=i,this.syncManager.reportStats(n);return}this.syncManager&&!this.syncManager.isLead&&u.warn("[Sync] Lead not alive, submitting stats directly"),u.info(`Submitting ${i.length} proof of play stats...`),await this.xmds.submitStats(n)?(u.info("Stats submitted successfully"),await this.statsCollector.clearSubmittedStats(i),u.debug(`Cleared ${i.length} submitted stats from database`)):u.warn("Stats submission failed (CMS returned false)")}catch(t){u.error("Failed to submit stats:",t)}}async submitLogs(){if(this.logReporter){if(this._pendingFollowerLogs!==null){u.debug("Logs delegation in-flight, skipping");return}try{const e=await this.logReporter.getLogsForSubmission();if(e.length===0){u.debug("No logs to submit");return}const t=ve(e);if(this.syncManager&&!this.syncManager.isLead&&this._syncLeadAlive()){u.info(`[Sync] Delegating ${e.length} logs to lead`),this._pendingFollowerLogs=e,this.syncManager.reportLogs(t);return}this.syncManager&&!this.syncManager.isLead&&u.warn("[Sync] Lead not alive, submitting logs directly"),u.info(`Submitting ${e.length} logs to CMS...`),await this.xmds.submitLog(t)?(u.info("Logs submitted successfully"),await this.logReporter.clearSubmittedLogs(e)):u.warn("Log submission failed (CMS returned false)")}catch(e){u.error("Failed to submit logs:",e)}}}submitFault(e,t,i){if(!this.xmds)return;const n=JSON.stringify([{code:e,reason:t,date:new Date().toISOString().replace("T"," ").substring(0,19),...i}]);this.xmds.reportFaults(n).catch(o=>{u.debug("reportFaults failed (non-critical):",o)})}async captureAndSubmitScreenshot(){var e;if(this._screenshotInFlight){u.debug("Screenshot capture already in progress, skipping");return}this._screenshotInFlight=!0;try{let t;if(this._screenshotMethod==="electron"||this._screenshotMethod===null&&((e=window.electronAPI)!=null&&e.captureScreenshot)){const n=await window.electronAPI.captureScreenshot();if(n)this._screenshotMethod="electron",t=n;else{u.debug("Electron screenshot not ready yet, will retry next interval");return}}else t=await this.captureWithBrowserMethods();await this.xmds.submitScreenShot(t)?u.info(`Screenshot submitted (${this._screenshotMethod})`):u.warn("Screenshot submission failed")}catch(t){u.error("Failed to capture screenshot:",t)}finally{this._screenshotInFlight=!1}}async captureWithBrowserMethods(){return this._screenshotMethod="html2canvas",this.captureHtml2Canvas()}async captureHtml2Canvas(){const e=document.createElement("canvas");e.width=window.innerWidth,e.height=window.innerHeight;const t=e.getContext("2d");t.fillStyle="#000",t.fillRect(0,0,e.width,e.height);const i=document.getElementById("player-container");if(!i)return e.toDataURL("image/jpeg",.8).split(",")[1];const n=i.getBoundingClientRect(),o=getComputedStyle(i),s=o.backgroundColor;s&&s!=="transparent"&&s!=="rgba(0, 0, 0, 0)"&&(t.fillStyle=s,t.fillRect(n.left,n.top,n.width,n.height));const r=o.backgroundImage;if(r&&r!=="none"){const c=r.match(/url\(["']?(.*?)["']?\)/);if(c)try{const d=new Image;d.crossOrigin="anonymous",await new Promise(h=>{d.onload=()=>h(),d.onerror=()=>h(),setTimeout(()=>h(),2e3),d.src=c[1]}),d.naturalWidth&&t.drawImage(d,n.left,n.top,n.width,n.height)}catch{}}this._html2canvasMod||(this._html2canvasMod=(await M(async()=>{const{default:c}=await import("./html2canvas.esm-CBrSDip1.js");return{default:c}},[],import.meta.url)).default);const l=i.querySelectorAll("img, video, iframe, canvas");let a=0;for(const c of l){const d=c;if(d.style.visibility==="hidden"||d.style.display==="none")continue;const h=c.getBoundingClientRect();if(!(h.width===0||h.height===0))try{if(c instanceof HTMLImageElement){if(!c.complete||!c.naturalWidth)continue;if(getComputedStyle(c).objectFit==="contain"&&c.naturalWidth&&c.naturalHeight){const p=this.containedRect(c.naturalWidth,c.naturalHeight,h);t.drawImage(c,p.x,p.y,p.w,p.h)}else t.drawImage(c,h.left,h.top,h.width,h.height);a++}else if(c instanceof HTMLVideoElement){if(c.readyState<2)continue;if(getComputedStyle(c).objectFit==="contain"&&c.videoWidth&&c.videoHeight){const p=this.containedRect(c.videoWidth,c.videoHeight,h);t.drawImage(c,p.x,p.y,p.w,p.h)}else t.drawImage(c,h.left,h.top,h.width,h.height);a++}else if(c instanceof HTMLCanvasElement)t.drawImage(c,h.left,h.top,h.width,h.height),a++;else if(c instanceof HTMLIFrameElement){const g=c.contentDocument;if(!(g!=null&&g.body))continue;const p=document.createElement("div");p.style.cssText=`position:fixed;left:-9999px;top:0;width:${h.width}px;height:${h.height}px;overflow:hidden;`;const m=[];for(const v of g.querySelectorAll("style"))p.appendChild(v.cloneNode(!0));for(const v of g.querySelectorAll('link[rel="stylesheet"]')){const x=document.createElement("link");x.rel="stylesheet",x.href=new URL(v.getAttribute("href")||"",g.baseURI).href,p.appendChild(x),m.push(new Promise(C=>{x.onload=()=>C(),x.onerror=()=>C()}))}p.appendChild(g.body.cloneNode(!0)),document.body.appendChild(p);const w=g.querySelectorAll("img"),b=new Map;w.forEach((v,x)=>{v.naturalWidth&&v.naturalHeight&&b.set(String(x),{nw:v.naturalWidth,nh:v.naturalHeight})}),m.length>0&&await Promise.race([Promise.all(m),new Promise(v=>setTimeout(v,500))]);const I=await this._html2canvasMod(p,{useCORS:!0,allowTaint:!0,logging:!1,backgroundColor:null,width:h.width,height:h.height,onclone:v=>{const x=v.createElement("style");x.textContent="*, *::before, *::after { animation: none !important; transition: none !important; opacity: 1 !important; }",v.head.appendChild(x),v.querySelectorAll("img").forEach((S,T)=>{var se,re;const $=(se=v.defaultView)==null?void 0:se.getComputedStyle(S);if(!$||$.objectFit!=="contain")return;const k=b.get(String(T));if(!k)return;const W=S.clientWidth||parseFloat($.width)||0,V=S.clientHeight||parseFloat($.height)||0;if(!W||!V)return;const Q=k.nw/k.nh,Ce=W/V;let Y,Z;Q>Ce?(Y=W,Z=W/Q):(Z=V,Y=V*Q);const ee=v.createElement("div");ee.style.cssText=`width:${W}px;height:${V}px;display:flex;align-items:center;justify-content:center;overflow:hidden;`,S.style.objectFit="fill",S.style.width=`${Y}px`,S.style.height=`${Z}px`,(re=S.parentNode)==null||re.insertBefore(ee,S),ee.appendChild(S)})}});document.body.removeChild(p),t.drawImage(I,h.left,h.top,h.width,h.height),a++}}catch(g){u.warn("Screenshot: failed to draw element",c.tagName,g)}}return u.debug(`Screenshot: composed ${a}/${l.length} elements`),e.toDataURL("image/jpeg",.8).split(",")[1]}containedRect(e,t,i){const n=e/t,o=i.width/i.height;let s,r;return n>o?(s=i.width,r=i.width/n):(r=i.height,s=i.height*n),{x:i.left+(i.width-s)/2,y:i.top+(i.height-r)/2,w:s,h:r}}startScreenshotInterval(){var i;const e=((i=this.displaySettings)==null?void 0:i.getSetting("screenshotInterval"))||0;if(!e||e<=0)return;this._html2canvasMod||M(()=>import("./html2canvas.esm-CBrSDip1.js"),[],import.meta.url).then(n=>{this._html2canvasMod=n.default});const t=e*1e3;u.info(`Starting periodic screenshots every ${e}s`),this._screenshotInterval=setInterval(()=>{this.captureAndSubmitScreenshot()},t)}updateStatus(e,t="info"){const i=document.getElementById("status");i&&(i.textContent=e,i.className=`status status-${t}`),t==="error"?u.error("Status:",e):u.info("Status:",e)}showOfflineIndicator(){var e;(e=this.timelineOverlay)==null||e.setOffline(!0)}removeOfflineIndicator(){var e;(e=this.timelineOverlay)==null||e.setOffline(!1)}_syncLeadAlive(){if(!this.syncManager)return!1;for(const[,e]of this.syncManager.followers)if(e.role==="lead"&&Date.now()-e.lastSeen<15e3)return!0;return!1}cleanup(){var e;this.core.cleanup(),this.renderer.cleanup(),this._screenshotInterval&&(clearInterval(this._screenshotInterval),this._screenshotInterval=null),this._wakeLock&&(this._wakeLock.release(),this._wakeLock=null),this.downloadOverlay&&this.downloadOverlay.destroy(),this.timelineOverlay&&this.timelineOverlay.destroy(),this._iframeObserver&&(this._iframeObserver.disconnect(),this._iframeObserver=null),navigator.serviceWorker&&(this._swIcHandler&&(navigator.serviceWorker.removeEventListener("message",this._swIcHandler),this._swIcHandler=null),this._swFileCachedHandler&&(navigator.serviceWorker.removeEventListener("message",this._swFileCachedHandler),this._swFileCachedHandler=null)),(e=q==null?void 0:q.cleanup)==null||e.call(q),this._probeTimer&&(clearTimeout(this._probeTimer),this._probeTimer=null)}}function Se(){const y=new st;y.init().catch(e=>{u.error("Failed to initialize:",e),u.warn("Redirecting to setup screen..."),window.location.href="./setup.html"}),window.addEventListener("beforeunload",()=>{y.cleanup()})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Se):Se();export{Ze as D,$e as E,ht as I,K as L,Ye as O,it as P,Ne as R,Qe as S,dt as a,Je as b,Ve as c,Be as p,ut as s};
|
|
724
|
+
//# sourceMappingURL=main-DstA7-TG.js.map
|