@xiboplayer/pwa 0.6.11 → 0.6.13
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/chunk-config-C9U90T6u.js +2 -0
- package/dist/assets/chunk-config-C9U90T6u.js.map +1 -0
- package/dist/assets/{index-DMq935D7.js → index-B2dyKYhW.js} +2 -2
- package/dist/assets/{index-DMq935D7.js.map → index-B2dyKYhW.js.map} +1 -1
- package/dist/assets/{index-Dllq0Rxc.js → index-B57dvLVB.js} +2 -2
- package/dist/assets/{index-Dllq0Rxc.js.map → index-B57dvLVB.js.map} +1 -1
- package/dist/assets/{index-DuYioXxs.js → index-B_ADwXGQ.js} +2 -2
- package/dist/assets/{index-DuYioXxs.js.map → index-B_ADwXGQ.js.map} +1 -1
- package/dist/assets/{index-D3ONc-uh.js → index-BpwloMHc.js} +2 -2
- package/dist/assets/{index-D3ONc-uh.js.map → index-BpwloMHc.js.map} +1 -1
- package/dist/assets/{index-DpUJWDra.js → index-CLgKYdBJ.js} +2 -2
- package/dist/assets/{index-DpUJWDra.js.map → index-CLgKYdBJ.js.map} +1 -1
- package/dist/assets/index-ClTQ0ldA.js +2 -0
- package/dist/assets/{index-B2q-aBh8.js.map → index-ClTQ0ldA.js.map} +1 -1
- package/dist/assets/index-D39gYDMZ.js +2 -0
- package/dist/assets/{index-I6Jt7iN-.js.map → index-D39gYDMZ.js.map} +1 -1
- package/dist/assets/{index-DLnEjxEP.js → index-D9_3Ns4E.js} +2 -2
- package/dist/assets/{index-DLnEjxEP.js.map → index-D9_3Ns4E.js.map} +1 -1
- package/dist/assets/{index-DhU2Fgj5.js → index-GPOkOOlx.js} +2 -2
- package/dist/assets/{index-DhU2Fgj5.js.map → index-GPOkOOlx.js.map} +1 -1
- package/dist/assets/{index-DaK61i9Z.js → index-dBd5BTjH.js} +2 -2
- package/dist/assets/{index-DaK61i9Z.js.map → index-dBd5BTjH.js.map} +1 -1
- package/dist/assets/{main-D251kcoe.js → main-GlNtH9kX.js} +6 -6
- package/dist/assets/main-GlNtH9kX.js.map +1 -0
- package/dist/assets/{protocol-detector-BEdREUxU.js → protocol-detector-CpRVVofI.js} +3 -3
- package/dist/assets/protocol-detector-CpRVVofI.js.map +1 -0
- package/dist/assets/{setup-DbE9wDXy.js → setup-CInkLEZK.js} +2 -2
- package/dist/assets/{setup-DbE9wDXy.js.map → setup-CInkLEZK.js.map} +1 -1
- package/dist/assets/{sync-manager-CNULCESw.js → sync-manager-C0UDCBzv.js} +2 -2
- package/dist/assets/{sync-manager-CNULCESw.js.map → sync-manager-C0UDCBzv.js.map} +1 -1
- package/dist/assets/widget-html-BSjCib6e.js +2 -0
- package/dist/assets/widget-html-BSjCib6e.js.map +1 -0
- package/dist/index.html +3 -3
- package/dist/setup.html +3 -3
- package/dist/sw-pwa.js +1 -1
- package/package.json +13 -13
- package/dist/assets/chunk-config-C86koBXE.js +0 -2
- package/dist/assets/chunk-config-C86koBXE.js.map +0 -1
- package/dist/assets/index-B2q-aBh8.js +0 -2
- package/dist/assets/index-I6Jt7iN-.js +0 -2
- package/dist/assets/main-D251kcoe.js.map +0 -1
- package/dist/assets/protocol-detector-BEdREUxU.js.map +0 -1
- package/dist/assets/widget-html-CRNarPfj.js +0 -2
- package/dist/assets/widget-html-CRNarPfj.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-
|
|
2
|
-
var Fe=Object.defineProperty;var We=(y,e,t)=>e in y?Fe(y,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):y[e]=t;var L=(y,e,t)=>We(y,typeof e!="symbol"?e+"":e,t);import"./modulepreload-polyfill-B5Qt9EMX.js";import{createLogger as U,PLAYER_API as B,isDebug as Re,EventEmitter as Oe,fetchWithRetry as Ne,applyCmsLogLevel as qe,config as Be,registerLogSink as he}from"./index-Dllq0Rxc.js";import{c as Ue,C as He,D as ze,L as ae,B as ge,S as je}from"./widget-html-CRNarPfj.js";const Ve="modulepreload",Ke=function(y,e){return new URL(y,e).href},fe={},F=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]"),a=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));n=Promise.allSettled(t.map(l=>{if(l=Ke(l,i),l in fe)return;fe[l]=!0;const d=l.endsWith(".css"),c=d?'[rel="stylesheet"]':"";if(!!i)for(let w=s.length-1;w>=0;w--){const m=s[w];if(m.href===l&&(!d||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${c}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":Ve,d||(h.as="script"),h.crossOrigin="",h.href=l,a&&h.setAttribute("nonce",a),document.head.appendChild(h),d)return new Promise((w,m)=>{h.addEventListener("load",w),h.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${l}`)))})}))}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 Xe=()=>({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)}}});const oe=U("schedule:criteria"),Ge=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],ye={weatherTemp:"temperature",weatherHumidity:"humidity",weatherWindSpeed:"windSpeed",weatherCondition:"condition",weatherCloudCover:"cloudCover"};function Je(y,e,t={},i={}){switch(y){case"dayOfWeek":return Ge[e.getDay()];case"dayOfMonth":return String(e.getDate());case"month":return String(e.getMonth()+1);case"hour":return String(e.getHours());case"isoDay":return String(e.getDay()===0?7:e.getDay());default:if(ye[y]){const n=ye[y];return i[n]!==void 0?String(i[n]):(oe.debug(`Weather metric "${y}" requested but no weather data available`),null)}return t[y]!==void 0?String(t[y]):(oe.debug(`Unknown metric: ${y}`),null)}}function Qe(y,e,t,i){if(y===null)return!1;if(i==="number"){const s=parseFloat(y),r=parseFloat(t);if(isNaN(s)||isNaN(r))return!1;switch(e){case"equals":return s===r;case"notEquals":return s!==r;case"greaterThan":return s>r;case"greaterThanOrEquals":return s>=r;case"lessThan":return s<r;case"lessThanOrEquals":return s<=r;default:return!1}}const n=y.toLowerCase(),o=t.toLowerCase();switch(e){case"equals":return n===o;case"notEquals":return n!==o;case"contains":return n.includes(o);case"notContains":return!n.includes(o);case"startsWith":return n.startsWith(o);case"endsWith":return n.endsWith(o);case"in":return o.split(",").map(s=>s.trim().toLowerCase()).includes(n);case"greaterThan":return n>o;case"lessThan":return n<o;default:return oe.debug(`Unknown condition: ${e}`),!1}}function ce(y,e={}){if(!y||y.length===0)return!0;const t=e.now||new Date,i=e.displayProperties||{},n=e.weatherData||{};for(const o of y){const s=Je(o.metric,t,i,n);if(!Qe(s,o.condition,o.value,o.type))return oe.debug(`Criteria failed: ${o.metric} ${o.condition} "${o.value}" (actual: "${s}")`),!1}return!0}function Pe(y,e=null){const i=new DOMParser().parseFromString(y,"text/xml").querySelector("layout");if(!i)return{duration:60,isDynamic:!1};const n=parseInt(i.getAttribute("duration")||"0",10);if(n>0)return{duration:n,isDynamic:!1};let o=0,s=!1;for(const a of i.querySelectorAll("region")){const l=a.getAttribute("type");if(l==="drawer")continue;const d=l==="canvas";let c=0;for(const g of a.querySelectorAll("media")){const h=parseInt(g.getAttribute("duration")||"0",10),w=parseInt(g.getAttribute("useDuration")||"1",10),m=g.getAttribute("fileId")||"",p=e==null?void 0:e.get(m);let b;p!==void 0?b=p:h>0&&w!==0?b=h:(b=60,s=!0),d?c=Math.max(c,b):c+=b}o=Math.max(o,c)}return{duration:o>0?o:60,isDynamic:s}}function Ye(y,e){if(y.length!==e.length)return!1;for(let t=0;t<y.length;t++)if(y[t]!==e[t])return!1;return!0}function Ze(y,e,t){if(!e||e===0)return!0;const i=t-36e5,n=y.filter(o=>o>i);if(n.length>=e)return!1;if(n.length>0){const o=36e5/e,s=Math.max(...n);if(t-s<o)return!1}return!0}function pe(y,e,t){const i=y.filter(o=>{if(!o.maxPlaysPerHour||o.maxPlaysPerHour===0)return!0;const s=e.get(o.file)||[];return Ze(s,o.maxPlaysPerHour,t)});if(i.length===0)return[];const n=Math.max(...i.map(o=>o.priority));return i.filter(o=>o.priority===n).map(o=>o.file)}function et(y,e,t={}){const i=t.from||new Date,n=t.hours||2,o=new Date(i.getTime()+n*36e5);t.currentLayoutStartedAt;const s=t.defaultLayout||null,r=t.durations||null;if(!y||y.length===0)return[];const a=[];let l=new Date(i),d=e%y.length;const c=500;for(;l<o&&a.length<c;){const g=y[d];let h=r&&r.get(g.layoutId)||g.duration;const w=l.getTime()+h*1e3;a.push({layoutFile:g.layoutId,startTime:new Date(l),endTime:new Date(w),duration:h,isDefault:s?g.layoutId===s:!1}),l=new Date(w),d=(d+1)%y.length}return a}function tt(y,e){for(y=Math.abs(Math.round(y)),e=Math.abs(Math.round(e));e;)[y,e]=[e,y%e];return y}function it(y,e){return y===0||e===0?0:Math.abs(Math.round(y)*Math.round(e))/tt(y,e)}function nt(y){return y.reduce((e,t)=>it(e,t),1)}function ot(y,e,t={}){const{defaultLayout:i=null,defaultDuration:n=60}=t;if(y.length===0&&!i)return{queue:[],periodSeconds:0};const o=new Map;for(const w of y)w.duration>0&&o.set(w.file,w.duration);const s=w=>e.get(w)||o.get(w)||n,r=y.filter(w=>w.maxPlaysPerHour>0);let a;if(r.length>0){const w=r.map(m=>Math.round(3600/m.maxPlaysPerHour));a=nt(w),a>7200&&(a=7200)}else a=y.reduce((m,p)=>m+s(p.file),0)+(i&&!y.some(m=>m.file===i)?s(i):0)||n;const l=[],d=new Map;let c=0;const g=a*1e3,h=500;for(;c<g&&l.length<h;){const w=pe(y,d,c);if(w.length===0){if(i){const m=s(i);l.push({layoutId:i,duration:m}),c+=m*1e3}else c+=6e4;continue}for(let m=0;m<w.length&&c<g&&l.length<h;m++){const p=w[m],b=s(p);l.push({layoutId:p,duration:b}),d.has(p)||d.set(p,[]),d.get(p).push(c),c+=b*1e3;const _=pe(y,d,c);if(!Ye(w,_))break}}if(l.length===0&&i){const w=s(i);l.push({layoutId:i,duration:w})}return{queue:l,periodSeconds:a}}const q=U("Schedule");class st{constructor(e={}){this.schedule=null,this.playHistory=new Map,this.interruptScheduler=e.interruptScheduler||null,this.displayProperties=e.displayProperties||{},this.weatherData={},this.playerLocation=null,this._layoutMetadata=new Map,this._scheduleQueue=null,this._queuePosition=0,this._queueLayoutSet=null}setSchedule(e){this.schedule=e,this._invalidateQueue()}setWeatherData(e){this.weatherData=e||{}}getDataConnectors(){var e;return((e=this.schedule)==null?void 0:e.dataConnectors)||[]}getDependantsMap(){const e=new Map;if(!this.schedule)return e;const t=this.schedule.dependants||[],i=n=>{const o=parseInt(String(n.file||n.id).replace(".xlf",""),10),s=[...t,...n.dependants||[]];s.length>0&&e.set(o,s)};if(this.schedule.layouts)for(const n of this.schedule.layouts)i(n);if(this.schedule.campaigns)for(const n of this.schedule.campaigns)for(const o of n.layouts)i(o);return e}isRecurringScheduleActive(e,t){if(!e.recurrenceType)return!0;if(e.recurrenceRange){const i=new Date(e.recurrenceRange);if(t>i)return!1}switch(e.recurrenceType){case"Week":{if(e.recurrenceRepeatsOn){const i=this.getIsoDayOfWeek(t);if(!e.recurrenceRepeatsOn.split(",").map(o=>parseInt(o.trim())).includes(i))return!1}return!0}case"Day":{const i=e.recurrenceDetail||1;if(i>1&&e.fromdt){const n=new Date(e.fromdt),o=t.getTime()-n.getTime(),s=Math.floor(o/864e5);if(s<0||s%i!==0)return!1}return!0}case"Month":{if(e.recurrenceRepeatsOn){const n=e.recurrenceRepeatsOn.split(",").map(s=>parseInt(s.trim())),o=t.getDate();if(!n.includes(o))return!1}const i=e.recurrenceDetail||1;if(i>1&&e.fromdt){const n=new Date(e.fromdt),o=(t.getFullYear()-n.getFullYear())*12+t.getMonth()-n.getMonth();if(o<0||o%i!==0)return!1}return!0}default:return q.debug(`Unsupported recurrence type: ${e.recurrenceType}`),!0}}getIsoDayOfWeek(e){const t=e.getDay();return t===0?7:t}isTimeActive(e,t){const i=e.fromdt?new Date(e.fromdt):null,n=e.todt?new Date(e.todt):null;if(e.recurrenceType==="Week"||e.recurrenceType==="Day"||e.recurrenceType==="Month"){if(i&&n){const o=t.getHours()*3600+t.getMinutes()*60+t.getSeconds(),s=i.getHours()*3600+i.getMinutes()*60+i.getSeconds(),r=n.getHours()*3600+n.getMinutes()*60+n.getSeconds();return s<=r?o>=s&&o<=r:o>=s||o<=r}return!0}return!(i&&t<i||n&&t>n)}getCurrentLayouts(){return this._getLayoutsAt(new Date)}getLayoutsAtTime(e){return this._getLayoutsAt(e,{skipRateLimiting:!0,skipInterrupts:!0,quiet:!0})}getAllLayoutsAtTime(e){if(!this.schedule)return[];const t=e,i=[];if(this.schedule.layouts)for(const n of this.schedule.layouts)this.isRecurringScheduleActive(n,t)&&this.isTimeActive(n,t)&&(n.criteria&&n.criteria.length>0&&!ce(n.criteria,{now:t,displayProperties:this.displayProperties,weatherData:this.weatherData})||n.isGeoAware&&n.geoLocation&&!this.isWithinGeoFence(n.geoLocation)||i.push({file:n.file,priority:n.priority||0,maxPlaysPerHour:n.maxPlaysPerHour||0,duration:n.duration||0}));if(this.schedule.campaigns){for(const n of this.schedule.campaigns)if(this.isRecurringScheduleActive(n,t)&&this.isTimeActive(n,t))for(const o of n.layouts)i.push({file:o.file,priority:n.priority||0,maxPlaysPerHour:o.maxPlaysPerHour||0,duration:o.duration||0})}return i}detectConflicts(e={}){const t=e.from||new Date,i=e.hours||24,n=new Date(t.getTime()+i*36e5),o=6e4,s=[];let r=null;for(let a=t.getTime();a<n.getTime();a+=o){const l=new Date(a),d=this.getAllLayoutsAtTime(l);if(d.length===0){r&&(s.push(r),r=null);continue}const c=Math.max(...d.map(p=>p.priority)),g=d.filter(p=>p.priority<c);if(g.length===0){r&&(s.push(r),r=null);continue}const h=d.filter(p=>p.priority===c),w=h.map(p=>p.file).sort().join(","),m=g.map(p=>`${p.file}:${p.priority}`).sort().join(",");r&&r._winnerKey===w&&r._hiddenKey===m?r.endTime=new Date(a+o):(r&&s.push(r),r={startTime:new Date(a),endTime:new Date(a+o),winner:{file:h[0].file,priority:c},hidden:g.map(p=>({file:p.file,priority:p.priority})),_winnerKey:w,_hiddenKey:m})}r&&s.push(r);for(const a of s)delete a._winnerKey,delete a._hiddenKey;return s}_getLayoutsAt(e,t={}){if(!this.schedule)return[];const{skipRateLimiting:i=!1,skipInterrupts:n=!1,quiet:o=!1}=t,s=o?()=>{}:(...c)=>q.info(...c),r=[];if(this._maxActivePriority=0,this.schedule.campaigns)for(const c of this.schedule.campaigns)this.isRecurringScheduleActive(c,e)&&this.isTimeActive(c,e)&&(this._maxActivePriority=Math.max(this._maxActivePriority,c.priority||0),r.push({type:"campaign",priority:c.priority,layouts:c.layouts,campaignId:c.id}));if(this.schedule.layouts){for(const c of this.schedule.layouts)if(this.isRecurringScheduleActive(c,e)&&this.isTimeActive(c,e)){if(c.criteria&&c.criteria.length>0&&!ce(c.criteria,{now:e,displayProperties:this.displayProperties,weatherData:this.weatherData})){s("[Schedule] Layout",c.id,"filtered by criteria");continue}if(c.isGeoAware&&c.geoLocation&&!this.isWithinGeoFence(c.geoLocation)){s("[Schedule] Layout",c.id,"filtered by geofence");continue}if(this._maxActivePriority=Math.max(this._maxActivePriority,c.priority||0),!i&&!this.canPlayLayout(c.id,c.maxPlaysPerHour)){s("[Schedule] Layout",c.id,"filtered by maxPlaysPerHour (limit:",c.maxPlaysPerHour,")");continue}r.push({type:"layout",priority:c.priority||0,layouts:[c],layoutId:c.id})}}if(r.length===0)return this.schedule.default?[this.schedule.default]:[];let a=Math.max(...r.map(c=>c.priority));s("[Schedule] Max priority:",a,"from",r.length,"active items");let l=[];for(const c of r)c.priority===a?(s("[Schedule] Including priority",c.priority,"layouts:",c.layouts.map(g=>g.file)),l.push(...c.layouts)):s("[Schedule] Skipping priority",c.priority,"< max",a);this._layoutMetadata.clear();for(const c of l)this._layoutMetadata.set(c.file,{syncEvent:c.syncEvent||!1,shareOfVoice:c.shareOfVoice||0,scheduleid:c.scheduleid,priority:c.priority||0});if(!n&&this.interruptScheduler){const{normalLayouts:c,interruptLayouts:g}=this.interruptScheduler.separateLayouts(l);if(g.length>0){s("[Schedule] Found",g.length,"interrupt layouts with shareOfVoice");const w=this.interruptScheduler.processInterrupts(c,g).map(m=>m.file);return s("[Schedule] Final layouts (with interrupts):",w),w}}const d=l.map(c=>c.file);return s("[Schedule] Final layouts:",d),d}shouldCheckSchedule(e){return e?Date.now()-e>=6e4:!0}canPlayLayout(e,t){if(!t||t===0)return!0;const i=Date.now(),n=i-60*60*1e3,s=(this.playHistory.get(e)||[]).filter(r=>r>n);if(s.length>=t)return q.info(`Layout ${e} has reached max plays per hour (${s.length}/${t})`),!1;if(s.length>0){const r=36e5/t,a=Math.max(...s),l=i-a;if(l<r){const d=((r-l)/6e4).toFixed(1);return q.info(`Layout ${e} spacing: next play in ${d} min (${s.length}/${t} plays, ${Math.round(r/6e4)} min gap)`),!1}}return!0}recordPlay(e){this.playHistory.has(e)||this.playHistory.set(e,[]);const t=this.playHistory.get(e);t.push(Date.now());const i=Date.now()-60*60*1e3,n=t.filter(o=>o>i);this.playHistory.set(e,n),q.info(`Recorded play for layout ${e} (${n.length} plays in last hour)`)}getMaxActivePriority(){return this._maxActivePriority||0}isSyncEvent(e){const t=this._layoutMetadata.get(e);return(t==null?void 0:t.syncEvent)===!0}getLayoutMetadata(e){return this._layoutMetadata.get(e)||null}getScheduleQueue(e,t={}){var r;const i=this.getAllLayoutsAtTime(new Date),n=i.map(a=>`${a.file}:${a.priority}:${a.maxPlaysPerHour}`).sort().join("|");if(this._scheduleQueue&&this._queueLayoutSet===n)return this._scheduleQueue;const o=ot(i,e,{defaultLayout:((r=this.schedule)==null?void 0:r.default)||null,defaultDuration:60,dynamicLayouts:t.dynamicLayouts||new Set}),s=this._queueLayoutSet;return this._scheduleQueue=o,this._queueLayoutSet=n,s!==n&&(this._queuePosition=0),o.queue.length>0&&(q.info(`[Schedule] Built queue: ${o.queue.length} entries, period ${o.periodSeconds}s (pos ${this._queuePosition})`),q.info(`[Schedule] Queue: ${o.queue.map(a=>`${a.layoutId}(${a.duration}s)`).join(" → ")}`)),o}popNextFromQueue(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);if(i.length===0)return null;const n=i[this._queuePosition%i.length];return this._queuePosition=(this._queuePosition+1)%i.length,n}peekNextInQueue(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);return i.length===0?null:i[this._queuePosition%i.length]}peekAfterNext(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);return i.length<=1?null:i[(this._queuePosition+1)%i.length]}_invalidateQueue(){this._scheduleQueue=null}hasSyncEvents(){for(const e of this._layoutMetadata.values())if(e.syncEvent)return!0;return!1}getActiveActions(){var t;if(!((t=this.schedule)!=null&&t.actions))return[];const e=new Date;return this.schedule.actions.filter(i=>this.isTimeActive(i,e))}getCommands(){var e;return((e=this.schedule)==null?void 0:e.commands)||[]}findActionByTrigger(e){return this.getActiveActions().find(i=>i.triggerCode===e)||null}clearPlayHistory(){this.playHistory.clear(),q.info("Play history cleared")}setLocation(e,t){this.playerLocation={latitude:e,longitude:t},q.info(`Location set: ${e}, ${t}`)}setDisplayProperties(e){this.displayProperties=e||{}}isWithinGeoFence(e,t=500){if(!this.playerLocation)return q.debug("No player location, skipping geofence check"),!0;if(!e)return!0;const i=e.split(",").map(l=>parseFloat(l.trim()));if(i.length<2||isNaN(i[0])||isNaN(i[1]))return q.warn("Invalid geoLocation format:",e),!0;const n=i[0],o=i[1],s=i[2]||t,r=this.haversineDistance(this.playerLocation.latitude,this.playerLocation.longitude,n,o),a=r<=s;return q.info(`Geofence: ${r.toFixed(0)}m from (${n},${o}), radius ${s}m → ${a?"WITHIN":"OUTSIDE"}`),a}haversineDistance(e,t,i,n){const s=d=>d*Math.PI/180,r=s(i-e),a=s(n-t),l=Math.sin(r/2)**2+Math.cos(s(e))*Math.cos(s(i))*Math.sin(a/2)**2;return 6371e3*2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))}}const vt=new st,H=U("schedule:interrupts");class bt{constructor(){this.interruptCommittedDurations=new Map}isInterrupt(e){return!!(e.shareOfVoice&&e.shareOfVoice>0)}resetCommittedDurations(){this.interruptCommittedDurations.clear(),H.debug("Reset interrupt committed durations")}getCommittedDuration(e){return this.interruptCommittedDurations.get(e)||0}addCommittedDuration(e,t){const i=this.getCommittedDuration(e);this.interruptCommittedDurations.set(e,i+t)}isInterruptDurationSatisfied(e){if(!e.shareOfVoice)return!0;const t=e.id||e.file,i=e.shareOfVoice/100*3600;return this.getCommittedDuration(t)>=i}getRequiredSeconds(e){return e.shareOfVoice?e.shareOfVoice/100*3600:0}processInterrupts(e,t){if(!t||t.length===0)return H.debug("No interrupt layouts, returning normal layouts"),e;if(!e||e.length===0)return H.warn("No normal layouts available, interrupts will fill entire hour"),this.fillHourWithInterrupts(t);H.info(`Processing ${t.length} interrupt layouts with ${e.length} normal layouts`);for(const d of t){const c=d.id||d.file;this.interruptCommittedDurations.set(c,0)}const i=[];let n=0,o=0,s=!1;for(;!s;){if(o>=t.length){o=0;let c=!0;for(const g of t)if(!this.isInterruptDurationSatisfied(g)){c=!1;break}if(c){s=!0;break}}const d=t[o];if(!this.isInterruptDurationSatisfied(d)){const c=d.id||d.file;this.addCommittedDuration(c,d.duration),n+=d.duration,i.push(d)}o++}if(H.debug(`Resolved ${i.length} interrupt plays (${n}s total)`),n>=3600)return H.info("Interrupts fill entire hour (>= 3600s), no room for normal layouts"),i;const r=3600-n,a=this.fillTimeWithLayouts(e,r);H.debug(`Resolved ${a.length} normal plays (${r}s target)`);const l=this.interleaveLayouts(a,i);return H.info(`Final loop: ${l.length} layouts (${a.length} normal + ${i.length} interrupts)`),l}fillTimeWithLayouts(e,t){const i=[];let n=t,o=0;for(;n>0;){o>=e.length&&(o=0);const s=e[o];i.push(s),n-=s.duration,o++}return i}fillHourWithInterrupts(e){return this.fillTimeWithLayouts(e,3600)}interleaveLayouts(e,t){const i=[],n=Math.max(e.length,t.length),o=Math.ceil(1*n/e.length),s=Math.floor(1*n/t.length);H.debug(`Interleaving: pickCount=${n}, normalPick=${o}, interruptPick=${s}`);let r=0,a=0,l=0;for(let d=0;d<n;d++)d%o===0&&(r>=e.length&&(r=0),i.push(e[r]),l+=e[r].duration,r++),d%s===0&&a<t.length&&(i.push(t[a]),l+=t[a].duration,a++);for(;l<3600;)r>=e.length&&(r=0),i.push(e[r]),l+=e[r].duration,r++;return H.debug(`Interleaved ${i.length} layouts, total duration: ${l}s`),i}separateLayouts(e){const t=[],i=[];for(const n of e)this.isInterrupt(n)?i.push(n):t.push(n);return{normalLayouts:t,interruptLayouts:i}}}const Q=U("schedule:overlays");class rt{constructor(){this.overlays=[],this.displayProperties={},this.scheduleManager=null,Q.debug("OverlayScheduler initialized")}setScheduleManager(e){this.scheduleManager=e}setDisplayProperties(e){this.displayProperties=e||{}}setOverlays(e){this.overlays=e||[],Q.info(`Loaded ${this.overlays.length} overlay(s)`)}getCurrentOverlays(){if(!this.overlays||this.overlays.length===0)return[];const e=new Date,t=[];for(const i of this.overlays){if(!this.isTimeActive(i,e)){Q.debug(`Overlay ${i.file} not in time window`);continue}if(i.isGeoAware&&i.geoLocation&&this.scheduleManager&&!this.scheduleManager.isWithinGeoFence(i.geoLocation)){Q.debug(`Overlay ${i.file} filtered by geofence`);continue}if(i.criteria&&i.criteria.length>0&&!ce(i.criteria,{now:e,displayProperties:this.displayProperties})){Q.debug(`Overlay ${i.file} filtered by criteria`);continue}t.push(i)}return t.sort((i,n)=>{const o=i.priority||0;return(n.priority||0)-o}),t.length>0&&Q.info(`Active overlays: ${t.length}`),t}isTimeActive(e,t){const i=e.fromdt||e.fromDt?new Date(e.fromdt||e.fromDt):null,n=e.todt||e.toDt?new Date(e.todt||e.toDt):null;return!(i&&t<i||n&&t>n)}shouldCheckOverlays(e){return e?Date.now()-e>=6e4:!0}getOverlayByFile(e){return this.overlays.find(t=>t.file===e)||null}clear(){this.overlays=[],Q.debug("Cleared all overlays")}processOverlays(e,t){return this.setOverlays(t),e}}new rt;const Y=U("LayoutPool");class ie{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),Y.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(Y.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&&ie.releaseMediaElements(t.container),t.blobUrls&&t.blobUrls.size>0&&(t.blobUrls.forEach(i=>{URL.revokeObjectURL(i)}),Y.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()}),e.querySelectorAll(".pdf-widget").forEach(n=>{n._pdfDestroy&&n._pdfDestroy()}),t>0&&Y.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&&Y.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&&Y.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 ne={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":return t?this.fadeIn(y,s):this.fadeOut(y,s);case"fadein":return t?this.fadeIn(y,s):null;case"fadeout":return t?null:this.fadeOut(y,s);case"fly":return t?this.flyIn(y,s,r,i,n):this.flyOut(y,s,r,i,n);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 at{constructor(e,t,i={}){this.config=e,this.container=t,this.options=i,this.log=U("RendererLite",i.logLevel),this.emitter=Xe(),this.currentLayout=null,this.currentLayoutId=null,this._preloadingLayoutId=null,this.regions=new Map,this.layoutTimer=null,this.layoutEndEmitted=!1,this._deferredTimerLayoutId=null,this._paused=!1,this._layoutTimerStartedAt=null,this._layoutTimerDurationMs=null,this.widgetTimers=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._startedWidgets=new Set,this.layoutPool=new ie(2),this.preloadTimer=null,this._preloadRetryTimer=null,this.setupContainer(),this.emitter.on("interactiveTrigger",n=>this._handleInteractiveTrigger(n)),this.emitter.on("widgetExpire",n=>this._handleWidgetExpire(n)),this.emitter.on("widgetExtendDuration",n=>this._handleWidgetExtendDuration(n)),this.emitter.on("widgetSetDuration",n=>this._handleWidgetSetDuration(n)),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",this._resizeSuppressed=!1,typeof ResizeObserver<"u"){let e=null;this.resizeObserver=new ResizeObserver(()=>{this._resizeSuppressed||(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 a of r){const l=a.tagName==="drawer",d=a.getAttribute("type")||null,c={id:a.getAttribute("id"),width:parseInt(a.getAttribute("width")||"0"),height:parseInt(a.getAttribute("height")||"0"),top:parseInt(a.getAttribute("top")||"0"),left:parseInt(a.getAttribute("left")||"0"),zindex:parseInt(a.getAttribute("zindex")||(l?"2000":"0")),enableStat:a.getAttribute("enableStat")!=="0",actions:this.parseActions(a),exitTransition:null,transitionType:null,transitionDuration:null,transitionDirection:null,loop:!0,isDrawer:l,isCanvas:d==="canvas",widgets:[]},g=Array.from(a.children).find(h=>h.tagName==="options");if(g){const h=g.querySelector("exitTransType");if(h&&h.textContent){const p=g.querySelector("exitTransDuration"),b=g.querySelector("exitTransDirection");c.exitTransition={type:h.textContent,duration:parseInt(p&&p.textContent||"1000"),direction:b&&b.textContent||"N"}}const w=g.querySelector("loop");w&&(c.loop=w.textContent!=="0");const m=g.querySelector("transitionType");if(m&&m.textContent){c.transitionType=m.textContent;const p=g.querySelector("transitionDuration"),b=g.querySelector("transitionDirection");c.transitionDuration=parseInt(p&&p.textContent||"1000"),c.transitionDirection=b&&b.textContent||"N"}}for(const h of a.children){if(h.tagName!=="media")continue;const w=this.parseWidget(h);c.widgets.push(w)}!c.isCanvas&&c.widgets.some(h=>h.type==="global")&&(c.isCanvas=!0),s.regions.push(c),l&&this.log.info(`Parsed drawer: id=${c.id} with ${c.widgets.length} widgets`),c.isCanvas&&this.log.info(`Parsed canvas region: id=${c.id} with ${c.widgets.length} widgets (all render simultaneously)`)}if(s.duration===0){const{duration:a,isDynamic:l}=Pe(e);s.duration=a,s.isDynamic=l,this.log.info(`Calculated layout duration: ${s.duration}s (not specified in XLF)${l?" [dynamic — has useDuration=0 video]":""}`)}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={},a=e.querySelector("options");if(a)for(const v of a.children)r[v.tagName]=v.textContent;const l=e.querySelector("raw"),d=l?l.textContent:"",c={in:null,out:null};r.transIn&&(c.in={type:r.transIn,duration:parseInt(r.transInDuration||"1000"),direction:r.transInDirection||"N"}),r.transOut&&(c.out={type:r.transOut,duration:parseInt(r.transOutDuration||"1000"),direction:r.transOutDirection||"N"});const g=this.parseActions(e),h=[];for(const v of e.children)if(v.tagName.toLowerCase()==="audio"){const S=v.querySelector("uri");S?h.push({mediaId:S.getAttribute("mediaId")||null,uri:S.textContent||"",volume:parseInt(S.getAttribute("volume")||"100"),loop:S.getAttribute("loop")==="1"}):h.push({mediaId:v.getAttribute("mediaId")||null,uri:v.getAttribute("uri")||"",volume:parseInt(v.getAttribute("volume")||"100"),loop:v.getAttribute("loop")==="1"})}const w=[],m=Array.from(e.children).find(v=>v.tagName==="commands");if(m)for(const v of m.children)v.tagName==="command"&&w.push({commandCode:v.getAttribute("commandCode")||"",commandString:v.getAttribute("commandString")||""});const p=e.getAttribute("parentWidgetId")||null,b=parseInt(e.getAttribute("displayOrder")||"0"),_=e.getAttribute("cyclePlayback")==="1",C=parseInt(e.getAttribute("playCount")||"0"),R=e.getAttribute("isRandom")==="1",x=e.getAttribute("fromDt")||e.getAttribute("fromdt")||null,T=e.getAttribute("toDt")||e.getAttribute("todt")||null,$=e.getAttribute("render")||null;return{type:t,duration:i,useDuration:n,id:o,fileId:s,render:$,fromDt:x,toDt:T,enableStat:e.getAttribute("enableStat")!=="0",webhookUrl:r.webhookUrl||null,options:r,raw:d,transitions:c,actions:g,audioNodes:h,commands:w,parentWidgetId:p,displayOrder:b,cyclePlayback:_,playCount:C,isRandom:R}}trackBlobUrl(e){const t=this._preloadingLayoutId||this.currentLayoutId||0;t||this.log.warn("trackBlobUrl called without currentLayoutId, tracking under key 0"),this.layoutBlobUrls.has(t)||this.layoutBlobUrls.set(t,new Set),this.layoutBlobUrls.get(t).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;this.currentLayout.duration=e,this.log.info(`Layout duration updated: ${t}s → ${e}s (based on video metadata)`);const i=!this._hasUnprobedVideos();if(this.emit("layoutDurationUpdated",this.currentLayoutId,e,i),this._deferredTimerLayoutId===this.currentLayoutId&&!this.layoutTimer)if(this._hasUnprobedVideos())this.log.info(`Layout duration updated to ${e}s but still has unprobed videos — keeping timer deferred`);else{const n=Date.now()-(this._layoutTimerStartedAt||Date.now()),o=Math.max(1e3,e*1e3-n);this._deferredTimerLayoutId=null,this._layoutTimerDurationMs=o,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))},o),this.log.info(`All video durations resolved — deferred timer started: ${(o/1e3).toFixed(1)}s remaining (waited ${(n/1e3).toFixed(1)}s for metadata)`)}else if(this.layoutTimer){clearTimeout(this.layoutTimer);const n=Date.now()-(this._layoutTimerStartedAt||Date.now()),o=Math.max(1e3,this.currentLayout.duration*1e3-n);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))},o),this.log.info(`Layout timer adjusted to ${(o/1e3).toFixed(1)}s remaining (elapsed ${(n/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 a=s.widgetElements.get(r.id);if(a)for(const l of r.actions)l.triggerType==="touch"?(this.attachTouchAction(a,l,o.id,r.id),i++):l.triggerType.startsWith("keyboard:")&&t.push(l)}}}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=""}}_findRegionByWidgetId(e){for(const[t,i]of this.regions){const n=i.widgets.findIndex(o=>o.id===e);if(n!==-1)return{regionId:t,region:i,widget:i.widgets[n],widgetIndex:n,regionMap:this.regions}}for(const t of this.activeOverlays.values())if(t.regions)for(const[i,n]of t.regions){const o=n.widgets.findIndex(s=>s.id===e);if(o!==-1)return{regionId:i,region:n,widget:n.widgets[o],widgetIndex:o,regionMap:t.regions}}return null}_advanceRegion(e,t){const i=t.get(e);if(!i)return;i.currentIndex=(i.currentIndex+1)%i.widgets.length;const n=t===this.regions;this._startRegionCycle(i,e,n?(o,s)=>this.renderWidget(o,s):(o,s)=>this.renderWidget(o,s),n?(o,s)=>this.stopWidget(o,s):(o,s)=>this.stopWidget(o,s),n?()=>this.checkLayoutComplete():void 0)}_handleInteractiveTrigger({targetId:e,triggerCode:t}){this.log.info(`XIC interactiveTrigger: target=${e} code=${t}`),this._findRegionByWidgetId(e)?this.navigateToWidget(e):this.log.warn(`XIC interactiveTrigger: widget ${e} not found`)}_handleWidgetExpire({widgetId:e}){const t=this._findRegionByWidgetId(e);if(!t){this.log.warn(`XIC widgetExpire: widget ${e} not found`);return}const{regionId:i,region:n,widgetIndex:o,regionMap:s}=t;this.log.info(`XIC widgetExpire: widget=${e} region=${i}`),n.timer&&(clearTimeout(n.timer),n.timer=null),this.stopWidget(i,o),this._advanceRegion(i,s)}_handleWidgetExtendDuration({widgetId:e,duration:t}){const i=this._findRegionByWidgetId(e);if(!i){this.log.warn(`XIC widgetExtendDuration: widget ${e} not found`);return}const{regionId:n,region:o}=i;this.log.info(`XIC widgetExtendDuration: widget=${e} +${t}s`),o.timer&&(clearTimeout(o.timer),o.timer=null),o.timer=setTimeout(()=>{this.stopWidget(n,o.currentIndex),this._advanceRegion(n,i.regionMap)},t*1e3)}_handleWidgetSetDuration({widgetId:e,duration:t}){const i=this._findRegionByWidgetId(e);if(!i){this.log.warn(`XIC widgetSetDuration: widget ${e} not found`);return}const{regionId:n,region:o}=i;this.log.info(`XIC widgetSetDuration: widget=${e} ${t}s`),o.timer&&(clearTimeout(o.timer),o.timer=null),o.timer=setTimeout(()=>{this.stopWidget(n,o.currentIndex),this._advanceRegion(n,i.regionMap)},t*1e3)}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)`)):i.isDrawer?this.navigateToWidget(i.widgets[r].id):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)}_mediaFileUrl(e){return`${window.location.origin}${B}/media/file/${e}`}_positionWidgetElement(e){Object.assign(e.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",visibility:"hidden",opacity:"0"})}_applyBackgroundImage(e,t){Object.assign(e.style,{backgroundImage:`url(${t})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"})}_clearRegionTimers(e){for(const[,t]of e)t.timer&&(clearTimeout(t.timer),t.timer=null)}async renderLayout(e,t){var i;try{if(this.log.info(`Rendering layout ${t}`),this.currentLayoutId===t){this.log.info(`Replaying layout ${t} - reusing elements (no recreation!)`),this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,(s,r)=>this.stopWidget(s,r));for(const[,s]of this.regions)s.currentIndex=0,s.complete=!1;this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this._deferredTimerLayoutId=null,this.layoutEndEmitted=!1,this.emit("layoutStart",t,this.currentLayout);for(const[s,r]of this.regions)r.isDrawer||this.startRegion(s);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 o=this.parseXlf(e);if(this.currentLayout=o,this.currentLayoutId=t,this.calculateScale(o),this.container.style.backgroundColor=o.bgcolor,this.container.style.backgroundImage="",o.background){const s=((i=this.options.fileIdToSaveAs)==null?void 0:i.get(String(o.background)))||o.background;this._applyBackgroundImage(this.container,this._mediaFileUrl(s)),this.log.info(`Background image set: ${o.background} → ${s}`)}for(const s of o.regions)await this.createRegion(s);this.log.info("Pre-creating widget elements for instant transitions...");for(const[s,r]of this.regions)for(let a=0;a<r.widgets.length;a++){const l=r.widgets[a];l.layoutId=this.currentLayoutId,l.regionId=s;try{const d=await this.createWidgetElement(l,r);this._positionWidgetElement(d),r.element.appendChild(d),r.widgetElements.set(l.id,d)}catch(d){this.log.error(`Failed to pre-create widget ${l.id}:`,d)}}if(this.log.info("All widget elements pre-created"),this.attachActionListeners(o),this.emit("layoutStart",t,o),o.duration>0){const s=!this._hasUnprobedVideos();this.emit("layoutDurationUpdated",t,o.duration,s)}for(const[s,r]of this.regions)r.isDrawer||this.startRegion(s);this.startLayoutTimerWhenReady(t,o),this._scheduleNextLayoutPreload(o),this.log.info(`Layout ${t} started`)}catch(n){throw this.log.error("Error rendering layout:",n),this.emit("error",{type:"layoutError",error:n,layoutId:t}),n}}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,isCanvas:e.isCanvas||!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 a=setTimeout(()=>{this.log.warn(`Video ready timeout (10000ms) for widget ${t.id}`),r()},1e4),l=()=>{n.removeEventListener("playing",l),clearTimeout(a),this.log.info(`Video widget ${t.id} ready (playing)`),r()};n.addEventListener("playing",l)});const o=this.findMediaElement(e,"AUDIO");if(o)return!o.paused&&o.readyState>=3?Promise.resolve():new Promise(r=>{const a=setTimeout(()=>{this.log.warn(`Audio ready timeout (10000ms) for widget ${t.id}`),r()},1e4),l=()=>{o.removeEventListener("playing",l),clearTimeout(a),this.log.info(`Audio widget ${t.id} ready (playing)`),r()};o.addEventListener("playing",l)});const s=this.findMediaElement(e,"IMG");return s?s.complete&&s.naturalWidth>0?Promise.resolve():new Promise(r=>{const a=()=>{s.removeEventListener("load",a),clearTimeout(l),r()},l=setTimeout(()=>{s.removeEventListener("load",a),this.log.warn(`Image ready timeout for widget ${t.id}`),r()},1e4);s.addEventListener("load",a)}):Promise.resolve()}async startLayoutTimerWhenReady(e,t){if(!t||t.duration<=0)return;const i=[];for(const[n,o]of this.regions){if(o.widgets.length===0)continue;const s=o.widgets[o.currentIndex||0],r=o.widgetElements.get(s.id);r&&i.push(this.waitForWidgetReady(r,s))}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}if(t.isDynamic&&this._hasUnprobedVideos()){this._deferredTimerLayoutId=e,this._layoutTimerStartedAt=Date.now(),this.log.info(`Layout ${e} has unprobed videos — deferring timer until metadata loads`);return}this._startLayoutTimer(e,t)}_hasUnprobedVideos(){for(const[,e]of this.regions)for(const t of e.widgets)if(t.useDuration===0&&t.duration===0)return!0;return!1}_startLayoutTimer(e,t){this._deferredTimerLayoutId=null;const i=t.duration*1e3;this.log.info(`Layout ${e} will end after ${t.duration}s`),this._layoutTimerStartedAt=Date.now(),this._layoutTimerDurationMs=i,this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${e} duration expired (${t.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},i)}async _showWidget(e,t){var o,s;const i=e.widgets[t];if(!i)return null;let n=e.widgetElements.get(i.id);if(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)),!e.isCanvas)for(const[r,a]of e.widgetElements)r!==i.id&&((o=a.getAnimations)==null||o.call(a).forEach(l=>l.cancel()),a.style.visibility="hidden",a.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?ne.apply(n,i.transitions.in,!0,e.width,e.height):n.style.opacity="1",n._pdfResume&&n._pdfResume(),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)),n.src=i.uri?this._mediaFileUrl(i.uri):"",n.style.display="none",this.container.appendChild(n);const o=n.play();o&&o.catch&&o.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 a=ne.apply(n,i.transitions.out,!1,e.width,e.height);a&&(o=new Promise(l=>{a.onfinish=l}))}const s=n.querySelector("video");if(s&&i.options.loop!=="1"&&s.pause(),s!=null&&s._mediaStream&&(s._mediaStream.getTracks().forEach(a=>a.stop()),s._mediaStream=null,s.srcObject=null),s!=null&&s._hlsInstance&&(s._hlsInstance.destroy(),s._hlsInstance=null),s!=null&&s._eventCleanup){for(const[a,l]of s._eventCleanup)s.removeEventListener(a,l);s._eventCleanup=null}const r=n.querySelector("audio");if(r&&i.options.loop!=="1"&&r.pause(),r!=null&&r._eventCleanup){for(const[a,l]of r._eventCleanup)r.removeEventListener(a,l);r._eventCleanup=null}return this._stopAudioOverlays(i.id),n._pdfCleanup&&n._pdfCleanup(),{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=t.duration,n=e.match(/<!--\s*DURATION=(\d+)\s*-->/);if(n){const s=parseInt(n[1],10);if(s>0){this.log.info(`Widget ${t.id}: DURATION comment overrides duration ${t.duration}→${s}s`),t.duration=s,t.duration!==i&&this.updateLayoutDuration();return}}const o=e.match(/<!--\s*NUMITEMS=(\d+)\s*-->/);if(o){const s=parseInt(o[1],10);if(s>0&&t.duration>0){const r=s*t.duration;this.log.info(`Widget ${t.id}: NUMITEMS=${s} × ${t.duration}s = ${r}s`),t.duration=r}}t.duration!==i&&this.updateLayoutDuration()}_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,a)=>r.displayOrder-a.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)||{widgetIdx:0,playsDone:0};s=o[r.widgetIdx%o.length];const a=s.playCount||1;r.playsDone++,r.playsDone>=a&&(r.widgetIdx++,r.playsDone=0),this._subPlaylistCycleIndex.set(n,r)}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.isCanvas){this._startCanvasRegion(e,t,i,o);return}if(e.widgets.length===1){i(t,0);return}const s=()=>{const r=e.currentIndex,a=e.widgets[r];i(t,r);const l=a.duration*1e3;this.log.info(`Region ${t} widget ${a.id} (${a.type}) playing for ${a.duration}s (useDuration=${a.useDuration}, index ${r}/${e.widgets.length})`),e.timer=setTimeout(()=>{this._handleWidgetCycleEnd(a,e,t,r,i,n,o,s)},l)};s()}_startCanvasRegion(e,t,i,n){for(let s=0;s<e.widgets.length;s++)i(t,s);const o=Math.max(...e.widgets.map(s=>s.duration))*1e3;o>0?e.timer=setTimeout(()=>{e.complete||(e.complete=!0,n==null||n())},o):(e.complete=!0,n==null||n())}_handleWidgetCycleEnd(e,t,i,n,o,s,r,a){var d;e.webhookUrl&&this.emit("widgetAction",{type:"durationEnd",widgetId:e.id,layoutId:this.currentLayoutId,regionId:i,url:e.webhookUrl}),s(i,n);const l=(t.currentIndex+1)%t.widgets.length;if(l===0&&!t.complete&&(t.complete=!0,r==null||r()),l===0&&((d=t.config)==null?void 0:d.loop)===!1&&t.widgets.length===1){o(i,0);return}this.layoutEndEmitted||(t.currentIndex=l,a())}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._startedWidgets.add(`${e}:${t}`),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=`${e}:${t}`;if(!this._startedWidgets.delete(i))return;const n=this.regions.get(e);if(!n)return;const{widget:o,animPromise:s}=this._hideWidget(n,t);o&&this.emit("widgetEnd",{widgetId:o.id,regionId:e,layoutId:this.currentLayoutId,mediaId:parseInt(o.fileId||o.id)||null,type:o.type,enableStat:o.enableStat}),s&&await s}_stopAllRegionWidgets(e,t){for(const[i,n]of e)if(n.isCanvas)for(let o=0;o<n.widgets.length;o++)t(i,o);else n.widgets.length>0&&t(i,n.currentIndex)}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"},a=s[e.options.alignId]||"center",l=r[e.options.valignId]||"center";i.style.objectPosition=`${a} ${l}`,i.style.opacity="0";const d=e.options.uri?this._mediaFileUrl(e.options.uri):"";return 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;const s=e.options.uri||"",r=e.fileId||e.id,a=()=>{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`)};i.addEventListener("ended",a);let l=s?this._mediaFileUrl(s):"";if(l.includes(".m3u8"))if(i.canPlayType("application/vnd.apple.mpegurl"))this.log.info(`HLS stream (native): ${r}`),i.src=l;else try{const{default:p}=await F(async()=>{const{default:b}=await import("hls.js");return{default:b}},[],import.meta.url);if(p.isSupported()){const b=new p({enableWorker:!0,lowLatencyMode:!0});b.loadSource(l),b.attachMedia(i),i._hlsInstance=b,b.on(p.Events.ERROR,(_,C)=>{C.fatal&&(this.log.error(`HLS fatal error: ${C.type}`,C.details),b.destroy(),i._hlsInstance=null)}),this.log.info(`HLS stream (hls.js): ${r}`)}else this.log.warn(`HLS not supported on this browser for ${r}`),i.src=l}catch(p){this.log.warn(`hls.js not available, falling back to native: ${p.message}`),i.src=l}else i.src=l;const c=this.currentLayoutId,g=()=>{const p=i.duration;this.log.info(`Video ${s} duration detected: ${p}s`),(e.duration===0||e.useDuration===0)&&(e.duration=p,this.log.info(`Updated widget ${e.id} duration to ${p}s (useDuration=0)`),this.currentLayoutId===c?this.updateLayoutDuration():this.log.info(`Video ${s} duration set but layout timer not updated (preloaded for layout ${c}, current is ${this.currentLayoutId})`))};i.addEventListener("loadedmetadata",g);const h=()=>{this.log.info("Video loaded and ready:",s)};i.addEventListener("loadeddata",h);const w=()=>{const p=i.error,b=p==null?void 0:p.code,_=(p==null?void 0:p.message)||"Unknown error";this.log.warn(`Video error: ${s}, code: ${b}, time: ${i.currentTime.toFixed(1)}s, message: ${_}`),this.emit("videoError",{storedAs:s,fileId:r,errorCode:b,errorMessage:_,currentTime:i.currentTime})};i.addEventListener("error",w);const m=()=>{this.log.info("Video playing:",s)};return i.addEventListener("playing",m),i._eventCleanup=[["ended",a],["loadedmetadata",g],["loadeddata",h],["error",w],["playing",m]],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=e.options.uri||"";e.fileId||e.id,n.src=o?this._mediaFileUrl(o):"";const s=()=>{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`)};n.addEventListener("ended",s);const r=this.currentLayoutId,a=()=>{const h=Math.floor(n.duration);this.log.info(`Audio ${o} duration detected: ${h}s`),(e.duration===0||e.useDuration===0)&&(e.duration=h,this.log.info(`Updated widget ${e.id} duration to ${h}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("loadedmetadata",a);const l=()=>{const h=n.error;this.log.warn(`Audio error (non-fatal): ${o}, code: ${h==null?void 0:h.code}, message: ${(h==null?void 0:h.message)||"Unknown"}`)};n.addEventListener("error",l),n._eventCleanup=[["ended",s],["loadedmetadata",a],["error",l]];const d=document.createElement("div");d.innerHTML="♪",d.style.fontSize="120px",d.style.color="white",d.style.marginBottom="20px";const c=document.createElement("div");c.style.color="white",c.style.fontSize="24px",c.textContent="Playing Audio";const g=document.createElement("div");return g.style.color="rgba(255,255,255,0.7)",g.style.fontSize="16px",g.style.marginTop="10px",g.textContent=e.options.uri,i.appendChild(n),i.appendChild(d),i.appendChild(c),i.appendChild(g),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 a=this;i.addEventListener("load",function(){var l;try{if(!((l=i.contentDocument)!=null&&l.querySelector("base"))){a.log.warn("Cache URL failed (hard reload?), using original CMS URLs");const d=new Blob([r.fallback],{type:"text/html"}),c=URL.createObjectURL(d);a.trackBlobUrl(c),i.src=c}}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="transparent",i.style.opacity="0",i.style.position="relative",typeof window.pdfjsLib>"u")try{const o=await F(()=>import("./pdf-BnPRJEQ6.js"),[],import.meta.url);window.pdfjsLib=o;const s=window.location.pathname.replace(/\/[^/]*$/,"/");window.pdfjsLib.GlobalWorkerOptions.workerSrc=`${window.location.origin}${s}pdf.worker.min.mjs`}catch(o){return this.log.error("PDF.js not available:",o),i.innerHTML='<div style="color:white;padding:20px;text-align:center;">PDF viewer unavailable</div>',i.style.opacity="1",i}let n=e.options.uri?this._mediaFileUrl(e.options.uri):"";try{const s=await window.pdfjsLib.getDocument(n).promise,r=s.numPages,a=e.duration||60,l=a*1e3/r;this.log.info(`[pdf] PDF loaded: ${r} pages, ${a}s duration, ${(l/1e3).toFixed(1)}s/page`);const d=await s.getPage(1),c=d.getViewport({scale:1}),g=Math.min(t.width/c.width,t.height/c.height);d.cleanup();const h=document.createElement("canvas");h.className="pdf-page",h.width=Math.floor(c.width*g),h.height=Math.floor(c.height*g),h.style.cssText="display:block;margin:auto;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);";const w=h.getContext("2d");i.appendChild(h);const m=document.createElement("div");m.style.cssText="position:absolute;bottom:10px;right:10px;background:rgba(0,0,0,0.7);color:white;padding:8px 12px;border-radius:4px;font:14px system-ui;z-index:1;",Re()||(m.style.display="none"),i.appendChild(m);let p=1,b=null,_=null,C=!1;const R=async()=>{if(C)return;m.textContent=`Page ${p} / ${r}`;const T=await s.getPage(p),$=T.getViewport({scale:g});w.clearRect(0,0,h.width,h.height),_=T.render({canvasContext:w,viewport:$});try{await _.promise}catch(v){if(C)return;throw v}_=null,T.cleanup(),r>1&&!C&&(b=setTimeout(()=>{p=p>=r?1:p+1,R()},l))};await R();let x=null;i._pdfCleanup=()=>{if(C=!0,b&&clearTimeout(b),b=null,_){const T=_;_=null,T.cancel(),x=T.promise.catch(()=>{})}},i._pdfResume=async()=>{i._pdfCleanup(),x&&(await x,x=null),C=!1,p=1,R()},i._pdfDestroy=()=>{i._pdfCleanup(),h.width=0,h.height=0,s.destroy()}}catch(o){this.log.error("PDF render failed:",o),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");n.className="renderer-lite-widget",n.style.width="100%",n.style.height="100%",n.style.border="none",n.style.opacity="0";const o=decodeURIComponent(e.options.uri||"");return n.src=o,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 a=new Blob([o.fallback],{type:"text/html"}),l=URL.createObjectURL(a);s.trackBlobUrl(l),i.src=l}}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)}hasPreloadedLayout(e){return this.layoutPool.has(e)}async preloadLayout(e,t){var i;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 n=this.parseXlf(e);this.calculateScale(n);const o=document.createElement("div");if(o.id=`preload_layout_${t}`,o.className="renderer-lite-preload-wrapper",o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="100%",o.style.height="100%",o.style.visibility="hidden",o.style.zIndex="-1",o.style.backgroundColor=n.bgcolor,n.background){const g=((i=this.options.fileIdToSaveAs)==null?void 0:i.get(String(n.background)))||n.background;this._applyBackgroundImage(o,this._mediaFileUrl(g))}const s=this.currentLayoutId,r=new Map,a=this.scaleFactor;for(const g of n.regions){const h=document.createElement("div");h.id=`preload_region_${t}_${g.id}`,h.className="renderer-lite-region",h.style.position="absolute",h.style.zIndex=g.zindex,h.style.overflow="hidden",this.applyRegionScale(h,g),o.appendChild(h);const w={element:h,config:g,widgets:g.widgets,currentIndex:0,timer:null,width:g.width*a,height:g.height*a,complete:!1,widgetElements:new Map};r.set(g.id,w)}const l=new Set,d=this.layoutBlobUrls;this.layoutBlobUrls=new Map,this.layoutBlobUrls.set(t,l),this._preloadingLayoutId=t;for(const[g,h]of r)for(let w=0;w<h.widgets.length;w++){const m=h.widgets[w];m.layoutId=t,m.regionId=g;try{const p=await this.createWidgetElement(m,h);this._positionWidgetElement(p),h.element.appendChild(p),h.widgetElements.set(m.id,p)}catch(p){this.log.error(`Preload: Failed to create widget ${m.id}:`,p)}}return this.currentLayoutId=s,o.querySelectorAll("video").forEach(g=>g.pause()),(this.layoutBlobUrls.get(t)||new Set).forEach(g=>l.add(g)),this.layoutBlobUrls=d,this.container.appendChild(o),this.layoutPool.add(t,{container:o,layout:n,regions:r,blobUrls:l}),this.log.info(`Layout ${t} preloaded into pool (${r.size} regions)`),!0}catch(n){return this.log.error(`Preload failed for layout ${t}:`,n),!1}}async _swapToPreloadedLayout(e){var o;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,n=this.layoutEndEmitted;if(this.layoutEndEmitted=!1,i&&this.layoutPool.has(i))this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,(s,r)=>this.stopWidget(s,r)),this.layoutPool.evict(i);else{this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,(s,r)=>this.stopWidget(s,r));for(const[,s]of this.regions)if(ie.releaseMediaElements(s.element),(o=s.config)!=null&&o.exitTransition){const r=ne.apply(s.element,s.config.exitTransition,!1,s.width,s.height);if(r){const a=s.element;r.onfinish=()=>a.remove()}else s.element.remove()}else s.element.remove();i&&this.revokeBlobUrlsForLayout(i)}if(this.currentLayout=null,this.currentLayoutId=null,this.regions.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,i&&!n&&this.emit("layoutEnd",i),this.container.style.backgroundColor=t.layout.bgcolor,t.container.style.backgroundImage)for(const s of["backgroundImage","backgroundSize","backgroundPosition","backgroundRepeat"])this.container.style[s]=t.container.style[s];else this.container.style.backgroundImage="";this.calculateScale(t.layout),this.attachActionListeners(t.layout),this.emit("layoutStart",e,t.layout);for(const[s,r]of this.regions)r.currentIndex=0,r.complete=!1,this.startRegion(s);this.updateLayoutDuration(),this.startLayoutTimerWhenReady(e,t.layout),this.preloadTimer||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(){var i;if(!this.currentLayout)return;this.log.info(`Stopping layout ${this.currentLayoutId}`);const e=this.currentLayoutId,t=e&&!this.layoutEndEmitted;if(this.layoutEndEmitted=!1,this._deferredTimerLayoutId=null,this.currentLayout=null,this.currentLayoutId=null,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.removeActionListeners(),e&&this.layoutPool.has(e))this.layoutPool.evict(e);else{e&&this.revokeBlobUrlsForLayout(e),this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,(n,o)=>this.stopWidget(n,o));for(const[,n]of this.regions)if(ie.releaseMediaElements(n.element),(i=n.config)!=null&&i.exitTransition){const o=ne.apply(n.element,n.config.exitTransition,!1,n.width,n.height);if(o){const s=n.element;o.onfinish=()=>s.remove()}else n.element.remove()}else n.element.remove()}this.regions.clear(),t&&this.emit("layoutEnd",e)}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");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.calculateScale(n);const s=new Map,r=this.scaleFactor;for(const a of n.regions){const l=document.createElement("div");l.id=`overlay_${t}_region_${a.id}`,l.className="renderer-lite-region overlay-region",l.style.position="absolute",l.style.zIndex=String(a.zindex),l.style.overflow="hidden",this.applyRegionScale(l,a),o.appendChild(l),s.set(a.id,{element:l,config:a,widgets:a.widgets,currentIndex:0,timer:null,width:a.width*r,height:a.height*r,complete:!1,isCanvas:a.isCanvas||!1,widgetElements:new Map})}for(const[a,l]of s)for(const d of l.widgets){d.layoutId=t,d.regionId=a;try{const c=await this.createWidgetElement(d,l);this._positionWidgetElement(c),l.element.appendChild(c),l.widgetElements.set(d.id,c)}catch(c){this.log.error(`Failed to pre-create overlay widget ${d.id}:`,c)}}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[a,l]of s)this.startOverlayRegion(t,a);if(n.duration>0){const a=n.duration*1e3,l=this.activeOverlays.get(t);l&&(l.timer=setTimeout(()=>{this.log.info(`Overlay ${t} duration expired (${n.duration}s)`),this.emit("overlayEnd",t)},a))}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._startedWidgets.add(`overlay:${e}:${t}:${i}`),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=`overlay:${e}:${t}:${i}`;if(!this._startedWidgets.delete(n))return;const o=this.activeOverlays.get(e);if(!o)return;const s=o.regions.get(t);if(!s)return;const{widget:r,animPromise:a}=this._hideWidget(s,i);r&&this.emit("overlayWidgetEnd",{overlayId:e,widgetId:r.id,regionId:t,type:r.type}),a&&await a}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]of t.regions)i.timer&&(clearTimeout(i.timer),i.timer=null);this._stopAllRegionWidgets(t.regions,(i,n)=>this.stopOverlayWidget(e,i,n)),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(),this._startedWidgets.clear();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 V=U("Layout");class St{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"),a=o.getAttribute("bgcolor")||"#000000",l=[];for(const d of n.querySelectorAll("region"))l.push(await this.translateRegion(e,d));return this.generateHTML(s,r,a,l)}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")),a=parseInt(t.getAttribute("zindex")||"0"),l=[];for(const d of t.querySelectorAll("media"))l.push(await this.translateMedia(e,i,d));return{id:i,width:n,height:o,top:s,left:r,zindex:a,media:l}}async translateMedia(e,t,i){const n=i.getAttribute("type"),o=parseInt(i.getAttribute("duration")||"10"),s=i.getAttribute("id"),r=i.querySelector("options"),a=i.querySelector("raw"),l={};if(r)for(const C of r.children)l[C.tagName]=C.textContent;const d={in:null,out:null},c=i.querySelector("options > transIn"),g=i.querySelector("options > transOut"),h=i.querySelector("options > transInDuration"),w=i.querySelector("options > transOutDuration"),m=i.querySelector("options > transInDirection"),p=i.querySelector("options > transOutDirection");c&&c.textContent&&(d.in={type:c.textContent,duration:parseInt((h==null?void 0:h.textContent)||"1000"),direction:(m==null?void 0:m.textContent)||"N"}),g&&g.textContent&&(d.out={type:g.textContent,duration:parseInt((w==null?void 0:w.textContent)||"1000"),direction:(p==null?void 0:p.textContent)||"N"});let b=a?a.textContent:"";if(["clock","clock-digital","clock-analogue","calendar","weather","currencies","stocks","twitter","global","embedded","text","ticker"].some(C=>n.includes(C))){let C=3,R=null;for(let x=1;x<=C;x++)try{V.info(`Fetching resource for ${n} widget (layout=${e}, region=${t}, media=${s}) - attempt ${x}/${C}`),b=await this.xmds.getResource(e,t,s),V.info(`Got resource HTML (${b.length} chars)`);const T=await Ue(e,t,s,b);l.widgetCacheKey=T;break}catch(T){if(R=T,V.warn(`Failed to get resource (attempt ${x}/${C}):`,T.message),x<C){const $=x*2e3;V.info(`Retrying in ${$}ms...`),await new Promise(v=>setTimeout(v,$))}}if(!b&&R){V.warn("All retries failed, checking for cached widget HTML...");try{const x=await fetch(`/store${B}/widgets/${e}/${t}/${s}`);x.ok?(b=await x.text(),l.widgetCacheKey=`${B}/widgets/${e}/${t}/${s}`,V.info(`Using stored widget HTML (${b.length} chars) - CMS update pending`)):(V.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(x){V.error("Store fallback failed:",x),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:l,raw:b,transitions:d}}generateHTML(e,t,i,n){const o=n.map(r=>this.generateRegionHTML(r)).join(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-BpwloMHc.js","./chunk-config-C9U90T6u.js","./index-B57dvLVB.js","./index-dBd5BTjH.js","./widget-html-BSjCib6e.js","./index-GPOkOOlx.js","./protocol-detector-CpRVVofI.js","./index-D39gYDMZ.js","./modulepreload-polyfill-B5Qt9EMX.js","./index-B2dyKYhW.js","./index-D9_3Ns4E.js","./index-B_ADwXGQ.js","./index-CLgKYdBJ.js","./index-ClTQ0ldA.js","./sync-manager-C0UDCBzv.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Fe=Object.defineProperty;var We=(y,e,t)=>e in y?Fe(y,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):y[e]=t;var L=(y,e,t)=>We(y,typeof e!="symbol"?e+"":e,t);import"./modulepreload-polyfill-B5Qt9EMX.js";import{createLogger as U,PLAYER_API as B,isDebug as Re,EventEmitter as Oe,fetchWithRetry as Ne,applyCmsLogLevel as qe,config as Be,registerLogSink as he}from"./index-B57dvLVB.js";import{c as Ue,C as He,D as ze,L as ae,B as ge,S as je}from"./widget-html-BSjCib6e.js";const Ve="modulepreload",Ke=function(y,e){return new URL(y,e).href},fe={},F=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]"),a=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));n=Promise.allSettled(t.map(l=>{if(l=Ke(l,i),l in fe)return;fe[l]=!0;const d=l.endsWith(".css"),c=d?'[rel="stylesheet"]':"";if(!!i)for(let w=s.length-1;w>=0;w--){const m=s[w];if(m.href===l&&(!d||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${c}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":Ve,d||(h.as="script"),h.crossOrigin="",h.href=l,a&&h.setAttribute("nonce",a),document.head.appendChild(h),d)return new Promise((w,m)=>{h.addEventListener("load",w),h.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${l}`)))})}))}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 Xe=()=>({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)}}});const oe=U("schedule:criteria"),Ge=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],ye={weatherTemp:"temperature",weatherHumidity:"humidity",weatherWindSpeed:"windSpeed",weatherCondition:"condition",weatherCloudCover:"cloudCover"};function Je(y,e,t={},i={}){switch(y){case"dayOfWeek":return Ge[e.getDay()];case"dayOfMonth":return String(e.getDate());case"month":return String(e.getMonth()+1);case"hour":return String(e.getHours());case"isoDay":return String(e.getDay()===0?7:e.getDay());default:if(ye[y]){const n=ye[y];return i[n]!==void 0?String(i[n]):(oe.debug(`Weather metric "${y}" requested but no weather data available`),null)}return t[y]!==void 0?String(t[y]):(oe.debug(`Unknown metric: ${y}`),null)}}function Qe(y,e,t,i){if(y===null)return!1;if(i==="number"){const s=parseFloat(y),r=parseFloat(t);if(isNaN(s)||isNaN(r))return!1;switch(e){case"equals":return s===r;case"notEquals":return s!==r;case"greaterThan":return s>r;case"greaterThanOrEquals":return s>=r;case"lessThan":return s<r;case"lessThanOrEquals":return s<=r;default:return!1}}const n=y.toLowerCase(),o=t.toLowerCase();switch(e){case"equals":return n===o;case"notEquals":return n!==o;case"contains":return n.includes(o);case"notContains":return!n.includes(o);case"startsWith":return n.startsWith(o);case"endsWith":return n.endsWith(o);case"in":return o.split(",").map(s=>s.trim().toLowerCase()).includes(n);case"greaterThan":return n>o;case"lessThan":return n<o;default:return oe.debug(`Unknown condition: ${e}`),!1}}function ce(y,e={}){if(!y||y.length===0)return!0;const t=e.now||new Date,i=e.displayProperties||{},n=e.weatherData||{};for(const o of y){const s=Je(o.metric,t,i,n);if(!Qe(s,o.condition,o.value,o.type))return oe.debug(`Criteria failed: ${o.metric} ${o.condition} "${o.value}" (actual: "${s}")`),!1}return!0}function Pe(y,e=null){const i=new DOMParser().parseFromString(y,"text/xml").querySelector("layout");if(!i)return{duration:60,isDynamic:!1};const n=parseInt(i.getAttribute("duration")||"0",10);if(n>0)return{duration:n,isDynamic:!1};let o=0,s=!1;for(const a of i.querySelectorAll("region")){const l=a.getAttribute("type");if(l==="drawer")continue;const d=l==="canvas";let c=0;for(const g of a.querySelectorAll("media")){const h=parseInt(g.getAttribute("duration")||"0",10),w=parseInt(g.getAttribute("useDuration")||"1",10),m=g.getAttribute("fileId")||"",p=e==null?void 0:e.get(m);let b;p!==void 0?b=p:h>0&&w!==0?b=h:(b=60,s=!0),d?c=Math.max(c,b):c+=b}o=Math.max(o,c)}return{duration:o>0?o:60,isDynamic:s}}function Ye(y,e){if(y.length!==e.length)return!1;for(let t=0;t<y.length;t++)if(y[t]!==e[t])return!1;return!0}function Ze(y,e,t){if(!e||e===0)return!0;const i=t-36e5,n=y.filter(o=>o>i);if(n.length>=e)return!1;if(n.length>0){const o=36e5/e,s=Math.max(...n);if(t-s<o)return!1}return!0}function pe(y,e,t){const i=y.filter(o=>{if(!o.maxPlaysPerHour||o.maxPlaysPerHour===0)return!0;const s=e.get(o.file)||[];return Ze(s,o.maxPlaysPerHour,t)});if(i.length===0)return[];const n=Math.max(...i.map(o=>o.priority));return i.filter(o=>o.priority===n).map(o=>o.file)}function et(y,e,t={}){const i=t.from||new Date,n=t.hours||2,o=new Date(i.getTime()+n*36e5);t.currentLayoutStartedAt;const s=t.defaultLayout||null,r=t.durations||null;if(!y||y.length===0)return[];const a=[];let l=new Date(i),d=e%y.length;const c=500;for(;l<o&&a.length<c;){const g=y[d];let h=r&&r.get(g.layoutId)||g.duration;const w=l.getTime()+h*1e3;a.push({layoutFile:g.layoutId,startTime:new Date(l),endTime:new Date(w),duration:h,isDefault:s?g.layoutId===s:!1}),l=new Date(w),d=(d+1)%y.length}return a}function tt(y,e){for(y=Math.abs(Math.round(y)),e=Math.abs(Math.round(e));e;)[y,e]=[e,y%e];return y}function it(y,e){return y===0||e===0?0:Math.abs(Math.round(y)*Math.round(e))/tt(y,e)}function nt(y){return y.reduce((e,t)=>it(e,t),1)}function ot(y,e,t={}){const{defaultLayout:i=null,defaultDuration:n=60}=t;if(y.length===0&&!i)return{queue:[],periodSeconds:0};const o=new Map;for(const w of y)w.duration>0&&o.set(w.file,w.duration);const s=w=>e.get(w)||o.get(w)||n,r=y.filter(w=>w.maxPlaysPerHour>0);let a;if(r.length>0){const w=r.map(m=>Math.round(3600/m.maxPlaysPerHour));a=nt(w),a>7200&&(a=7200)}else a=y.reduce((m,p)=>m+s(p.file),0)+(i&&!y.some(m=>m.file===i)?s(i):0)||n;const l=[],d=new Map;let c=0;const g=a*1e3,h=500;for(;c<g&&l.length<h;){const w=pe(y,d,c);if(w.length===0){if(i){const m=s(i);l.push({layoutId:i,duration:m}),c+=m*1e3}else c+=6e4;continue}for(let m=0;m<w.length&&c<g&&l.length<h;m++){const p=w[m],b=s(p);l.push({layoutId:p,duration:b}),d.has(p)||d.set(p,[]),d.get(p).push(c),c+=b*1e3;const _=pe(y,d,c);if(!Ye(w,_))break}}if(l.length===0&&i){const w=s(i);l.push({layoutId:i,duration:w})}return{queue:l,periodSeconds:a}}const q=U("Schedule");class st{constructor(e={}){this.schedule=null,this.playHistory=new Map,this.interruptScheduler=e.interruptScheduler||null,this.displayProperties=e.displayProperties||{},this.weatherData={},this.playerLocation=null,this._layoutMetadata=new Map,this._scheduleQueue=null,this._queuePosition=0,this._queueLayoutSet=null}setSchedule(e){this.schedule=e,this._invalidateQueue()}setWeatherData(e){this.weatherData=e||{}}getDataConnectors(){var e;return((e=this.schedule)==null?void 0:e.dataConnectors)||[]}getDependantsMap(){const e=new Map;if(!this.schedule)return e;const t=this.schedule.dependants||[],i=n=>{const o=parseInt(String(n.file||n.id).replace(".xlf",""),10),s=[...t,...n.dependants||[]];s.length>0&&e.set(o,s)};if(this.schedule.layouts)for(const n of this.schedule.layouts)i(n);if(this.schedule.campaigns)for(const n of this.schedule.campaigns)for(const o of n.layouts)i(o);return e}isRecurringScheduleActive(e,t){if(!e.recurrenceType)return!0;if(e.recurrenceRange){const i=new Date(e.recurrenceRange);if(t>i)return!1}switch(e.recurrenceType){case"Week":{if(e.recurrenceRepeatsOn){const i=this.getIsoDayOfWeek(t);if(!e.recurrenceRepeatsOn.split(",").map(o=>parseInt(o.trim())).includes(i))return!1}return!0}case"Day":{const i=e.recurrenceDetail||1;if(i>1&&e.fromdt){const n=new Date(e.fromdt),o=t.getTime()-n.getTime(),s=Math.floor(o/864e5);if(s<0||s%i!==0)return!1}return!0}case"Month":{if(e.recurrenceRepeatsOn){const n=e.recurrenceRepeatsOn.split(",").map(s=>parseInt(s.trim())),o=t.getDate();if(!n.includes(o))return!1}const i=e.recurrenceDetail||1;if(i>1&&e.fromdt){const n=new Date(e.fromdt),o=(t.getFullYear()-n.getFullYear())*12+t.getMonth()-n.getMonth();if(o<0||o%i!==0)return!1}return!0}default:return q.debug(`Unsupported recurrence type: ${e.recurrenceType}`),!0}}getIsoDayOfWeek(e){const t=e.getDay();return t===0?7:t}isTimeActive(e,t){const i=e.fromdt?new Date(e.fromdt):null,n=e.todt?new Date(e.todt):null;if(e.recurrenceType==="Week"||e.recurrenceType==="Day"||e.recurrenceType==="Month"){if(i&&n){const o=t.getHours()*3600+t.getMinutes()*60+t.getSeconds(),s=i.getHours()*3600+i.getMinutes()*60+i.getSeconds(),r=n.getHours()*3600+n.getMinutes()*60+n.getSeconds();return s<=r?o>=s&&o<=r:o>=s||o<=r}return!0}return!(i&&t<i||n&&t>n)}getCurrentLayouts(){return this._getLayoutsAt(new Date)}getLayoutsAtTime(e){return this._getLayoutsAt(e,{skipRateLimiting:!0,skipInterrupts:!0,quiet:!0})}getAllLayoutsAtTime(e){if(!this.schedule)return[];const t=e,i=[];if(this.schedule.layouts)for(const n of this.schedule.layouts)this.isRecurringScheduleActive(n,t)&&this.isTimeActive(n,t)&&(n.criteria&&n.criteria.length>0&&!ce(n.criteria,{now:t,displayProperties:this.displayProperties,weatherData:this.weatherData})||n.isGeoAware&&n.geoLocation&&!this.isWithinGeoFence(n.geoLocation)||i.push({file:n.file,priority:n.priority||0,maxPlaysPerHour:n.maxPlaysPerHour||0,duration:n.duration||0}));if(this.schedule.campaigns){for(const n of this.schedule.campaigns)if(this.isRecurringScheduleActive(n,t)&&this.isTimeActive(n,t))for(const o of n.layouts)i.push({file:o.file,priority:n.priority||0,maxPlaysPerHour:o.maxPlaysPerHour||0,duration:o.duration||0})}return i}detectConflicts(e={}){const t=e.from||new Date,i=e.hours||24,n=new Date(t.getTime()+i*36e5),o=6e4,s=[];let r=null;for(let a=t.getTime();a<n.getTime();a+=o){const l=new Date(a),d=this.getAllLayoutsAtTime(l);if(d.length===0){r&&(s.push(r),r=null);continue}const c=Math.max(...d.map(p=>p.priority)),g=d.filter(p=>p.priority<c);if(g.length===0){r&&(s.push(r),r=null);continue}const h=d.filter(p=>p.priority===c),w=h.map(p=>p.file).sort().join(","),m=g.map(p=>`${p.file}:${p.priority}`).sort().join(",");r&&r._winnerKey===w&&r._hiddenKey===m?r.endTime=new Date(a+o):(r&&s.push(r),r={startTime:new Date(a),endTime:new Date(a+o),winner:{file:h[0].file,priority:c},hidden:g.map(p=>({file:p.file,priority:p.priority})),_winnerKey:w,_hiddenKey:m})}r&&s.push(r);for(const a of s)delete a._winnerKey,delete a._hiddenKey;return s}_getLayoutsAt(e,t={}){if(!this.schedule)return[];const{skipRateLimiting:i=!1,skipInterrupts:n=!1,quiet:o=!1}=t,s=o?()=>{}:(...c)=>q.info(...c),r=[];if(this._maxActivePriority=0,this.schedule.campaigns)for(const c of this.schedule.campaigns)this.isRecurringScheduleActive(c,e)&&this.isTimeActive(c,e)&&(this._maxActivePriority=Math.max(this._maxActivePriority,c.priority||0),r.push({type:"campaign",priority:c.priority,layouts:c.layouts,campaignId:c.id}));if(this.schedule.layouts){for(const c of this.schedule.layouts)if(this.isRecurringScheduleActive(c,e)&&this.isTimeActive(c,e)){if(c.criteria&&c.criteria.length>0&&!ce(c.criteria,{now:e,displayProperties:this.displayProperties,weatherData:this.weatherData})){s("[Schedule] Layout",c.id,"filtered by criteria");continue}if(c.isGeoAware&&c.geoLocation&&!this.isWithinGeoFence(c.geoLocation)){s("[Schedule] Layout",c.id,"filtered by geofence");continue}if(this._maxActivePriority=Math.max(this._maxActivePriority,c.priority||0),!i&&!this.canPlayLayout(c.id,c.maxPlaysPerHour)){s("[Schedule] Layout",c.id,"filtered by maxPlaysPerHour (limit:",c.maxPlaysPerHour,")");continue}r.push({type:"layout",priority:c.priority||0,layouts:[c],layoutId:c.id})}}if(r.length===0)return this.schedule.default?[this.schedule.default]:[];let a=Math.max(...r.map(c=>c.priority));s("[Schedule] Max priority:",a,"from",r.length,"active items");let l=[];for(const c of r)c.priority===a?(s("[Schedule] Including priority",c.priority,"layouts:",c.layouts.map(g=>g.file)),l.push(...c.layouts)):s("[Schedule] Skipping priority",c.priority,"< max",a);this._layoutMetadata.clear();for(const c of l)this._layoutMetadata.set(c.file,{syncEvent:c.syncEvent||!1,shareOfVoice:c.shareOfVoice||0,scheduleid:c.scheduleid,priority:c.priority||0});if(!n&&this.interruptScheduler){const{normalLayouts:c,interruptLayouts:g}=this.interruptScheduler.separateLayouts(l);if(g.length>0){s("[Schedule] Found",g.length,"interrupt layouts with shareOfVoice");const w=this.interruptScheduler.processInterrupts(c,g).map(m=>m.file);return s("[Schedule] Final layouts (with interrupts):",w),w}}const d=l.map(c=>c.file);return s("[Schedule] Final layouts:",d),d}shouldCheckSchedule(e){return e?Date.now()-e>=6e4:!0}canPlayLayout(e,t){if(!t||t===0)return!0;const i=Date.now(),n=i-60*60*1e3,s=(this.playHistory.get(e)||[]).filter(r=>r>n);if(s.length>=t)return q.info(`Layout ${e} has reached max plays per hour (${s.length}/${t})`),!1;if(s.length>0){const r=36e5/t,a=Math.max(...s),l=i-a;if(l<r){const d=((r-l)/6e4).toFixed(1);return q.info(`Layout ${e} spacing: next play in ${d} min (${s.length}/${t} plays, ${Math.round(r/6e4)} min gap)`),!1}}return!0}recordPlay(e){this.playHistory.has(e)||this.playHistory.set(e,[]);const t=this.playHistory.get(e);t.push(Date.now());const i=Date.now()-60*60*1e3,n=t.filter(o=>o>i);this.playHistory.set(e,n),q.info(`Recorded play for layout ${e} (${n.length} plays in last hour)`)}getMaxActivePriority(){return this._maxActivePriority||0}isSyncEvent(e){const t=this._layoutMetadata.get(e);return(t==null?void 0:t.syncEvent)===!0}getLayoutMetadata(e){return this._layoutMetadata.get(e)||null}getScheduleQueue(e,t={}){var r;const i=this.getAllLayoutsAtTime(new Date),n=i.map(a=>`${a.file}:${a.priority}:${a.maxPlaysPerHour}`).sort().join("|");if(this._scheduleQueue&&this._queueLayoutSet===n)return this._scheduleQueue;const o=ot(i,e,{defaultLayout:((r=this.schedule)==null?void 0:r.default)||null,defaultDuration:60,dynamicLayouts:t.dynamicLayouts||new Set}),s=this._queueLayoutSet;return this._scheduleQueue=o,this._queueLayoutSet=n,s!==n&&(this._queuePosition=0),o.queue.length>0&&(q.info(`[Schedule] Built queue: ${o.queue.length} entries, period ${o.periodSeconds}s (pos ${this._queuePosition})`),q.info(`[Schedule] Queue: ${o.queue.map(a=>`${a.layoutId}(${a.duration}s)`).join(" → ")}`)),o}popNextFromQueue(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);if(i.length===0)return null;const n=i[this._queuePosition%i.length];return this._queuePosition=(this._queuePosition+1)%i.length,n}peekNextInQueue(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);return i.length===0?null:i[this._queuePosition%i.length]}peekAfterNext(e,t={}){const{queue:i}=this.getScheduleQueue(e,t);return i.length<=1?null:i[(this._queuePosition+1)%i.length]}_invalidateQueue(){this._scheduleQueue=null}hasSyncEvents(){for(const e of this._layoutMetadata.values())if(e.syncEvent)return!0;return!1}getActiveActions(){var t;if(!((t=this.schedule)!=null&&t.actions))return[];const e=new Date;return this.schedule.actions.filter(i=>this.isTimeActive(i,e))}getCommands(){var e;return((e=this.schedule)==null?void 0:e.commands)||[]}findActionByTrigger(e){return this.getActiveActions().find(i=>i.triggerCode===e)||null}clearPlayHistory(){this.playHistory.clear(),q.info("Play history cleared")}setLocation(e,t){this.playerLocation={latitude:e,longitude:t},q.info(`Location set: ${e}, ${t}`)}setDisplayProperties(e){this.displayProperties=e||{}}isWithinGeoFence(e,t=500){if(!this.playerLocation)return q.debug("No player location, skipping geofence check"),!0;if(!e)return!0;const i=e.split(",").map(l=>parseFloat(l.trim()));if(i.length<2||isNaN(i[0])||isNaN(i[1]))return q.warn("Invalid geoLocation format:",e),!0;const n=i[0],o=i[1],s=i[2]||t,r=this.haversineDistance(this.playerLocation.latitude,this.playerLocation.longitude,n,o),a=r<=s;return q.info(`Geofence: ${r.toFixed(0)}m from (${n},${o}), radius ${s}m → ${a?"WITHIN":"OUTSIDE"}`),a}haversineDistance(e,t,i,n){const s=d=>d*Math.PI/180,r=s(i-e),a=s(n-t),l=Math.sin(r/2)**2+Math.cos(s(e))*Math.cos(s(i))*Math.sin(a/2)**2;return 6371e3*2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))}}const vt=new st,H=U("schedule:interrupts");class bt{constructor(){this.interruptCommittedDurations=new Map}isInterrupt(e){return!!(e.shareOfVoice&&e.shareOfVoice>0)}resetCommittedDurations(){this.interruptCommittedDurations.clear(),H.debug("Reset interrupt committed durations")}getCommittedDuration(e){return this.interruptCommittedDurations.get(e)||0}addCommittedDuration(e,t){const i=this.getCommittedDuration(e);this.interruptCommittedDurations.set(e,i+t)}isInterruptDurationSatisfied(e){if(!e.shareOfVoice)return!0;const t=e.id||e.file,i=e.shareOfVoice/100*3600;return this.getCommittedDuration(t)>=i}getRequiredSeconds(e){return e.shareOfVoice?e.shareOfVoice/100*3600:0}processInterrupts(e,t){if(!t||t.length===0)return H.debug("No interrupt layouts, returning normal layouts"),e;if(!e||e.length===0)return H.warn("No normal layouts available, interrupts will fill entire hour"),this.fillHourWithInterrupts(t);H.info(`Processing ${t.length} interrupt layouts with ${e.length} normal layouts`);for(const d of t){const c=d.id||d.file;this.interruptCommittedDurations.set(c,0)}const i=[];let n=0,o=0,s=!1;for(;!s;){if(o>=t.length){o=0;let c=!0;for(const g of t)if(!this.isInterruptDurationSatisfied(g)){c=!1;break}if(c){s=!0;break}}const d=t[o];if(!this.isInterruptDurationSatisfied(d)){const c=d.id||d.file;this.addCommittedDuration(c,d.duration),n+=d.duration,i.push(d)}o++}if(H.debug(`Resolved ${i.length} interrupt plays (${n}s total)`),n>=3600)return H.info("Interrupts fill entire hour (>= 3600s), no room for normal layouts"),i;const r=3600-n,a=this.fillTimeWithLayouts(e,r);H.debug(`Resolved ${a.length} normal plays (${r}s target)`);const l=this.interleaveLayouts(a,i);return H.info(`Final loop: ${l.length} layouts (${a.length} normal + ${i.length} interrupts)`),l}fillTimeWithLayouts(e,t){const i=[];let n=t,o=0;for(;n>0;){o>=e.length&&(o=0);const s=e[o];i.push(s),n-=s.duration,o++}return i}fillHourWithInterrupts(e){return this.fillTimeWithLayouts(e,3600)}interleaveLayouts(e,t){const i=[],n=Math.max(e.length,t.length),o=Math.ceil(1*n/e.length),s=Math.floor(1*n/t.length);H.debug(`Interleaving: pickCount=${n}, normalPick=${o}, interruptPick=${s}`);let r=0,a=0,l=0;for(let d=0;d<n;d++)d%o===0&&(r>=e.length&&(r=0),i.push(e[r]),l+=e[r].duration,r++),d%s===0&&a<t.length&&(i.push(t[a]),l+=t[a].duration,a++);for(;l<3600;)r>=e.length&&(r=0),i.push(e[r]),l+=e[r].duration,r++;return H.debug(`Interleaved ${i.length} layouts, total duration: ${l}s`),i}separateLayouts(e){const t=[],i=[];for(const n of e)this.isInterrupt(n)?i.push(n):t.push(n);return{normalLayouts:t,interruptLayouts:i}}}const Q=U("schedule:overlays");class rt{constructor(){this.overlays=[],this.displayProperties={},this.scheduleManager=null,Q.debug("OverlayScheduler initialized")}setScheduleManager(e){this.scheduleManager=e}setDisplayProperties(e){this.displayProperties=e||{}}setOverlays(e){this.overlays=e||[],Q.info(`Loaded ${this.overlays.length} overlay(s)`)}getCurrentOverlays(){if(!this.overlays||this.overlays.length===0)return[];const e=new Date,t=[];for(const i of this.overlays){if(!this.isTimeActive(i,e)){Q.debug(`Overlay ${i.file} not in time window`);continue}if(i.isGeoAware&&i.geoLocation&&this.scheduleManager&&!this.scheduleManager.isWithinGeoFence(i.geoLocation)){Q.debug(`Overlay ${i.file} filtered by geofence`);continue}if(i.criteria&&i.criteria.length>0&&!ce(i.criteria,{now:e,displayProperties:this.displayProperties})){Q.debug(`Overlay ${i.file} filtered by criteria`);continue}t.push(i)}return t.sort((i,n)=>{const o=i.priority||0;return(n.priority||0)-o}),t.length>0&&Q.info(`Active overlays: ${t.length}`),t}isTimeActive(e,t){const i=e.fromdt||e.fromDt?new Date(e.fromdt||e.fromDt):null,n=e.todt||e.toDt?new Date(e.todt||e.toDt):null;return!(i&&t<i||n&&t>n)}shouldCheckOverlays(e){return e?Date.now()-e>=6e4:!0}getOverlayByFile(e){return this.overlays.find(t=>t.file===e)||null}clear(){this.overlays=[],Q.debug("Cleared all overlays")}processOverlays(e,t){return this.setOverlays(t),e}}new rt;const Y=U("LayoutPool");class ie{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),Y.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(Y.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&&ie.releaseMediaElements(t.container),t.blobUrls&&t.blobUrls.size>0&&(t.blobUrls.forEach(i=>{URL.revokeObjectURL(i)}),Y.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()}),e.querySelectorAll(".pdf-widget").forEach(n=>{n._pdfDestroy&&n._pdfDestroy()}),t>0&&Y.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&&Y.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&&Y.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 ne={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":return t?this.fadeIn(y,s):this.fadeOut(y,s);case"fadein":return t?this.fadeIn(y,s):null;case"fadeout":return t?null:this.fadeOut(y,s);case"fly":return t?this.flyIn(y,s,r,i,n):this.flyOut(y,s,r,i,n);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 at{constructor(e,t,i={}){this.config=e,this.container=t,this.options=i,this.log=U("RendererLite",i.logLevel),this.emitter=Xe(),this.currentLayout=null,this.currentLayoutId=null,this._preloadingLayoutId=null,this.regions=new Map,this.layoutTimer=null,this.layoutEndEmitted=!1,this._deferredTimerLayoutId=null,this._paused=!1,this._layoutTimerStartedAt=null,this._layoutTimerDurationMs=null,this.widgetTimers=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._startedWidgets=new Set,this.layoutPool=new ie(2),this.preloadTimer=null,this._preloadRetryTimer=null,this.setupContainer(),this.emitter.on("interactiveTrigger",n=>this._handleInteractiveTrigger(n)),this.emitter.on("widgetExpire",n=>this._handleWidgetExpire(n)),this.emitter.on("widgetExtendDuration",n=>this._handleWidgetExtendDuration(n)),this.emitter.on("widgetSetDuration",n=>this._handleWidgetSetDuration(n)),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",this._resizeSuppressed=!1,typeof ResizeObserver<"u"){let e=null;this.resizeObserver=new ResizeObserver(()=>{this._resizeSuppressed||(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 a of r){const l=a.tagName==="drawer",d=a.getAttribute("type")||null,c={id:a.getAttribute("id"),width:parseInt(a.getAttribute("width")||"0"),height:parseInt(a.getAttribute("height")||"0"),top:parseInt(a.getAttribute("top")||"0"),left:parseInt(a.getAttribute("left")||"0"),zindex:parseInt(a.getAttribute("zindex")||(l?"2000":"0")),enableStat:a.getAttribute("enableStat")!=="0",actions:this.parseActions(a),exitTransition:null,transitionType:null,transitionDuration:null,transitionDirection:null,loop:!0,isDrawer:l,isCanvas:d==="canvas",widgets:[]},g=Array.from(a.children).find(h=>h.tagName==="options");if(g){const h=g.querySelector("exitTransType");if(h&&h.textContent){const p=g.querySelector("exitTransDuration"),b=g.querySelector("exitTransDirection");c.exitTransition={type:h.textContent,duration:parseInt(p&&p.textContent||"1000"),direction:b&&b.textContent||"N"}}const w=g.querySelector("loop");w&&(c.loop=w.textContent!=="0");const m=g.querySelector("transitionType");if(m&&m.textContent){c.transitionType=m.textContent;const p=g.querySelector("transitionDuration"),b=g.querySelector("transitionDirection");c.transitionDuration=parseInt(p&&p.textContent||"1000"),c.transitionDirection=b&&b.textContent||"N"}}for(const h of a.children){if(h.tagName!=="media")continue;const w=this.parseWidget(h);c.widgets.push(w)}!c.isCanvas&&c.widgets.some(h=>h.type==="global")&&(c.isCanvas=!0),s.regions.push(c),l&&this.log.info(`Parsed drawer: id=${c.id} with ${c.widgets.length} widgets`),c.isCanvas&&this.log.info(`Parsed canvas region: id=${c.id} with ${c.widgets.length} widgets (all render simultaneously)`)}if(s.duration===0){const{duration:a,isDynamic:l}=Pe(e);s.duration=a,s.isDynamic=l,this.log.info(`Calculated layout duration: ${s.duration}s (not specified in XLF)${l?" [dynamic — has useDuration=0 video]":""}`)}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={},a=e.querySelector("options");if(a)for(const v of a.children)r[v.tagName]=v.textContent;const l=e.querySelector("raw"),d=l?l.textContent:"",c={in:null,out:null};r.transIn&&(c.in={type:r.transIn,duration:parseInt(r.transInDuration||"1000"),direction:r.transInDirection||"N"}),r.transOut&&(c.out={type:r.transOut,duration:parseInt(r.transOutDuration||"1000"),direction:r.transOutDirection||"N"});const g=this.parseActions(e),h=[];for(const v of e.children)if(v.tagName.toLowerCase()==="audio"){const S=v.querySelector("uri");S?h.push({mediaId:S.getAttribute("mediaId")||null,uri:S.textContent||"",volume:parseInt(S.getAttribute("volume")||"100"),loop:S.getAttribute("loop")==="1"}):h.push({mediaId:v.getAttribute("mediaId")||null,uri:v.getAttribute("uri")||"",volume:parseInt(v.getAttribute("volume")||"100"),loop:v.getAttribute("loop")==="1"})}const w=[],m=Array.from(e.children).find(v=>v.tagName==="commands");if(m)for(const v of m.children)v.tagName==="command"&&w.push({commandCode:v.getAttribute("commandCode")||"",commandString:v.getAttribute("commandString")||""});const p=e.getAttribute("parentWidgetId")||null,b=parseInt(e.getAttribute("displayOrder")||"0"),_=e.getAttribute("cyclePlayback")==="1",C=parseInt(e.getAttribute("playCount")||"0"),O=e.getAttribute("isRandom")==="1",x=e.getAttribute("fromDt")||e.getAttribute("fromdt")||null,T=e.getAttribute("toDt")||e.getAttribute("todt")||null,$=e.getAttribute("render")||null;return{type:t,duration:i,useDuration:n,id:o,fileId:s,render:$,fromDt:x,toDt:T,enableStat:e.getAttribute("enableStat")!=="0",webhookUrl:r.webhookUrl||null,options:r,raw:d,transitions:c,actions:g,audioNodes:h,commands:w,parentWidgetId:p,displayOrder:b,cyclePlayback:_,playCount:C,isRandom:O}}trackBlobUrl(e){const t=this._preloadingLayoutId||this.currentLayoutId||0;t||this.log.warn("trackBlobUrl called without currentLayoutId, tracking under key 0"),this.layoutBlobUrls.has(t)||this.layoutBlobUrls.set(t,new Set),this.layoutBlobUrls.get(t).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;this.currentLayout.duration=e,this.log.info(`Layout duration updated: ${t}s → ${e}s (based on video metadata)`);const i=!this._hasUnprobedVideos();if(this.emit("layoutDurationUpdated",this.currentLayoutId,e,i),this._deferredTimerLayoutId===this.currentLayoutId&&!this.layoutTimer)if(this._hasUnprobedVideos())this.log.info(`Layout duration updated to ${e}s but still has unprobed videos — keeping timer deferred`);else{const n=Date.now()-(this._layoutTimerStartedAt||Date.now()),o=Math.max(1e3,e*1e3-n);this._deferredTimerLayoutId=null,this._layoutTimerDurationMs=o,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))},o),this.log.info(`All video durations resolved — deferred timer started: ${(o/1e3).toFixed(1)}s remaining (waited ${(n/1e3).toFixed(1)}s for metadata)`)}else if(this.layoutTimer){clearTimeout(this.layoutTimer);const n=Date.now()-(this._layoutTimerStartedAt||Date.now()),o=Math.max(1e3,this.currentLayout.duration*1e3-n);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))},o),this.log.info(`Layout timer adjusted to ${(o/1e3).toFixed(1)}s remaining (elapsed ${(n/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 a=s.widgetElements.get(r.id);if(a)for(const l of r.actions)l.triggerType==="touch"?(this.attachTouchAction(a,l,o.id,r.id),i++):l.triggerType.startsWith("keyboard:")&&t.push(l)}}}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=""}}_findRegionByWidgetId(e){for(const[t,i]of this.regions){const n=i.widgets.findIndex(o=>o.id===e);if(n!==-1)return{regionId:t,region:i,widget:i.widgets[n],widgetIndex:n,regionMap:this.regions}}for(const t of this.activeOverlays.values())if(t.regions)for(const[i,n]of t.regions){const o=n.widgets.findIndex(s=>s.id===e);if(o!==-1)return{regionId:i,region:n,widget:n.widgets[o],widgetIndex:o,regionMap:t.regions}}return null}_advanceRegion(e,t){const i=t.get(e);if(!i)return;i.currentIndex=(i.currentIndex+1)%i.widgets.length;const n=t===this.regions;this._startRegionCycle(i,e,n?(o,s)=>this.renderWidget(o,s):(o,s)=>this.renderWidget(o,s),n?(o,s)=>this.stopWidget(o,s):(o,s)=>this.stopWidget(o,s),n?()=>this.checkLayoutComplete():void 0)}_handleInteractiveTrigger({targetId:e,triggerCode:t}){this.log.info(`XIC interactiveTrigger: target=${e} code=${t}`),this._findRegionByWidgetId(e)?this.navigateToWidget(e):this.log.warn(`XIC interactiveTrigger: widget ${e} not found`)}_handleWidgetExpire({widgetId:e}){const t=this._findRegionByWidgetId(e);if(!t){this.log.warn(`XIC widgetExpire: widget ${e} not found`);return}const{regionId:i,region:n,widgetIndex:o,regionMap:s}=t;this.log.info(`XIC widgetExpire: widget=${e} region=${i}`),n.timer&&(clearTimeout(n.timer),n.timer=null),this.stopWidget(i,o),this._advanceRegion(i,s)}_handleWidgetExtendDuration({widgetId:e,duration:t}){const i=this._findRegionByWidgetId(e);if(!i){this.log.warn(`XIC widgetExtendDuration: widget ${e} not found`);return}const{regionId:n,region:o}=i;this.log.info(`XIC widgetExtendDuration: widget=${e} +${t}s`),o.timer&&(clearTimeout(o.timer),o.timer=null),o.timer=setTimeout(()=>{this.stopWidget(n,o.currentIndex),this._advanceRegion(n,i.regionMap)},t*1e3)}_handleWidgetSetDuration({widgetId:e,duration:t}){const i=this._findRegionByWidgetId(e);if(!i){this.log.warn(`XIC widgetSetDuration: widget ${e} not found`);return}const{regionId:n,region:o}=i;this.log.info(`XIC widgetSetDuration: widget=${e} ${t}s`),o.timer&&(clearTimeout(o.timer),o.timer=null),o.timer=setTimeout(()=>{this.stopWidget(n,o.currentIndex),this._advanceRegion(n,i.regionMap)},t*1e3)}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)`)):i.isDrawer?this.navigateToWidget(i.widgets[r].id):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)}_mediaFileUrl(e){return`${window.location.origin}${B}/media/file/${e}`}_positionWidgetElement(e){Object.assign(e.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",visibility:"hidden",opacity:"0"})}_applyBackgroundImage(e,t){Object.assign(e.style,{backgroundImage:`url(${t})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"})}_clearRegionTimers(e){for(const[,t]of e)t.timer&&(clearTimeout(t.timer),t.timer=null)}async renderLayout(e,t){var i;try{if(this.log.info(`Rendering layout ${t}`),this.currentLayoutId===t){this.log.info(`Replaying layout ${t} - reusing elements (no recreation!)`),this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,(s,r)=>this.stopWidget(s,r));for(const[,s]of this.regions)s.currentIndex=0,s.complete=!1;this.layoutTimer&&(clearTimeout(this.layoutTimer),this.layoutTimer=null),this._deferredTimerLayoutId=null,this.layoutEndEmitted=!1,this.emit("layoutStart",t,this.currentLayout);for(const[s,r]of this.regions)r.isDrawer||this.startRegion(s);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 o=this.parseXlf(e);if(this.currentLayout=o,this.currentLayoutId=t,this.calculateScale(o),this.container.style.backgroundColor=o.bgcolor,this.container.style.backgroundImage="",o.background){const s=((i=this.options.fileIdToSaveAs)==null?void 0:i.get(String(o.background)))||o.background;this._applyBackgroundImage(this.container,this._mediaFileUrl(s)),this.log.info(`Background image set: ${o.background} → ${s}`)}for(const s of o.regions)await this.createRegion(s);this.log.info("Pre-creating widget elements for instant transitions...");for(const[s,r]of this.regions)for(let a=0;a<r.widgets.length;a++){const l=r.widgets[a];l.layoutId=this.currentLayoutId,l.regionId=s;try{const d=await this.createWidgetElement(l,r);this._positionWidgetElement(d),r.element.appendChild(d),r.widgetElements.set(l.id,d)}catch(d){this.log.error(`Failed to pre-create widget ${l.id}:`,d)}}if(this.log.info("All widget elements pre-created"),this.attachActionListeners(o),this.emit("layoutStart",t,o),o.duration>0){const s=!this._hasUnprobedVideos();this.emit("layoutDurationUpdated",t,o.duration,s)}for(const[s,r]of this.regions)r.isDrawer||this.startRegion(s);this.startLayoutTimerWhenReady(t,o),this._scheduleNextLayoutPreload(o),this.log.info(`Layout ${t} started`)}catch(n){throw this.log.error("Error rendering layout:",n),this.emit("error",{type:"layoutError",error:n,layoutId:t}),n}}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,isCanvas:e.isCanvas||!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 a=setTimeout(()=>{this.log.warn(`Video ready timeout (10000ms) for widget ${t.id}`),r()},1e4),l=()=>{n.removeEventListener("playing",l),clearTimeout(a),this.log.info(`Video widget ${t.id} ready (playing)`),r()};n.addEventListener("playing",l)});const o=this.findMediaElement(e,"AUDIO");if(o)return!o.paused&&o.readyState>=3?Promise.resolve():new Promise(r=>{const a=setTimeout(()=>{this.log.warn(`Audio ready timeout (10000ms) for widget ${t.id}`),r()},1e4),l=()=>{o.removeEventListener("playing",l),clearTimeout(a),this.log.info(`Audio widget ${t.id} ready (playing)`),r()};o.addEventListener("playing",l)});const s=this.findMediaElement(e,"IMG");return s?s.complete&&s.naturalWidth>0?Promise.resolve():new Promise(r=>{const a=()=>{s.removeEventListener("load",a),clearTimeout(l),r()},l=setTimeout(()=>{s.removeEventListener("load",a),this.log.warn(`Image ready timeout for widget ${t.id}`),r()},1e4);s.addEventListener("load",a)}):Promise.resolve()}async startLayoutTimerWhenReady(e,t){if(!t||t.duration<=0)return;const i=[];for(const[n,o]of this.regions){if(o.widgets.length===0)continue;const s=o.widgets[o.currentIndex||0],r=o.widgetElements.get(s.id);r&&i.push(this.waitForWidgetReady(r,s))}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}if(t.isDynamic&&this._hasUnprobedVideos()){this._deferredTimerLayoutId=e,this._layoutTimerStartedAt=Date.now(),this.log.info(`Layout ${e} has unprobed videos — deferring timer until metadata loads`);return}this._startLayoutTimer(e,t)}_hasUnprobedVideos(){for(const[,e]of this.regions)for(const t of e.widgets)if(t.useDuration===0&&t.duration===0)return!0;return!1}_startLayoutTimer(e,t){this._deferredTimerLayoutId=null;const i=t.duration*1e3;this.log.info(`Layout ${e} will end after ${t.duration}s`),this._layoutTimerStartedAt=Date.now(),this._layoutTimerDurationMs=i,this.layoutTimer=setTimeout(()=>{this.log.info(`Layout ${e} duration expired (${t.duration}s)`),this.currentLayoutId&&(this.layoutEndEmitted=!0,this.emit("layoutEnd",this.currentLayoutId))},i)}async _showWidget(e,t){var o,s;const i=e.widgets[t];if(!i)return null;let n=e.widgetElements.get(i.id);if(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)),!e.isCanvas)for(const[r,a]of e.widgetElements)r!==i.id&&((o=a.getAnimations)==null||o.call(a).forEach(l=>l.cancel()),a.style.visibility="hidden",a.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?ne.apply(n,i.transitions.in,!0,e.width,e.height):n.style.opacity="1",n._pdfResume&&n._pdfResume(),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)),n.src=i.uri?this._mediaFileUrl(i.uri):"",n.style.display="none",this.container.appendChild(n);const o=n.play();o&&o.catch&&o.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 a=ne.apply(n,i.transitions.out,!1,e.width,e.height);a&&(o=new Promise(l=>{a.onfinish=l}))}const s=n.querySelector("video");if(s&&i.options.loop!=="1"&&s.pause(),s!=null&&s._mediaStream&&(s._mediaStream.getTracks().forEach(a=>a.stop()),s._mediaStream=null,s.srcObject=null),s!=null&&s._hlsInstance&&(s._hlsInstance.destroy(),s._hlsInstance=null),s!=null&&s._eventCleanup){for(const[a,l]of s._eventCleanup)s.removeEventListener(a,l);s._eventCleanup=null}const r=n.querySelector("audio");if(r&&i.options.loop!=="1"&&r.pause(),r!=null&&r._eventCleanup){for(const[a,l]of r._eventCleanup)r.removeEventListener(a,l);r._eventCleanup=null}return this._stopAudioOverlays(i.id),n._pdfCleanup&&n._pdfCleanup(),{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=t.duration,n=e.match(/<!--\s*DURATION=(\d+)\s*-->/);if(n){const s=parseInt(n[1],10);if(s>0){this.log.info(`Widget ${t.id}: DURATION comment overrides duration ${t.duration}→${s}s`),t.duration=s,t.duration!==i&&this.updateLayoutDuration();return}}const o=e.match(/<!--\s*NUMITEMS=(\d+)\s*-->/);if(o){const s=parseInt(o[1],10);if(s>0&&t.duration>0){const r=s*t.duration;this.log.info(`Widget ${t.id}: NUMITEMS=${s} × ${t.duration}s = ${r}s`),t.duration=r}}t.duration!==i&&this.updateLayoutDuration()}_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,a)=>r.displayOrder-a.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)||{widgetIdx:0,playsDone:0};s=o[r.widgetIdx%o.length];const a=s.playCount||1;r.playsDone++,r.playsDone>=a&&(r.widgetIdx++,r.playsDone=0),this._subPlaylistCycleIndex.set(n,r)}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.isCanvas){this._startCanvasRegion(e,t,i,o);return}if(e.widgets.length===1){i(t,0);return}const s=()=>{const r=e.currentIndex,a=e.widgets[r];i(t,r);const l=a.duration*1e3;this.log.info(`Region ${t} widget ${a.id} (${a.type}) playing for ${a.duration}s (useDuration=${a.useDuration}, index ${r}/${e.widgets.length})`),e.timer=setTimeout(()=>{this._handleWidgetCycleEnd(a,e,t,r,i,n,o,s)},l)};s()}_startCanvasRegion(e,t,i,n){for(let s=0;s<e.widgets.length;s++)i(t,s);const o=Math.max(...e.widgets.map(s=>s.duration))*1e3;o>0?e.timer=setTimeout(()=>{e.complete||(e.complete=!0,n==null||n())},o):(e.complete=!0,n==null||n())}_handleWidgetCycleEnd(e,t,i,n,o,s,r,a){var d;e.webhookUrl&&this.emit("widgetAction",{type:"durationEnd",widgetId:e.id,layoutId:this.currentLayoutId,regionId:i,url:e.webhookUrl}),s(i,n);const l=(t.currentIndex+1)%t.widgets.length;if(l===0&&!t.complete&&(t.complete=!0,r==null||r()),l===0&&((d=t.config)==null?void 0:d.loop)===!1&&t.widgets.length===1){o(i,0);return}this.layoutEndEmitted||(t.currentIndex=l,a())}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._startedWidgets.add(`${e}:${t}`),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=`${e}:${t}`;if(!this._startedWidgets.delete(i))return;const n=this.regions.get(e);if(!n)return;const{widget:o,animPromise:s}=this._hideWidget(n,t);o&&this.emit("widgetEnd",{widgetId:o.id,regionId:e,layoutId:this.currentLayoutId,mediaId:parseInt(o.fileId||o.id)||null,type:o.type,enableStat:o.enableStat}),s&&await s}_stopAllRegionWidgets(e,t){for(const[i,n]of e)if(n.isCanvas)for(let o=0;o<n.widgets.length;o++)t(i,o);else n.widgets.length>0&&t(i,n.currentIndex)}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"},a=s[e.options.alignId]||"center",l=r[e.options.valignId]||"center";i.style.objectPosition=`${a} ${l}`,i.style.opacity="0";const d=e.options.uri?this._mediaFileUrl(e.options.uri):"";return 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;const s=e.options.uri||"",r=e.fileId||e.id,a=()=>{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`)};i.addEventListener("ended",a);let l=s?this._mediaFileUrl(s):"";if(l.includes(".m3u8"))if(i.canPlayType("application/vnd.apple.mpegurl"))this.log.info(`HLS stream (native): ${r}`),i.src=l;else try{const{default:p}=await F(async()=>{const{default:b}=await import("hls.js");return{default:b}},[],import.meta.url);if(p.isSupported()){const b=new p({enableWorker:!0,lowLatencyMode:!0});b.loadSource(l),b.attachMedia(i),i._hlsInstance=b,b.on(p.Events.ERROR,(_,C)=>{C.fatal&&(this.log.error(`HLS fatal error: ${C.type}`,C.details),b.destroy(),i._hlsInstance=null)}),this.log.info(`HLS stream (hls.js): ${r}`)}else this.log.warn(`HLS not supported on this browser for ${r}`),i.src=l}catch(p){this.log.warn(`hls.js not available, falling back to native: ${p.message}`),i.src=l}else i.src=l;const c=this.currentLayoutId,g=()=>{const p=i.duration;this.log.info(`Video ${s} duration detected: ${p}s`),(e.duration===0||e.useDuration===0)&&(e.duration=p,this.log.info(`Updated widget ${e.id} duration to ${p}s (useDuration=0)`),this.currentLayoutId===c?this.updateLayoutDuration():this.log.info(`Video ${s} duration set but layout timer not updated (preloaded for layout ${c}, current is ${this.currentLayoutId})`))};i.addEventListener("loadedmetadata",g);const h=()=>{this.log.info("Video loaded and ready:",s)};i.addEventListener("loadeddata",h);const w=()=>{const p=i.error,b=p==null?void 0:p.code,_=(p==null?void 0:p.message)||"Unknown error";this.log.warn(`Video error: ${s}, code: ${b}, time: ${i.currentTime.toFixed(1)}s, message: ${_}`),this.emit("videoError",{storedAs:s,fileId:r,errorCode:b,errorMessage:_,currentTime:i.currentTime})};i.addEventListener("error",w);const m=()=>{this.log.info("Video playing:",s)};return i.addEventListener("playing",m),i._eventCleanup=[["ended",a],["loadedmetadata",g],["loadeddata",h],["error",w],["playing",m]],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=e.options.uri||"";e.fileId||e.id,n.src=o?this._mediaFileUrl(o):"";const s=()=>{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`)};n.addEventListener("ended",s);const r=this.currentLayoutId,a=()=>{const h=Math.floor(n.duration);this.log.info(`Audio ${o} duration detected: ${h}s`),(e.duration===0||e.useDuration===0)&&(e.duration=h,this.log.info(`Updated widget ${e.id} duration to ${h}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("loadedmetadata",a);const l=()=>{const h=n.error;this.log.warn(`Audio error (non-fatal): ${o}, code: ${h==null?void 0:h.code}, message: ${(h==null?void 0:h.message)||"Unknown"}`)};n.addEventListener("error",l),n._eventCleanup=[["ended",s],["loadedmetadata",a],["error",l]];const d=document.createElement("div");d.innerHTML="♪",d.style.fontSize="120px",d.style.color="white",d.style.marginBottom="20px";const c=document.createElement("div");c.style.color="white",c.style.fontSize="24px",c.textContent="Playing Audio";const g=document.createElement("div");return g.style.color="rgba(255,255,255,0.7)",g.style.fontSize="16px",g.style.marginTop="10px",g.textContent=e.options.uri,i.appendChild(n),i.appendChild(d),i.appendChild(c),i.appendChild(g),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 a=this;i.addEventListener("load",function(){var l;try{if(!((l=i.contentDocument)!=null&&l.querySelector("base"))){a.log.warn("Cache URL failed (hard reload?), using original CMS URLs");const d=new Blob([r.fallback],{type:"text/html"}),c=URL.createObjectURL(d);a.trackBlobUrl(c),i.src=c}}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="transparent",i.style.opacity="0",i.style.position="relative",typeof window.pdfjsLib>"u")try{const o=await F(()=>import("./pdf-BnPRJEQ6.js"),[],import.meta.url);window.pdfjsLib=o;const s=window.location.pathname.replace(/\/[^/]*$/,"/");window.pdfjsLib.GlobalWorkerOptions.workerSrc=`${window.location.origin}${s}pdf.worker.min.mjs`}catch(o){return this.log.error("PDF.js not available:",o),i.innerHTML='<div style="color:white;padding:20px;text-align:center;">PDF viewer unavailable</div>',i.style.opacity="1",i}let n=e.options.uri?this._mediaFileUrl(e.options.uri):"";try{const s=await window.pdfjsLib.getDocument(n).promise,r=s.numPages,a=e.duration||60,l=a*1e3/r;this.log.info(`[pdf] PDF loaded: ${r} pages, ${a}s duration, ${(l/1e3).toFixed(1)}s/page`);const d=await s.getPage(1),c=d.getViewport({scale:1}),g=Math.min(t.width/c.width,t.height/c.height);d.cleanup();const h=document.createElement("canvas");h.className="pdf-page",h.width=Math.floor(c.width*g),h.height=Math.floor(c.height*g),h.style.cssText="display:block;margin:auto;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);";const w=h.getContext("2d");i.appendChild(h);const m=document.createElement("div");m.style.cssText="position:absolute;bottom:10px;right:10px;background:rgba(0,0,0,0.7);color:white;padding:8px 12px;border-radius:4px;font:14px system-ui;z-index:1;",Re()||(m.style.display="none"),i.appendChild(m);let p=1,b=null,_=null,C=!1;const O=async()=>{if(C)return;m.textContent=`Page ${p} / ${r}`;const T=await s.getPage(p),$=T.getViewport({scale:g});w.clearRect(0,0,h.width,h.height),_=T.render({canvasContext:w,viewport:$});try{await _.promise}catch(v){if(C)return;throw v}_=null,T.cleanup(),r>1&&!C&&(b=setTimeout(()=>{p=p>=r?1:p+1,O()},l))};await O();let x=null;i._pdfCleanup=()=>{if(C=!0,b&&clearTimeout(b),b=null,_){const T=_;_=null,T.cancel(),x=T.promise.catch(()=>{})}},i._pdfResume=async()=>{i._pdfCleanup(),x&&(await x,x=null),C=!1,p=1,O()},i._pdfDestroy=()=>{i._pdfCleanup(),h.width=0,h.height=0,s.destroy()}}catch(o){this.log.error("PDF render failed:",o),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");n.className="renderer-lite-widget",n.style.width="100%",n.style.height="100%",n.style.border="none",n.style.opacity="0";const o=decodeURIComponent(e.options.uri||"");return n.src=o,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 a=new Blob([o.fallback],{type:"text/html"}),l=URL.createObjectURL(a);s.trackBlobUrl(l),i.src=l}}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)}hasPreloadedLayout(e){return this.layoutPool.has(e)}async preloadLayout(e,t){var i;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 n=this.parseXlf(e);this.calculateScale(n);const o=document.createElement("div");if(o.id=`preload_layout_${t}`,o.className="renderer-lite-preload-wrapper",o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="100%",o.style.height="100%",o.style.visibility="hidden",o.style.zIndex="-1",o.style.backgroundColor=n.bgcolor,n.background){const g=((i=this.options.fileIdToSaveAs)==null?void 0:i.get(String(n.background)))||n.background;this._applyBackgroundImage(o,this._mediaFileUrl(g))}const s=this.currentLayoutId,r=new Map,a=this.scaleFactor;for(const g of n.regions){const h=document.createElement("div");h.id=`preload_region_${t}_${g.id}`,h.className="renderer-lite-region",h.style.position="absolute",h.style.zIndex=g.zindex,h.style.overflow="hidden",this.applyRegionScale(h,g),o.appendChild(h);const w={element:h,config:g,widgets:g.widgets,currentIndex:0,timer:null,width:g.width*a,height:g.height*a,complete:!1,widgetElements:new Map};r.set(g.id,w)}const l=new Set,d=this.layoutBlobUrls;this.layoutBlobUrls=new Map,this.layoutBlobUrls.set(t,l),this._preloadingLayoutId=t;for(const[g,h]of r)for(let w=0;w<h.widgets.length;w++){const m=h.widgets[w];m.layoutId=t,m.regionId=g;try{const p=await this.createWidgetElement(m,h);this._positionWidgetElement(p),h.element.appendChild(p),h.widgetElements.set(m.id,p)}catch(p){this.log.error(`Preload: Failed to create widget ${m.id}:`,p)}}return this.currentLayoutId=s,o.querySelectorAll("video").forEach(g=>g.pause()),(this.layoutBlobUrls.get(t)||new Set).forEach(g=>l.add(g)),this.layoutBlobUrls=d,this.container.appendChild(o),this.layoutPool.add(t,{container:o,layout:n,regions:r,blobUrls:l}),this.log.info(`Layout ${t} preloaded into pool (${r.size} regions)`),!0}catch(n){return this.log.error(`Preload failed for layout ${t}:`,n),!1}}async _swapToPreloadedLayout(e){var o;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,n=this.layoutEndEmitted;if(this.layoutEndEmitted=!1,i&&this.layoutPool.has(i))this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,(s,r)=>this.stopWidget(s,r)),this.layoutPool.evict(i);else{this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,(s,r)=>this.stopWidget(s,r));for(const[,s]of this.regions)if(ie.releaseMediaElements(s.element),(o=s.config)!=null&&o.exitTransition){const r=ne.apply(s.element,s.config.exitTransition,!1,s.width,s.height);if(r){const a=s.element;r.onfinish=()=>a.remove()}else s.element.remove()}else s.element.remove();i&&this.revokeBlobUrlsForLayout(i)}if(this.currentLayout=null,this.currentLayoutId=null,this.regions.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,i&&!n&&this.emit("layoutEnd",i),this.container.style.backgroundColor=t.layout.bgcolor,t.container.style.backgroundImage)for(const s of["backgroundImage","backgroundSize","backgroundPosition","backgroundRepeat"])this.container.style[s]=t.container.style[s];else this.container.style.backgroundImage="";this.calculateScale(t.layout),this.attachActionListeners(t.layout),this.emit("layoutStart",e,t.layout);for(const[s,r]of this.regions)r.currentIndex=0,r.complete=!1,this.startRegion(s);this.updateLayoutDuration(),this.startLayoutTimerWhenReady(e,t.layout),this.preloadTimer||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(){var i;if(!this.currentLayout)return;this.log.info(`Stopping layout ${this.currentLayoutId}`);const e=this.currentLayoutId,t=e&&!this.layoutEndEmitted;if(this.layoutEndEmitted=!1,this._deferredTimerLayoutId=null,this.currentLayout=null,this.currentLayoutId=null,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.removeActionListeners(),e&&this.layoutPool.has(e))this.layoutPool.evict(e);else{e&&this.revokeBlobUrlsForLayout(e),this._clearRegionTimers(this.regions),this._stopAllRegionWidgets(this.regions,(n,o)=>this.stopWidget(n,o));for(const[,n]of this.regions)if(ie.releaseMediaElements(n.element),(i=n.config)!=null&&i.exitTransition){const o=ne.apply(n.element,n.config.exitTransition,!1,n.width,n.height);if(o){const s=n.element;o.onfinish=()=>s.remove()}else n.element.remove()}else n.element.remove()}this.regions.clear(),t&&this.emit("layoutEnd",e)}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");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.calculateScale(n);const s=new Map,r=this.scaleFactor;for(const a of n.regions){const l=document.createElement("div");l.id=`overlay_${t}_region_${a.id}`,l.className="renderer-lite-region overlay-region",l.style.position="absolute",l.style.zIndex=String(a.zindex),l.style.overflow="hidden",this.applyRegionScale(l,a),o.appendChild(l),s.set(a.id,{element:l,config:a,widgets:a.widgets,currentIndex:0,timer:null,width:a.width*r,height:a.height*r,complete:!1,isCanvas:a.isCanvas||!1,widgetElements:new Map})}for(const[a,l]of s)for(const d of l.widgets){d.layoutId=t,d.regionId=a;try{const c=await this.createWidgetElement(d,l);this._positionWidgetElement(c),l.element.appendChild(c),l.widgetElements.set(d.id,c)}catch(c){this.log.error(`Failed to pre-create overlay widget ${d.id}:`,c)}}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[a,l]of s)this.startOverlayRegion(t,a);if(n.duration>0){const a=n.duration*1e3,l=this.activeOverlays.get(t);l&&(l.timer=setTimeout(()=>{this.log.info(`Overlay ${t} duration expired (${n.duration}s)`),this.emit("overlayEnd",t)},a))}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._startedWidgets.add(`overlay:${e}:${t}:${i}`),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=`overlay:${e}:${t}:${i}`;if(!this._startedWidgets.delete(n))return;const o=this.activeOverlays.get(e);if(!o)return;const s=o.regions.get(t);if(!s)return;const{widget:r,animPromise:a}=this._hideWidget(s,i);r&&this.emit("overlayWidgetEnd",{overlayId:e,widgetId:r.id,regionId:t,type:r.type}),a&&await a}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]of t.regions)i.timer&&(clearTimeout(i.timer),i.timer=null);this._stopAllRegionWidgets(t.regions,(i,n)=>this.stopOverlayWidget(e,i,n)),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(),this._startedWidgets.clear();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 V=U("Layout");class St{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"),a=o.getAttribute("bgcolor")||"#000000",l=[];for(const d of n.querySelectorAll("region"))l.push(await this.translateRegion(e,d));return this.generateHTML(s,r,a,l)}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")),a=parseInt(t.getAttribute("zindex")||"0"),l=[];for(const d of t.querySelectorAll("media"))l.push(await this.translateMedia(e,i,d));return{id:i,width:n,height:o,top:s,left:r,zindex:a,media:l}}async translateMedia(e,t,i){const n=i.getAttribute("type"),o=parseInt(i.getAttribute("duration")||"10"),s=i.getAttribute("id"),r=i.querySelector("options"),a=i.querySelector("raw"),l={};if(r)for(const C of r.children)l[C.tagName]=C.textContent;const d={in:null,out:null},c=i.querySelector("options > transIn"),g=i.querySelector("options > transOut"),h=i.querySelector("options > transInDuration"),w=i.querySelector("options > transOutDuration"),m=i.querySelector("options > transInDirection"),p=i.querySelector("options > transOutDirection");c&&c.textContent&&(d.in={type:c.textContent,duration:parseInt((h==null?void 0:h.textContent)||"1000"),direction:(m==null?void 0:m.textContent)||"N"}),g&&g.textContent&&(d.out={type:g.textContent,duration:parseInt((w==null?void 0:w.textContent)||"1000"),direction:(p==null?void 0:p.textContent)||"N"});let b=a?a.textContent:"";if(["clock","clock-digital","clock-analogue","calendar","weather","currencies","stocks","twitter","global","embedded","text","ticker"].some(C=>n.includes(C))){let C=3,O=null;for(let x=1;x<=C;x++)try{V.info(`Fetching resource for ${n} widget (layout=${e}, region=${t}, media=${s}) - attempt ${x}/${C}`),b=await this.xmds.getResource(e,t,s),V.info(`Got resource HTML (${b.length} chars)`);const T=await Ue(e,t,s,b);l.widgetCacheKey=T;break}catch(T){if(O=T,V.warn(`Failed to get resource (attempt ${x}/${C}):`,T.message),x<C){const $=x*2e3;V.info(`Retrying in ${$}ms...`),await new Promise(v=>setTimeout(v,$))}}if(!b&&O){V.warn("All retries failed, checking for cached widget HTML...");try{const x=await fetch(`/store${B}/widgets/${e}/${t}/${s}`);x.ok?(b=await x.text(),l.widgetCacheKey=`${B}/widgets/${e}/${t}/${s}`,V.info(`Using stored widget HTML (${b.length} chars) - CMS update pending`)):(V.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(x){V.error("Store fallback failed:",x),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:l,raw:b,transitions:d}}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>
|
|
5
5
|
<html>
|
|
@@ -603,10 +603,10 @@ ${t}
|
|
|
603
603
|
}
|
|
604
604
|
container.remove();
|
|
605
605
|
}
|
|
606
|
-
}`;break;case"webpage":const
|
|
606
|
+
}`;break;case"webpage":const O=decodeURIComponent(e.options.uri||"");s=`() => {
|
|
607
607
|
const region = document.getElementById('region_${t}');
|
|
608
608
|
const iframe = document.createElement('iframe');
|
|
609
|
-
iframe.src = '${
|
|
609
|
+
iframe.src = '${O}';
|
|
610
610
|
iframe.style.opacity = '0';
|
|
611
611
|
region.innerHTML = '';
|
|
612
612
|
region.appendChild(iframe);
|
|
@@ -732,5 +732,5 @@ ${a.join(`
|
|
|
732
732
|
border: none;
|
|
733
733
|
background: #1D1D1D;
|
|
734
734
|
display: none;
|
|
735
|
-
`,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 a=this.iframe.contentDocument;if(!a)return;a.addEventListener("keydown",l=>{l.key==="Escape"&&(l.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()===Be.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=U("PWA"),z=B.slice(1),le=new URL("./",window.location.href).pathname.replace(/\/$/,"");let $e,X,D,_e,Le,Ce,Ie,N,G,xe,Te,ke,De,Ae,Me;const j={};class ft{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,"_html2canvasMod",null);L(this,"_screenshotInFlight",!1);L(this,"_wakeLock",null);L(this,"syncManager",null);L(this,"_currentLayoutEnableStat",!0);L(this,"_probeTimer",null);L(this,"_mediaStatusTimer",null);L(this,"_pendingFollowerStats",null);L(this,"_pendingFollowerLogs",null);L(this,"_iframeObserver",null);L(this,"_swIcHandler",null);L(this,"_chunkConfig",null);L(this,"_fileIdToSaveAs",new Map);L(this,"protocolDetector",null)}async init(){if(u.info("Initializing player with RendererLite + PlayerCore..."),await this.loadCoreModules(),"serviceWorker"in navigator)try{const s=await navigator.serviceWorker.register(`${le}/sw-pwa.js?v=${Date.now()}`,{scope:`${le}/`,type:"module",updateViaCache:"none"});u.info("Service Worker registered for offline mode:",s.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(s){u.warn("Service Worker registration failed:",s)}u.info("Initializing cache clients..."),N=new je;const{calculateChunkConfig:e}=await F(async()=>{const{calculateChunkConfig:s}=await import("./index-D3ONc-uh.js");return{calculateChunkConfig:s}},__vite__mapDeps([0,1,2]),import.meta.url);this._chunkConfig=e(u),G=new ze({concurrency:this._chunkConfig.concurrency,chunkSize:this._chunkConfig.chunkSize,chunksPerFile:2}),u.info("Cache clients ready — StoreClient + DownloadManager");const t=document.getElementById("player-container");if(!t)throw new Error("No #player-container found");this.renderer=new at({cmsUrl:D.cmsUrl,hardwareKey:D.hardwareKey},t,{fileIdToSaveAs:this._fileIdToSaveAs,getWidgetHtml:async s=>{const r=`${B}/widgets/${s.layoutId}/${s.regionId}/${s.id}`;u.debug(`Looking for widget HTML at: ${r}`,s);try{if(await N.has(`${z}/widgets`,`${s.layoutId}/${s.regionId}/${s.id}`))return u.debug("Widget HTML found in store, using mirror URL for iframe"),{url:r,fallback:s.raw||""};u.warn(`No widget HTML found in store: ${r}`)}catch(a){u.error(`Failed to check widget HTML for ${s.id}:`,a)}return u.warn(`Using widget.raw fallback for ${s.id}`),s.raw||""}}),this.core=new dt({config:D,xmds:this.xmds,cache:N,schedule:X,renderer:this.renderer,xmrWrapper:Ie,statsCollector:this.statsCollector,displaySettings:this.displaySettings,cmsId:D.activeCmsId}),this.setupCoreEventHandlers(),this.setupRendererEventHandlers(),this.setupInteractiveControl(),this.setupDataConnectorNotify(),this.setupRemoteControls(),this.core.on("register-complete",s=>{var l,d;const r=parseFloat((l=s==null?void 0:s.settings)==null?void 0:l.latitude),a=parseFloat((d=s==null?void 0:s.settings)==null?void 0:d.longitude);r&&a&&!isNaN(r)&&!isNaN(a)?(u.info(`Display location from CMS: ${r.toFixed(4)}, ${a.toFixed(4)}`),X!=null&&X.setLocation&&X.setLocation(r,a)):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(s=>{u.error("Failed to collect after coming online:",s)})}),window.addEventListener("offline",()=>{u.warn("Browser reports offline — continuing playback with cached data"),this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()});const n=(this.getControls().keyboard||{}).debugOverlays===!0,o=ut();o.enabled&&n&&(this.downloadOverlay=new ve(o),this.downloadOverlay.setProgressCallback(()=>G.getProgress()),u.info("Download overlay enabled (hover bottom-right corner)")),ht()&&n&&(this.timelineOverlay=new be(!0,s=>this.skipToLayout(s))),this.setupCertWarnings(),this.setupXmrWarning(),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)}}setupCertWarnings(){const e=new Set;window.addEventListener("cert-warning",t=>{const{host:i,error:n}=t.detail;if(e.has(i))return;e.add(i),u.warn(`Invalid SSL certificate accepted for stream: ${i} (${n})`);let o=document.getElementById("overlay"),s=!1;if(!o){o=document.createElement("div"),o.id="overlay";const l=document.createElement("div");l.id="config-info",o.appendChild(l);const d=document.createElement("div");d.id="status",o.appendChild(d),document.body.appendChild(o),s=!0}let r=document.getElementById("cert-warnings");if(!r){r=document.createElement("span"),r.id="cert-warnings",r.style.cssText="color: #ffaa33; flex: 0 0 auto;";const l=document.getElementById("status");o.insertBefore(r,l)}const a=[...e].join(", ");r.textContent=`⚠ SSL: ${a}`,s&&this.updateConfigDisplay()})}setupXmrWarning(){this.core.on("xmr-status",({connected:e})=>{const t=document.getElementById("overlay");if(!t)return;let i=document.getElementById("xmr-warning");if(e)i==null||i.remove();else{if(!i){i=document.createElement("span"),i.id="xmr-warning",i.style.cssText="color: #ff6666; flex: 0 0 auto;";const n=document.getElementById("cert-warnings")||document.getElementById("status");t.insertBefore(i,n)}i.textContent="⚠ XMR disconnected"}})}async loadCoreModules(){var e,t,i;try{const[n,o,s,r,a,l,d,c,g,h]=await Promise.all([F(()=>import("./index-DaK61i9Z.js"),__vite__mapDeps([3,4,2]),import.meta.url),F(()=>import("./index-DhU2Fgj5.js"),__vite__mapDeps([5,6,2]),import.meta.url),F(()=>import("./index-I6Jt7iN-.js"),__vite__mapDeps([7,8,2,4]),import.meta.url),F(()=>import("./index-Dllq0Rxc.js"),[],import.meta.url),F(()=>import("./index-DMq935D7.js"),__vite__mapDeps([9,2]),import.meta.url),F(()=>import("./index-DLnEjxEP.js"),__vite__mapDeps([10,2]),import.meta.url),F(()=>import("./index-DuYioXxs.js"),__vite__mapDeps([11,2]),import.meta.url),F(()=>import("./index-DpUJWDra.js"),__vite__mapDeps([12,2,8,4]),import.meta.url),F(()=>import("./index-B2q-aBh8.js"),__vite__mapDeps([13,8,2,4]),import.meta.url),F(()=>import("./sync-manager-CNULCESw.js"),__vite__mapDeps([14,2]),import.meta.url)]);if($e=n.cacheWidgetHtml,Me=h.SyncManager,X=s.scheduleManager,D=r.config,_e=o.RestClient,Le=o.XmdsClient,Ce=o.ProtocolDetector,Ie=a.XmrWrapper,xe=l.StatsCollector,Te=l.formatStats,ke=l.LogReporter,De=l.formatLogs,Ae=d.DisplaySettings,j.core=c.VERSION||"?",j.cache=n.VERSION||"?",j.renderer=g.VERSION||"?",j.schedule=s.VERSION||"?",j.xmds=o.VERSION||"?",j.xmr=a.VERSION||"?",j.utils=r.VERSION||"?",j.stats=l.VERSION||"?",j.settings=d.VERSION||"?",(e=window.electronAPI)!=null&&e.getSystemInfo)try{const E=await window.electronAPI.getSystemInfo();E.macAddress&&(D.macAddress=E.macAddress)}catch{}const w=D.transport!=="auto"?D.transport:void 0,p=new URLSearchParams(window.location.search).get("transport")||(le.includes("pwa-xmds")?"xmds":null)||w||"auto";this.protocolDetector=new Ce(D.cmsUrl,_e,Le);const b=p==="auto"?void 0:p,{client:_}=await this.protocolDetector.detect(D,b);this.xmds=_;const C=D.activeCmsId;this.statsCollector=new xe(C),await this.statsCollector.init(),u.info(`Stats collector initialized${C?` (CMS: ${C})`:""}`),this.logReporter=new ke(C),await this.logReporter.init(),u.info(`Log reporter initialized${C?` (CMS: ${C})`:""}`),he(({level:E,name:A,args:k})=>{if(!this.logReporter)return;const M=k.map(P=>typeof P=="string"?P:JSON.stringify(P)).join(" ");this.logReporter.log(E,`[${A}] ${M}`,"PLAYER").catch(()=>{})});const R=D.debug;if(R!=null&&R.consoleLogs){const E=(R.consoleLogsInterval||10)*1e3;let A=[],k=null;const M=()=>{if(A.length===0)return;const P=A;A=[],k=null,fetch("/debug/log",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)}).catch(()=>{})};he(({level:P,name:ee,args:se})=>{const te=se.map(J=>typeof J=="string"?J:JSON.stringify(J)).join(" ");A.push({level:P,name:ee,message:te,ts:new Date().toISOString()}),k||(k=setTimeout(M,E))}),u.info(`Console log forwarding to proxy enabled (flush every ${E/1e3}s)`)}this.displaySettings=new Ae,u.info("Display settings manager initialized");const x="2026-03-12T14:06:56.706Z",T="0.6.11";u.info(`v${T} built ${x}`);const $=Object.entries(j).map(([E,A])=>`${E}=${A}`).join(" ");u.info(`SDK: ${$}`);const v=!!window.electronAPI,S=v?((t=navigator.userAgent.match(/Electron\/([\d.]+)/))==null?void 0:t[1])||"?":null,O=((i=navigator.userAgent.match(/Chrome\/([\d.]+)/))==null?void 0:i[1])||"?",I=v?`Electron ${S} / Chrome ${O}`:`Chrome ${O}`;u.info(`Env: PWA v${T} | ${I} | ${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||D.hardwareKey;this.updateStatus(`Registered: ${t}`),this.displaySettings&&(document.title=`Xibo Player - ${this.displaySettings.getDisplayName()}`)}),this.core.on("sync-config",e=>{if(this.syncManager&&this.syncManager.stop(),e.syncPublisherPort&&e.syncGroup!=="lead"){const t=e.isLead?"localhost":e.syncGroup;e.relayUrl=`ws://${t}:${e.syncPublisherPort}/sync`}this.syncManager=new Me({displayId:D.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 N.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,i;(t=this.downloadOverlay)==null||t.startUpdating();try{const n=((i=this.xmds)==null?void 0:i._token)||null;n&&await fetch("/auth-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:n})}),await this.enqueueDownloads(e),u.info("Download enqueue complete")}catch(n){u.error("Download request failed:",n),this.updateStatus("Download failed: "+n,"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("layout-expire-current",()=>{u.info("Schedule changed — expiring current layout"),this.renderer.stopCurrentLayout()}),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.core.on("collection-error",async e=>{var t;if(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.protocolDetector&&this.protocolDetector.getProtocol()!==null)try{const{client:i,protocol:n,changed:o}=await this.protocolDetector.reprobe(D);o&&i&&(u.info(`Protocol switched to ${n} after connection error`),this.xmds=i,this.core.xmds=i)}catch(i){u.warn("Protocol re-probe failed:",i)}}),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}`)}),this.core.on("log-level-changed",()=>{u.info("Log level changed")}),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 N.list();if(e.length>0){const i=await N.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.core.on("execute-native-command",async e=>{var i;let t;if((i=window.electronAPI)!=null&&i.executeShellCommand)t=await window.electronAPI.executeShellCommand({commandString:e.commandString});else try{t=await(await fetch("/shell-command",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commandString:e.commandString})})).json()}catch(n){t={success:!1,reason:n.message}}this.core.emit("command-result",{code:e.code,...t})}),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("navigate-to-widget",e=>{e.targetId?this.renderer.navigateToWidget(e.targetId):u.warn("navigate-to-widget action has no targetId:",e)}),this.core.on("timeline-updated",e=>{var n;const t=this.core.getCurrentLayoutId(),i=t?this.core.getLayoutDuration(t):void 0;(n=this.timelineOverlay)==null||n.update(e,t,i)})}setupInteractiveControl(){var e;this._swIcHandler=t=>{var l,d;if(((l=t.data)==null?void 0:l.type)!=="INTERACTIVE_CONTROL")return;const{method:i,path:n,search:o,body:s}=t.data,r=(d=t.ports)==null?void 0:d[0];if(!r)return;const a=this.handleInteractiveControl(i,n,o,s);r.postMessage(a)},(e=navigator.serviceWorker)==null||e.addEventListener("message",this._swIcHandler)}setupDataConnectorNotify(){this.core.getDataConnectorManager().on("data-changed",t=>{var o;const i=document.querySelectorAll("iframe"),n={ctrl:"rtNotifyData",data:{dataKey:t}};for(const s of i)try{(o=s.contentWindow)==null||o.postMessage(n,"*")}catch{}})}setupRemoteControls(){window.addEventListener("blur",()=>{setTimeout(()=>window.focus(),200)});const e=a=>{const l=()=>{var d;try{const c=a.contentDocument||((d=a.contentWindow)==null?void 0:d.document);if(!c||a.__keyForwarderAttached)return;a.__keyForwarderAttached=!0,c.addEventListener("keydown",g=>{const h=new KeyboardEvent("keydown",{key:g.key,code:g.code,keyCode:g.keyCode,ctrlKey:g.ctrlKey,shiftKey:g.shiftKey,altKey:g.altKey,metaKey:g.metaKey,bubbles:!0,cancelable:!0});document.dispatchEvent(h)||g.preventDefault()})}catch{}};a.addEventListener("load",l),l()};Array.from(document.querySelectorAll("iframe")).forEach(a=>e(a)),this._iframeObserver=new MutationObserver(a=>{for(const l of a)for(const d of l.addedNodes)d instanceof HTMLIFrameElement&&e(d),d instanceof HTMLElement&&d.querySelectorAll("iframe").forEach(c=>e(c))}),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",a=>{if(a.key==="q"&&(a.ctrlKey||a.metaKey)){a.preventDefault(),u.info("[Remote] Quit requested (Ctrl+Q)"),fetch("/quit",{method:"POST"}).catch(()=>{});return}switch(a.key){case"t":case"T":if(!n)break;this.timelineOverlay||(this.timelineOverlay=new be(!0,l=>this.skipToLayout(l))),this.timelineOverlay.toggle();break;case"d":case"D":if(!n)break;this.downloadOverlay||(this.downloadOverlay=new ve({enabled:!0,autoHide:!1}),this.downloadOverlay.setProgressCallback(()=>G.getProgress())),this.downloadOverlay.toggle();break;case"v":case"V":{if(!r)break;const l=[...document.querySelectorAll("video")];document.querySelectorAll("iframe").forEach(c=>{try{l.push(...c.contentDocument.querySelectorAll("video"))}catch{}});const d=l.length>0&&!l[0].controls;l.forEach(c=>c.controls=d);break}case"ArrowRight":case"PageDown":if(!s)break;u.info("[Remote] Next layout (keyboard)"),this.core.advanceToNextLayout(),a.preventDefault();break;case"ArrowLeft":case"PageUp":if(!s)break;u.info("[Remote] Previous layout (keyboard)"),this.core.advanceToPreviousLayout(),a.preventDefault();break;case" ":if(!s)break;u.info("[Remote] Toggle pause (keyboard)"),this.renderer.isPaused()?this.renderer.resume():this.renderer.pause(),a.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 gt),this.setupOverlay.toggle(),a.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(){return D.controls}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:D.hardwareKey,displayName:D.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 l=this.core.getDataConnectorManager().getData(r);return l===null?{status:404,body:JSON.stringify({error:`No data available for key: ${r}`})}:{status:200,body:typeof l=="string"?l:JSON.stringify(l)}}case"/criteria":return{status:200,body:JSON.stringify({displayId:D.displayId,hardwareKey:D.hardwareKey,displayName:D.displayName,width:window.innerWidth,height:window.innerHeight,latitude:D.latitude||null,longitude:D.longitude||null,playerType:"pwa"})};default:return{status:404,body:JSON.stringify({error:"Unknown IC route"})}}}notifyFileCached(e,t){if(u.debug(`Download complete: ${t}/${e}`),t==="layout")this.core.notifyMediaReady(parseInt(e),t);else if(t==="media"){const i=this._fileIdToSaveAs.get(e)||e;this.core.notifyMediaReady(i,t)}this._probeTimer&&clearTimeout(this._probeTimer),this._probeTimer=setTimeout(()=>{this._probeTimer=null,this.probeLayoutDurations().catch(()=>{})},3e3),this._mediaStatusTimer&&clearTimeout(this._mediaStatusTimer),this._mediaStatusTimer=setTimeout(()=>{this._mediaStatusTimer=null,this.checkTimelineMediaStatus().catch(()=>{})},2e3)}async enqueueDownloads(e){const{extractMediaIdsFromXlf:t}=await F(async()=>{const{extractMediaIdsFromXlf:$}=await import("./index-D3ONc-uh.js");return{extractMediaIdsFromXlf:$}},__vite__mapDeps([0,1,2]),import.meta.url),{layoutOrder:i,files:n,layoutDependants:o}=e,s=G.queue,r=$=>($.path||"").split("?")[0].replace(/^\/+/,"")||`${$.type||"media"}/${$.id}`;for(const $ of n)$.saveAs&&this._fileIdToSaveAs.set(String($.id),$.saveAs);const a=new Map,l=[],d=new Map,c=new Map;for(const $ of n)if($.type==="layout")a.set(parseInt($.id),$);else if($.type==="static")l.push($);else{const v=`${$.type}:${$.id}`;d.set(v,$);const S=String($.id);c.has(S)||c.set(S,[]),c.get(S).push(v)}u.info(`Download: ${i.length} layouts, ${d.size} media, ${l.length} resources`);const g=new Map,w=[...i,...[...a.keys()].filter($=>!i.includes($))].map(async $=>{const v=a.get($);if(!(v!=null&&v.path))return;let S;try{const O=await fetch(v.path);O.ok&&(S=await O.text(),u.info(`Fetched XLF ${$} (${S.length} bytes)`),this.notifyFileCached(String($),"layout"))}catch{}S&&g.set($,t(S,u))});await Promise.allSettled(w),u.info(`Parsed ${g.size} XLFs`);const m=async($,v)=>{if(!v.path||v.path==="null"||v.path==="undefined")return!1;const S=r(v);try{if((await fetch(`/store/${S}`,{method:"HEAD"})).ok)return!1}catch{}if(G.getTask(S))return!1;try{const I=await fetch(`/store/missing-chunks/${S}`);if(I.ok){const{missing:E,numChunks:A}=await I.json();if(A>0&&E.length<A){const k=new Set;for(let M=0;M<A;M++)E.includes(M)||k.add(M);v.skipChunks=k,u.info(`Resuming ${S}: ${k.size}/${A} chunks cached, ${E.length} to download`)}}}catch{}const O=$.addFile(v);return O.state!=="pending"?!1:(O.wait().then(I=>{const E=parseInt(v.size)||I.size;u.info("Download complete:",S,`(${E} bytes)`),E>this._chunkConfig.chunkSize&&fetch("/store/mark-complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storeKey:S})}).catch(A=>u.warn("mark-complete failed:",S,A.message)),this.notifyFileCached(String(v.id),v.type),s.removeCompleted(S)}).catch(I=>{u.error("Download failed:",v.id,I),s.removeCompleted(r(v))}),!0)},p=new ae(s);for(const $ of l)await m(p,$);const b=await p.build();b.length>0&&(b.push(ge),s.enqueueOrderedTasks(b));const _=new Set,C=[...g.keys()].filter($=>!i.includes($)),R=new Map;for(const[$,v]of d)v.saveAs&&R.set(v.saveAs,$);const x=new Map;if(o)for(const[$,v]of Object.entries(o))x.set(parseInt($,10),v);for(const $ of i){const v=g.get($);if(!v)continue;const S=new Set(v);for(const k of C){const M=g.get(k);if(M)for(const P of M)S.add(P)}const O=x.get($)||[];for(const k of O){const M=R.get(k);M&&S.add(M)}const I=[];for(const k of S){if(d.has(k)&&!_.has(k)){I.push(d.get(k)),_.add(k);continue}const M=c.get(String(k))||[];for(const P of M)_.has(P)||(I.push(d.get(P)),_.add(P))}if(I.length===0)continue;u.info(`Layout ${$}: ${I.length} media`),I.sort((k,M)=>(k.size||0)-(M.size||0));const E=new ae(s);for(const k of I)await m(E,k);const A=await E.build();A.length>0&&(A.push(ge),s.enqueueOrderedTasks(A))}const T=[...d.keys()].filter($=>!_.has($));if(T.length>0){u.info(`${T.length} media not in any XLF`);const $=new ae(s);for(const S of T){const O=d.get(S);O&&await m($,O)}const v=await $.build();v.length>0&&s.enqueueOrderedTasks(v)}u.info("Downloads active:",s.running,", queued:",s.queue.length)}setupRendererEventHandlers(){this.renderer.on("layoutStart",(e,t)=>{var n;u.info("Layout started:",e),this.updateStatus(`Playing layout ${e}`),this.core.setCurrentLayout(e),this._currentLayoutEnableStat=(t==null?void 0:t.enableStat)!==!1;const i=this.core.getLayoutDuration(e)||(t==null?void 0:t.duration);(n=this.timelineOverlay)==null||n.update(null,e,i),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.startLayout(e,this.currentScheduleId).catch(o=>{u.error("Failed to start layout stat:",o)})}),this.renderer.on("layoutEnd",e=>{if(u.info("Layout ended:",e),X==null||X.recordPlay(e.toString()),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.endLayout(e,this.currentScheduleId).catch(i=>{u.error("Failed to end layout stat:",i)}),this.renderer.currentLayoutId&&this.renderer.currentLayoutId!==e){u.debug(`Layout ${e} ended but ${this.renderer.currentLayoutId} already playing, skipping advance`);return}if(this.preparingLayoutId&&this.preparingLayoutId!==e){u.debug(`Layout ${e} ended but ${this.preparingLayoutId} being prepared, skipping advance`);return}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("widgetCommand",e=>{u.info("Widget command:",e.commandCode);const t={[e.commandCode]:{commandString:e.commandString}};this.core.executeCommand(e.commandCode,t)}),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,a;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((a=e.source)==null?void 0:a.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,i)=>{this.core.recordLayoutDuration(String(e),t,i)}),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 N.get(`${z}/layouts`,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)}}),this.renderer.on("videoError",async({storedAs:e})=>{if(!e)return;const t=`${B.slice(1)}/media/file/${e}`;try{const i=await fetch(`/store/missing-chunks/${t}`),{missing:n}=await i.json();if(n.length===0){u.warn(`Video error for ${e} but no missing chunks — possible decode error`);return}u.warn(`Video ${e}: ${n.length} missing chunks (${n.join(", ")}), re-downloading`),await fetch("/store/unmark-complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storeKey:t})}),this.core.collectNow().catch(o=>{u.error(`Failed to trigger re-download for ${e}:`,o.message)})}catch(i){u.error(`Failed to check/re-download ${e}:`,i.message)}})}async prepareAndRenderLayout(e){var t;if(this.core.getCurrentLayoutId()===e){u.debug(`Layout ${e} already playing, skipping duplicate prepare`),this.core._preparingLayoutId=null;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 N.get(`${z}/layouts`,e);if(!i){u.info("Layout not in cache yet, marking as pending:",e),this.core.setPendingLayout(e,[String(e)]),this.updateStatus(`Downloading layout ${e}...`);return}const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(!await this.checkAllMediaCached(o)){G.prioritizeLayoutFiles(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}this.renderer.hasPreloadedLayout(e)||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,this.core._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(a=>{const l=a.getAttribute("fileId");if(l){const d=this._fileIdToSaveAs.get(l)||l;if(d.endsWith(".xlf"))return;n.push(d),a.getAttribute("type")==="video"&&o.push(d)}});const s=(r=i.querySelector("layout"))==null?void 0:r.getAttribute("background");if(s){const a=this._fileIdToSaveAs.get(s)||s;n.includes(a)||n.push(a)}return{allMedia:n,videoMedia:o}}async checkAllMediaCached(e){for(const t of e)try{if(!await N.has(z,`media/file/${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 a of s.querySelectorAll("media")){const l=a.getAttribute("type"),d=a.getAttribute("id");a.getAttribute("render")==="html"&&o.push((async()=>{try{const g=`${t}/${r}/${d}`;let h=null;const w=await N.get(`${z}/widgets`,g);w&&(h=await w.text(),u.debug(`Found cached widget HTML for ${l} ${d}`)),h||(h=await this.xmds.getResource(t,r,d),u.debug(`Retrieved widget HTML for ${l} ${d} from CMS`)),await $e(t,r,d,h);const m=await N.get(`${z}/widgets`,g);m&&(h=await m.text());const p=a.querySelector("raw");if(p)p.textContent=h;else{const b=n.createElement("raw");b.textContent=h,a.appendChild(b)}}catch(g){u.warn(`Failed to get widget HTML for ${l} ${d}:`,g)}})())}}o.length>0&&(u.info(`Fetching ${o.length} widget HTML resources in parallel...`),await Promise.all(o),u.debug("All widget HTML fetched"))}async checkTimelineMediaStatus(){if(this.scheduledLayoutIds.size!==0){for(const e of this.scheduledLayoutIds){const t=`${e}.xlf`;try{const i=await N.get(`${z}/layouts`,e);if(!i)continue;const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(o.length===0){this.core.setLayoutMediaStatus(t,!0);continue}const s=[];for(const r of o)try{await N.has(z,`media/file/${r}`)||s.push(r)}catch{}this.core.setLayoutMediaStatus(t,s.length===0,s)}catch{}}this.core.logUpcomingTimeline()}}async probeLayoutDurations(){if(this.scheduledLayoutIds.size!==0)for(const e of this.scheduledLayoutIds)try{const t=await N.get(`${z}/layouts`,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;let a=0;for(const c of s.querySelectorAll('media[type="video"]')){if(c.getAttribute("useDuration")==="1")continue;const h=c.getAttribute("fileId");if(!h)continue;a++;const w=this._fileIdToSaveAs.get(h)||h;if(!await N.has(z,`media/file/${w}`))continue;const p=await this.probeVideoDuration(`${window.location.origin}${B}/media/file/${w}`);p>0&&r.set(h,p)}if(r.size===0)continue;const l=r.size>=a,{duration:d}=Pe(i,r);d>0&&this.core.recordLayoutDuration(String(e),d,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=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.6.11",i="2026-03-12T14:06:56.706Z".replace("T"," ").replace(/\.\d+Z$/,""),n=i?`v${t} (${i})`:`v${t}`;e.textContent=`${n} | CMS: ${D.cmsUrl} | Display: ${D.displayName||"Unknown"} | HW: ${D.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=Te(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=De(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,t;if(this._screenshotInFlight){u.debug("Screenshot capture already in progress, skipping");return}this._screenshotInFlight=!0;try{let i;if(this._screenshotMethod==="electron"||this._screenshotMethod===null&&((e=window.electronAPI)!=null&&e.captureScreenshot)){const o=await window.electronAPI.captureScreenshot();if(o)this._screenshotMethod="electron",i=o;else{u.debug("Electron screenshot not ready yet, will retry next interval");return}}else if(this._screenshotMethod==="displayMedia"||this._screenshotMethod===null&&typeof((t=navigator.mediaDevices)==null?void 0:t.getDisplayMedia)=="function")try{i=await this.captureDisplayMedia(),this._screenshotMethod="displayMedia"}catch(o){u.warn("getDisplayMedia failed, falling back to html2canvas:",o.message||o),this._screenshotMethod=null,i=await this.captureHtml2CanvasIsolated(),this._screenshotMethod="html2canvas"}else this._screenshotMethod="html2canvas",i=await this.captureHtml2CanvasIsolated();await this.xmds.submitScreenShot(i)?u.info(`Screenshot submitted (${this._screenshotMethod})`):u.warn("Screenshot submission failed")}catch(i){u.error("Failed to capture screenshot:",i)}finally{this._screenshotInFlight=!1}}async captureDisplayMedia(){const e=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});try{const t=e.getVideoTracks()[0],n=await new window.ImageCapture(t).grabFrame(),o=document.createElement("canvas");return o.width=n.width,o.height=n.height,o.getContext("2d").drawImage(n,0,0),n.close(),o.toDataURL("image/jpeg",.8).split(",")[1]}finally{e.getTracks().forEach(t=>t.stop())}}async captureHtml2CanvasIsolated(){var o,s;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];this._html2canvasMod||(this._html2canvasMod=(await F(async()=>{const{default:r}=await import("./html2canvas.esm-CBrSDip1.js");return{default:r}},[],import.meta.url)).default),this.renderer&&(this.renderer._resizeSuppressed=!0);const n=i.style.contain||"";i.style.contain="strict";try{const r=i.getBoundingClientRect(),a=getComputedStyle(i),l=a.backgroundColor;l&&l!=="transparent"&&l!=="rgba(0, 0, 0, 0)"&&(t.fillStyle=l,t.fillRect(r.left,r.top,r.width,r.height));const d=a.backgroundImage;if(d&&d!=="none"){const h=d.match(/url\(["']?(.*?)["']?\)/);if(h)try{const w=new Image;w.crossOrigin="anonymous",await new Promise(m=>{w.onload=()=>m(),w.onerror=()=>m(),setTimeout(()=>m(),2e3),w.src=h[1]}),w.naturalWidth&&t.drawImage(w,r.left,r.top,r.width,r.height)}catch{}}const c=i.querySelectorAll("img, video, iframe, canvas");let g=0;for(const h of c){const w=h;if(w.style.visibility==="hidden"||w.style.display==="none")continue;const m=h.getBoundingClientRect();if(!(m.width===0||m.height===0))try{if(h instanceof HTMLImageElement){if(!h.complete||!h.naturalWidth)continue;if(getComputedStyle(h).objectFit==="contain"&&h.naturalWidth&&h.naturalHeight){const b=this.containedRect(h.naturalWidth,h.naturalHeight,m);t.drawImage(h,b.x,b.y,b.w,b.h)}else t.drawImage(h,m.left,m.top,m.width,m.height);g++}else if(h instanceof HTMLVideoElement){if(h.readyState<2)continue;if(getComputedStyle(h).objectFit==="contain"&&h.videoWidth&&h.videoHeight){const b=this.containedRect(h.videoWidth,h.videoHeight,m);t.drawImage(h,b.x,b.y,b.w,b.h)}else t.drawImage(h,m.left,m.top,m.width,m.height);g++}else if(h instanceof HTMLCanvasElement)t.drawImage(h,m.left,m.top,m.width,m.height),g++;else if(h instanceof HTMLIFrameElement){const p=h.contentDocument;if(!(p!=null&&p.body))continue;const b=document.createElement("div");b.style.cssText=`position:fixed;left:-9999px;top:0;width:${m.width}px;height:${m.height}px;overflow:hidden;`;const _=[];for(const v of p.querySelectorAll("style"))b.appendChild(v.cloneNode(!0));for(const v of p.querySelectorAll('link[rel="stylesheet"]')){const S=document.createElement("link");S.rel="stylesheet",S.href=new URL(v.getAttribute("href")||"",p.baseURI).href,b.appendChild(S),_.push(new Promise(O=>{S.onload=()=>O(),S.onerror=()=>O()}))}const C=p.body.cloneNode(!0);for(const v of C.querySelectorAll("img[src]")){const S=v.getAttribute("src")||"";S&&!S.startsWith("http")&&!S.startsWith("data:")&&!S.startsWith("blob:")&&v.setAttribute("src",new URL(S,p.baseURI).href)}b.appendChild(C),document.body.appendChild(b);const R=p.querySelectorAll("img"),x=new Map;R.forEach((v,S)=>{v.naturalWidth&&v.naturalHeight&&x.set(String(S),{nw:v.naturalWidth,nh:v.naturalHeight})}),_.length>0&&await Promise.race([Promise.all(_),new Promise(v=>setTimeout(v,500))]);const T=await this._html2canvasMod(b,{useCORS:!0,allowTaint:!0,logging:!1,backgroundColor:null,width:m.width,height:m.height,onclone:v=>{const S=v.createElement("style");S.textContent="*, *::before, *::after { animation: none !important; transition: none !important; opacity: 1 !important; }",v.head.appendChild(S),v.querySelectorAll("img").forEach((I,E)=>{var de,ue;const A=(de=v.defaultView)==null?void 0:de.getComputedStyle(I);if(!A||A.objectFit!=="contain")return;const k=x.get(String(E));if(!k)return;const M=I.clientWidth||parseFloat(A.width)||0,P=I.clientHeight||parseFloat(A.height)||0;if(!M||!P)return;const ee=k.nw/k.nh,se=M/P;let te,J;ee>se?(te=M,J=M/ee):(J=P,te=P*ee);const re=v.createElement("div");re.style.cssText=`width:${M}px;height:${P}px;display:flex;align-items:center;justify-content:center;overflow:hidden;`,I.style.objectFit="fill",I.style.width=`${te}px`,I.style.height=`${J}px`,(ue=I.parentNode)==null||ue.insertBefore(re,I),re.appendChild(I)})}});document.body.removeChild(b),t.drawImage(T,m.left,m.top,m.width,m.height);const $=h.getBoundingClientRect();for(const v of p.querySelectorAll("video")){if(v.readyState<2)continue;const S=v.getBoundingClientRect();if(!(S.width===0||S.height===0))try{if(((s=(o=p.defaultView)==null?void 0:o.getComputedStyle(v))==null?void 0:s.objectFit)==="contain"&&v.videoWidth&&v.videoHeight){const I=this.containedRect(v.videoWidth,v.videoHeight,new DOMRect($.left+S.left,$.top+S.top,S.width,S.height));t.drawImage(v,I.x,I.y,I.w,I.h)}else t.drawImage(v,$.left+S.left,$.top+S.top,S.width,S.height)}catch{}}for(const v of p.querySelectorAll("canvas")){const S=v.getBoundingClientRect();if(!(S.width===0||S.height===0))try{t.drawImage(v,$.left+S.left,$.top+S.top,S.width,S.height)}catch{}}g++}}catch(p){u.warn("Screenshot: failed to draw element",h.tagName,p)}}return u.debug(`Screenshot: composed ${g}/${c.length} elements`),e.toDataURL("image/jpeg",.8).split(",")[1]}finally{i.style.contain=n,this.renderer&&(this.renderer._resizeSuppressed=!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&&!window.electronAPI&&F(()=>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(){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),G==null||G.clear(),this._probeTimer&&(clearTimeout(this._probeTimer),this._probeTimer=null),this._mediaStatusTimer&&(clearTimeout(this._mediaStatusTimer),this._mediaStatusTimer=null)}}function Ee(){const y=new ft;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",Ee):Ee();export{lt as D,bt as I,ie as L,rt as O,dt as P,at as R,st as S,St as a,ot as b,et as c,Pe as p,vt as s};
|
|
736
|
-
//# sourceMappingURL=main-
|
|
735
|
+
`,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 a=this.iframe.contentDocument;if(!a)return;a.addEventListener("keydown",l=>{l.key==="Escape"&&(l.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()===Be.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=U("PWA"),z=B.slice(1),le=new URL("./",window.location.href).pathname.replace(/\/$/,"");let $e,X,D,_e,Le,Ce,Ie,N,G,xe,Te,ke,De,Ae,Me;const j={};class ft{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,"_html2canvasMod",null);L(this,"_screenshotInFlight",!1);L(this,"_wakeLock",null);L(this,"syncManager",null);L(this,"_currentLayoutEnableStat",!0);L(this,"_probeTimer",null);L(this,"_mediaStatusTimer",null);L(this,"_pendingFollowerStats",null);L(this,"_pendingFollowerLogs",null);L(this,"_iframeObserver",null);L(this,"_swIcHandler",null);L(this,"_chunkConfig",null);L(this,"_fileIdToSaveAs",new Map);L(this,"protocolDetector",null)}async init(){if(u.info("Initializing player with RendererLite + PlayerCore..."),await this.loadCoreModules(),"serviceWorker"in navigator)try{const s=await navigator.serviceWorker.register(`${le}/sw-pwa.js?v=${Date.now()}`,{scope:`${le}/`,type:"module",updateViaCache:"none"});u.info("Service Worker registered for offline mode:",s.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(s){u.warn("Service Worker registration failed:",s)}u.info("Initializing cache clients..."),N=new je;const{calculateChunkConfig:e}=await F(async()=>{const{calculateChunkConfig:s}=await import("./index-BpwloMHc.js");return{calculateChunkConfig:s}},__vite__mapDeps([0,1,2]),import.meta.url);this._chunkConfig=e(u),G=new ze({concurrency:this._chunkConfig.concurrency,chunkSize:this._chunkConfig.chunkSize,chunksPerFile:2}),u.info("Cache clients ready — StoreClient + DownloadManager");const t=document.getElementById("player-container");if(!t)throw new Error("No #player-container found");this.renderer=new at({cmsUrl:D.cmsUrl,hardwareKey:D.hardwareKey},t,{fileIdToSaveAs:this._fileIdToSaveAs,getWidgetHtml:async s=>{const r=`${B}/widgets/${s.layoutId}/${s.regionId}/${s.id}`;u.debug(`Looking for widget HTML at: ${r}`,s);try{if(await N.has(`${z}/widgets`,`${s.layoutId}/${s.regionId}/${s.id}`))return u.debug("Widget HTML found in store, using mirror URL for iframe"),{url:r,fallback:s.raw||""};u.warn(`No widget HTML found in store: ${r}`)}catch(a){u.error(`Failed to check widget HTML for ${s.id}:`,a)}return u.warn(`Using widget.raw fallback for ${s.id}`),s.raw||""}}),this.core=new dt({config:D,xmds:this.xmds,cache:N,schedule:X,renderer:this.renderer,xmrWrapper:Ie,statsCollector:this.statsCollector,displaySettings:this.displaySettings,cmsId:D.activeCmsId}),this.setupCoreEventHandlers(),this.setupRendererEventHandlers(),this.setupInteractiveControl(),this.setupDataConnectorNotify(),this.setupRemoteControls(),this.core.on("register-complete",s=>{var l,d;const r=parseFloat((l=s==null?void 0:s.settings)==null?void 0:l.latitude),a=parseFloat((d=s==null?void 0:s.settings)==null?void 0:d.longitude);r&&a&&!isNaN(r)&&!isNaN(a)?(u.info(`Display location from CMS: ${r.toFixed(4)}, ${a.toFixed(4)}`),X!=null&&X.setLocation&&X.setLocation(r,a)):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(s=>{u.error("Failed to collect after coming online:",s)})}),window.addEventListener("offline",()=>{u.warn("Browser reports offline — continuing playback with cached data"),this.updateStatus("Offline mode — using cached content"),this.showOfflineIndicator()});const n=(this.getControls().keyboard||{}).debugOverlays===!0,o=ut();o.enabled&&n&&(this.downloadOverlay=new ve(o),this.downloadOverlay.setProgressCallback(()=>G.getProgress()),u.info("Download overlay enabled (hover bottom-right corner)")),ht()&&n&&(this.timelineOverlay=new be(!0,s=>this.skipToLayout(s))),this.setupCertWarnings(),this.setupXmrWarning(),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)}}setupCertWarnings(){const e=new Set;window.addEventListener("cert-warning",t=>{const{host:i,error:n}=t.detail;if(e.has(i))return;e.add(i),u.warn(`Invalid SSL certificate accepted for stream: ${i} (${n})`);let o=document.getElementById("overlay"),s=!1;if(!o){o=document.createElement("div"),o.id="overlay";const l=document.createElement("div");l.id="config-info",o.appendChild(l);const d=document.createElement("div");d.id="status",o.appendChild(d),document.body.appendChild(o),s=!0}let r=document.getElementById("cert-warnings");if(!r){r=document.createElement("span"),r.id="cert-warnings",r.style.cssText="color: #ffaa33; flex: 0 0 auto;";const l=document.getElementById("status");o.insertBefore(r,l)}const a=[...e].join(", ");r.textContent=`⚠ SSL: ${a}`,s&&this.updateConfigDisplay()})}setupXmrWarning(){this.core.on("xmr-status",({connected:e})=>{const t=document.getElementById("overlay");if(!t)return;let i=document.getElementById("xmr-warning");if(e)i==null||i.remove();else{if(!i){i=document.createElement("span"),i.id="xmr-warning",i.style.cssText="color: #ff6666; flex: 0 0 auto;";const n=document.getElementById("cert-warnings")||document.getElementById("status");t.insertBefore(i,n)}i.textContent="⚠ XMR disconnected"}})}async loadCoreModules(){var e,t,i;try{const[n,o,s,r,a,l,d,c,g,h]=await Promise.all([F(()=>import("./index-dBd5BTjH.js"),__vite__mapDeps([3,4,2]),import.meta.url),F(()=>import("./index-GPOkOOlx.js"),__vite__mapDeps([5,6,2]),import.meta.url),F(()=>import("./index-D39gYDMZ.js"),__vite__mapDeps([7,8,2,4]),import.meta.url),F(()=>import("./index-B57dvLVB.js"),[],import.meta.url),F(()=>import("./index-B2dyKYhW.js"),__vite__mapDeps([9,2]),import.meta.url),F(()=>import("./index-D9_3Ns4E.js"),__vite__mapDeps([10,2]),import.meta.url),F(()=>import("./index-B_ADwXGQ.js"),__vite__mapDeps([11,2]),import.meta.url),F(()=>import("./index-CLgKYdBJ.js"),__vite__mapDeps([12,2,8,4]),import.meta.url),F(()=>import("./index-ClTQ0ldA.js"),__vite__mapDeps([13,8,2,4]),import.meta.url),F(()=>import("./sync-manager-C0UDCBzv.js"),__vite__mapDeps([14,2]),import.meta.url)]);if($e=n.cacheWidgetHtml,Me=h.SyncManager,X=s.scheduleManager,D=r.config,_e=o.RestClient,Le=o.XmdsClient,Ce=o.ProtocolDetector,Ie=a.XmrWrapper,xe=l.StatsCollector,Te=l.formatStats,ke=l.LogReporter,De=l.formatLogs,Ae=d.DisplaySettings,j.core=c.VERSION||"?",j.cache=n.VERSION||"?",j.renderer=g.VERSION||"?",j.schedule=s.VERSION||"?",j.xmds=o.VERSION||"?",j.xmr=a.VERSION||"?",j.utils=r.VERSION||"?",j.stats=l.VERSION||"?",j.settings=d.VERSION||"?",(e=window.electronAPI)!=null&&e.getSystemInfo)try{const R=await window.electronAPI.getSystemInfo();R.macAddress&&(D.macAddress=R.macAddress)}catch{}const w=D.transport!=="auto"?D.transport:void 0,p=new URLSearchParams(window.location.search).get("transport")||(le.includes("pwa-xmds")?"xmds":null)||w||"auto";this.protocolDetector=new Ce(D.cmsUrl,_e,Le);const b=p==="auto"?void 0:p,{client:_}=await this.protocolDetector.detect(D,b);this.xmds=_;const C=D.activeCmsId;this.statsCollector=new xe(C),await this.statsCollector.init(),u.info(`Stats collector initialized${C?` (CMS: ${C})`:""}`),this.logReporter=new ke(C),await this.logReporter.init(),u.info(`Log reporter initialized${C?` (CMS: ${C})`:""}`),he(({level:R,name:A,args:k})=>{if(!this.logReporter)return;const M=k.map(P=>typeof P=="string"?P:JSON.stringify(P)).join(" ");this.logReporter.log(R,`[${A}] ${M}`,"PLAYER").catch(()=>{})});const O=D.debug;if(O!=null&&O.consoleLogs){const R=(O.consoleLogsInterval||10)*1e3;let A=[],k=null;const M=()=>{if(A.length===0)return;const P=A;A=[],k=null,fetch("/debug/log",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)}).catch(()=>{})};he(({level:P,name:ee,args:se})=>{const te=se.map(J=>typeof J=="string"?J:JSON.stringify(J)).join(" ");A.push({level:P,name:ee,message:te,ts:new Date().toISOString()}),k||(k=setTimeout(M,R))}),u.info(`Console log forwarding to proxy enabled (flush every ${R/1e3}s)`)}this.displaySettings=new Ae,u.info("Display settings manager initialized");const x="2026-03-13T18:17:31.331Z",T="0.6.13";u.info(`v${T} built ${x}`);const $=Object.entries(j).map(([R,A])=>`${R}=${A}`).join(" ");u.info(`SDK: ${$}`);const v=!!window.electronAPI,S=v?((t=navigator.userAgent.match(/Electron\/([\d.]+)/))==null?void 0:t[1])||"?":null,E=((i=navigator.userAgent.match(/Chrome\/([\d.]+)/))==null?void 0:i[1])||"?",I=v?`Electron ${S} / Chrome ${E}`:`Chrome ${E}`;u.info(`Env: PWA v${T} | ${I} | ${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||D.hardwareKey;this.updateStatus(`Registered: ${t}`),this.displaySettings&&(document.title=`Xibo Player - ${this.displaySettings.getDisplayName()}`)}),this.core.on("sync-config",e=>{if(this.syncManager&&this.syncManager.stop(),e.syncPublisherPort&&e.syncGroup!=="lead"){const t=e.isLead?"localhost":e.syncGroup;e.relayUrl=`ws://${t}:${e.syncPublisherPort}/sync`}this.syncManager=new Me({displayId:D.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 N.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,i;(t=this.downloadOverlay)==null||t.startUpdating();try{const n=((i=this.xmds)==null?void 0:i._token)||null;n&&await fetch("/auth-token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:n})}),await this.enqueueDownloads(e),u.info("Download enqueue complete")}catch(n){u.error("Download request failed:",n),this.updateStatus("Download failed: "+n,"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("layout-expire-current",()=>{u.info("Schedule changed — expiring current layout"),this.renderer.stopCurrentLayout()}),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.core.on("collection-error",async 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}`)}),this.core.on("log-level-changed",()=>{u.info("Log level changed")}),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 N.list();if(e.length>0){const i=await N.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.core.on("execute-native-command",async e=>{var i;let t;if((i=window.electronAPI)!=null&&i.executeShellCommand)t=await window.electronAPI.executeShellCommand({commandString:e.commandString});else try{t=await(await fetch("/shell-command",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commandString:e.commandString})})).json()}catch(n){t={success:!1,reason:n.message}}this.core.emit("command-result",{code:e.code,...t})}),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("navigate-to-widget",e=>{e.targetId?this.renderer.navigateToWidget(e.targetId):u.warn("navigate-to-widget action has no targetId:",e)}),this.core.on("timeline-updated",e=>{var n;const t=this.core.getCurrentLayoutId(),i=t?this.core.getLayoutDuration(t):void 0;(n=this.timelineOverlay)==null||n.update(e,t,i)})}setupInteractiveControl(){var e;this._swIcHandler=t=>{var l,d;if(((l=t.data)==null?void 0:l.type)!=="INTERACTIVE_CONTROL")return;const{method:i,path:n,search:o,body:s}=t.data,r=(d=t.ports)==null?void 0:d[0];if(!r)return;const a=this.handleInteractiveControl(i,n,o,s);r.postMessage(a)},(e=navigator.serviceWorker)==null||e.addEventListener("message",this._swIcHandler)}setupDataConnectorNotify(){this.core.getDataConnectorManager().on("data-changed",t=>{var o;const i=document.querySelectorAll("iframe"),n={ctrl:"rtNotifyData",data:{dataKey:t}};for(const s of i)try{(o=s.contentWindow)==null||o.postMessage(n,"*")}catch{}})}setupRemoteControls(){window.addEventListener("blur",()=>{setTimeout(()=>window.focus(),200)});const e=a=>{const l=()=>{var d;try{const c=a.contentDocument||((d=a.contentWindow)==null?void 0:d.document);if(!c||a.__keyForwarderAttached)return;a.__keyForwarderAttached=!0,c.addEventListener("keydown",g=>{const h=new KeyboardEvent("keydown",{key:g.key,code:g.code,keyCode:g.keyCode,ctrlKey:g.ctrlKey,shiftKey:g.shiftKey,altKey:g.altKey,metaKey:g.metaKey,bubbles:!0,cancelable:!0});document.dispatchEvent(h)||g.preventDefault()})}catch{}};a.addEventListener("load",l),l()};Array.from(document.querySelectorAll("iframe")).forEach(a=>e(a)),this._iframeObserver=new MutationObserver(a=>{for(const l of a)for(const d of l.addedNodes)d instanceof HTMLIFrameElement&&e(d),d instanceof HTMLElement&&d.querySelectorAll("iframe").forEach(c=>e(c))}),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",a=>{if(a.key==="q"&&(a.ctrlKey||a.metaKey)){a.preventDefault(),u.info("[Remote] Quit requested (Ctrl+Q)"),fetch("/quit",{method:"POST"}).catch(()=>{});return}switch(a.key){case"t":case"T":if(!n)break;this.timelineOverlay||(this.timelineOverlay=new be(!0,l=>this.skipToLayout(l))),this.timelineOverlay.toggle();break;case"d":case"D":if(!n)break;this.downloadOverlay||(this.downloadOverlay=new ve({enabled:!0,autoHide:!1}),this.downloadOverlay.setProgressCallback(()=>G.getProgress())),this.downloadOverlay.toggle();break;case"v":case"V":{if(!r)break;const l=[...document.querySelectorAll("video")];document.querySelectorAll("iframe").forEach(c=>{try{l.push(...c.contentDocument.querySelectorAll("video"))}catch{}});const d=l.length>0&&!l[0].controls;l.forEach(c=>c.controls=d);break}case"ArrowRight":case"PageDown":if(!s)break;u.info("[Remote] Next layout (keyboard)"),this.core.advanceToNextLayout(),a.preventDefault();break;case"ArrowLeft":case"PageUp":if(!s)break;u.info("[Remote] Previous layout (keyboard)"),this.core.advanceToPreviousLayout(),a.preventDefault();break;case" ":if(!s)break;u.info("[Remote] Toggle pause (keyboard)"),this.renderer.isPaused()?this.renderer.resume():this.renderer.pause(),a.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 gt),this.setupOverlay.toggle(),a.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(){return D.controls}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:D.hardwareKey,displayName:D.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 l=this.core.getDataConnectorManager().getData(r);return l===null?{status:404,body:JSON.stringify({error:`No data available for key: ${r}`})}:{status:200,body:typeof l=="string"?l:JSON.stringify(l)}}case"/criteria":return{status:200,body:JSON.stringify({displayId:D.displayId,hardwareKey:D.hardwareKey,displayName:D.displayName,width:window.innerWidth,height:window.innerHeight,latitude:D.latitude||null,longitude:D.longitude||null,playerType:"pwa"})};default:return{status:404,body:JSON.stringify({error:"Unknown IC route"})}}}notifyFileCached(e,t){if(u.debug(`Download complete: ${t}/${e}`),t==="layout")this.core.notifyMediaReady(parseInt(e),t);else if(t==="media"){const i=this._fileIdToSaveAs.get(e)||e;this.core.notifyMediaReady(i,t)}this._probeTimer&&clearTimeout(this._probeTimer),this._probeTimer=setTimeout(()=>{this._probeTimer=null,this.probeLayoutDurations().catch(()=>{})},3e3),this._mediaStatusTimer&&clearTimeout(this._mediaStatusTimer),this._mediaStatusTimer=setTimeout(()=>{this._mediaStatusTimer=null,this.checkTimelineMediaStatus().catch(()=>{})},2e3)}async enqueueDownloads(e){const{extractMediaIdsFromXlf:t}=await F(async()=>{const{extractMediaIdsFromXlf:$}=await import("./index-BpwloMHc.js");return{extractMediaIdsFromXlf:$}},__vite__mapDeps([0,1,2]),import.meta.url),{layoutOrder:i,files:n,layoutDependants:o}=e,s=G.queue,r=$=>($.path||"").split("?")[0].replace(/^\/+/,"")||`${$.type||"media"}/${$.id}`;for(const $ of n)$.saveAs&&this._fileIdToSaveAs.set(String($.id),$.saveAs);const a=new Map,l=[],d=new Map,c=new Map;for(const $ of n)if($.type==="layout")a.set(parseInt($.id),$);else if($.type==="static")l.push($);else{const v=`${$.type}:${$.id}`;d.set(v,$);const S=String($.id);c.has(S)||c.set(S,[]),c.get(S).push(v)}u.info(`Download: ${i.length} layouts, ${d.size} media, ${l.length} resources`);const g=new Map,w=[...i,...[...a.keys()].filter($=>!i.includes($))].map(async $=>{const v=a.get($);if(!(v!=null&&v.path))return;let S;try{const E={};v.cmsDownloadUrl&&(E["X-Cms-Download-Url"]=v.cmsDownloadUrl);const I=await fetch(v.path,Object.keys(E).length?{headers:E}:void 0);I.ok&&(S=await I.text(),u.info(`Fetched XLF ${$} (${S.length} bytes)`),this.notifyFileCached(String($),"layout"))}catch{}S&&g.set($,t(S,u))});await Promise.allSettled(w),u.info(`Parsed ${g.size} XLFs`);const m=async($,v)=>{if(!v.path||v.path==="null"||v.path==="undefined")return!1;const S=r(v);try{if((await fetch(`/store/${S}`,{method:"HEAD"})).ok)return!1}catch{}if(G.getTask(S))return!1;try{const I=await fetch(`/store/missing-chunks/${S}`);if(I.ok){const{missing:R,numChunks:A}=await I.json();if(A>0&&R.length<A){const k=new Set;for(let M=0;M<A;M++)R.includes(M)||k.add(M);v.skipChunks=k,u.info(`Resuming ${S}: ${k.size}/${A} chunks cached, ${R.length} to download`)}}}catch{}const E=$.addFile(v);return E.state!=="pending"?!1:(E.wait().then(I=>{const R=parseInt(v.size)||I.size;u.info("Download complete:",S,`(${R} bytes)`),R>this._chunkConfig.chunkSize&&fetch("/store/mark-complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storeKey:S})}).catch(A=>u.warn("mark-complete failed:",S,A.message)),this.notifyFileCached(String(v.id),v.type),s.removeCompleted(S)}).catch(I=>{u.error("Download failed:",v.id,I),s.removeCompleted(r(v))}),!0)},p=new ae(s);for(const $ of l)await m(p,$);const b=await p.build();b.length>0&&(b.push(ge),s.enqueueOrderedTasks(b));const _=new Set,C=[...g.keys()].filter($=>!i.includes($)),O=new Map;for(const[$,v]of d)v.saveAs&&O.set(v.saveAs,$);const x=new Map;if(o)for(const[$,v]of Object.entries(o))x.set(parseInt($,10),v);for(const $ of i){const v=g.get($);if(!v)continue;const S=new Set(v);for(const k of C){const M=g.get(k);if(M)for(const P of M)S.add(P)}const E=x.get($)||[];for(const k of E){const M=O.get(k);M&&S.add(M)}const I=[];for(const k of S){if(d.has(k)&&!_.has(k)){I.push(d.get(k)),_.add(k);continue}const M=c.get(String(k))||[];for(const P of M)_.has(P)||(I.push(d.get(P)),_.add(P))}if(I.length===0)continue;u.info(`Layout ${$}: ${I.length} media`),I.sort((k,M)=>(k.size||0)-(M.size||0));const R=new ae(s);for(const k of I)await m(R,k);const A=await R.build();A.length>0&&(A.push(ge),s.enqueueOrderedTasks(A))}const T=[...d.keys()].filter($=>!_.has($));if(T.length>0){u.info(`${T.length} media not in any XLF`);const $=new ae(s);for(const S of T){const E=d.get(S);E&&await m($,E)}const v=await $.build();v.length>0&&s.enqueueOrderedTasks(v)}u.info("Downloads active:",s.running,", queued:",s.queue.length)}setupRendererEventHandlers(){this.renderer.on("layoutStart",(e,t)=>{var n;u.info("Layout started:",e),this.updateStatus(`Playing layout ${e}`),this.core.setCurrentLayout(e),this._currentLayoutEnableStat=(t==null?void 0:t.enableStat)!==!1;const i=this.core.getLayoutDuration(e)||(t==null?void 0:t.duration);(n=this.timelineOverlay)==null||n.update(null,e,i),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.startLayout(e,this.currentScheduleId).catch(o=>{u.error("Failed to start layout stat:",o)})}),this.renderer.on("layoutEnd",e=>{if(u.info("Layout ended:",e),X==null||X.recordPlay(e.toString()),this.statsCollector&&this._currentLayoutEnableStat&&this.statsCollector.endLayout(e,this.currentScheduleId).catch(i=>{u.error("Failed to end layout stat:",i)}),this.renderer.currentLayoutId&&this.renderer.currentLayoutId!==e){u.debug(`Layout ${e} ended but ${this.renderer.currentLayoutId} already playing, skipping advance`);return}if(this.preparingLayoutId&&this.preparingLayoutId!==e){u.debug(`Layout ${e} ended but ${this.preparingLayoutId} being prepared, skipping advance`);return}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("widgetCommand",e=>{u.info("Widget command:",e.commandCode);const t={[e.commandCode]:{commandString:e.commandString}};this.core.executeCommand(e.commandCode,t)}),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,a;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((a=e.source)==null?void 0:a.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,i)=>{this.core.recordLayoutDuration(String(e),t,i)}),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 N.get(`${z}/layouts`,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)}}),this.renderer.on("videoError",async({storedAs:e})=>{if(!e)return;const t=`${B.slice(1)}/media/file/${e}`;try{const i=await fetch(`/store/missing-chunks/${t}`),{missing:n}=await i.json();if(n.length===0){u.warn(`Video error for ${e} but no missing chunks — possible decode error`);return}u.warn(`Video ${e}: ${n.length} missing chunks (${n.join(", ")}), re-downloading`),await fetch("/store/unmark-complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storeKey:t})}),this.core.collectNow().catch(o=>{u.error(`Failed to trigger re-download for ${e}:`,o.message)})}catch(i){u.error(`Failed to check/re-download ${e}:`,i.message)}})}async prepareAndRenderLayout(e){var t;if(this.core.getCurrentLayoutId()===e){u.debug(`Layout ${e} already playing, skipping duplicate prepare`),this.core._preparingLayoutId=null;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 N.get(`${z}/layouts`,e);if(!i){u.info("Layout not in cache yet, marking as pending:",e),this.core.setPendingLayout(e,[String(e)]),this.updateStatus(`Downloading layout ${e}...`);return}const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(!await this.checkAllMediaCached(o)){G.prioritizeLayoutFiles(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}this.renderer.hasPreloadedLayout(e)||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,this.core._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(a=>{const l=a.getAttribute("fileId");if(l){const d=this._fileIdToSaveAs.get(l)||l;if(d.endsWith(".xlf"))return;n.push(d),a.getAttribute("type")==="video"&&o.push(d)}});const s=(r=i.querySelector("layout"))==null?void 0:r.getAttribute("background");if(s){const a=this._fileIdToSaveAs.get(s)||s;n.includes(a)||n.push(a)}return{allMedia:n,videoMedia:o}}async checkAllMediaCached(e){for(const t of e)try{if(!await N.has(z,`media/file/${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 a of s.querySelectorAll("media")){const l=a.getAttribute("type"),d=a.getAttribute("id");a.getAttribute("render")==="html"&&o.push((async()=>{try{const g=`${t}/${r}/${d}`;let h=null;const w=await N.get(`${z}/widgets`,g);w&&(h=await w.text(),u.debug(`Found cached widget HTML for ${l} ${d}`)),h||(h=await this.xmds.getResource(t,r,d),u.debug(`Retrieved widget HTML for ${l} ${d} from CMS`)),await $e(t,r,d,h);const m=await N.get(`${z}/widgets`,g);m&&(h=await m.text());const p=a.querySelector("raw");if(p)p.textContent=h;else{const b=n.createElement("raw");b.textContent=h,a.appendChild(b)}}catch(g){u.warn(`Failed to get widget HTML for ${l} ${d}:`,g)}})())}}o.length>0&&(u.info(`Fetching ${o.length} widget HTML resources in parallel...`),await Promise.all(o),u.debug("All widget HTML fetched"))}async checkTimelineMediaStatus(){if(this.scheduledLayoutIds.size!==0){for(const e of this.scheduledLayoutIds){const t=`${e}.xlf`;try{const i=await N.get(`${z}/layouts`,e);if(!i)continue;const n=await i.text(),{allMedia:o}=this.getMediaIds(n);if(o.length===0){this.core.setLayoutMediaStatus(t,!0);continue}const s=[];for(const r of o)try{await N.has(z,`media/file/${r}`)||s.push(r)}catch{}this.core.setLayoutMediaStatus(t,s.length===0,s)}catch{}}this.core.logUpcomingTimeline()}}async probeLayoutDurations(){if(this.scheduledLayoutIds.size!==0)for(const e of this.scheduledLayoutIds)try{const t=await N.get(`${z}/layouts`,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;let a=0;for(const c of s.querySelectorAll('media[type="video"]')){if(c.getAttribute("useDuration")==="1")continue;const h=c.getAttribute("fileId");if(!h)continue;a++;const w=this._fileIdToSaveAs.get(h)||h;if(!await N.has(z,`media/file/${w}`))continue;const p=await this.probeVideoDuration(`${window.location.origin}${B}/media/file/${w}`);p>0&&r.set(h,p)}if(r.size===0)continue;const l=r.size>=a,{duration:d}=Pe(i,r);d>0&&this.core.recordLayoutDuration(String(e),d,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=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.6.13",i="2026-03-13T18:17:31.331Z".replace("T"," ").replace(/\.\d+Z$/,""),n=i?`v${t} (${i})`:`v${t}`;e.textContent=`${n} | CMS: ${D.cmsUrl} | Display: ${D.displayName||"Unknown"} | HW: ${D.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=Te(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=De(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,t;if(this._screenshotInFlight){u.debug("Screenshot capture already in progress, skipping");return}this._screenshotInFlight=!0;try{let i;if(this._screenshotMethod==="electron"||this._screenshotMethod===null&&((e=window.electronAPI)!=null&&e.captureScreenshot)){const o=await window.electronAPI.captureScreenshot();if(o)this._screenshotMethod="electron",i=o;else{u.debug("Electron screenshot not ready yet, will retry next interval");return}}else if(this._screenshotMethod==="displayMedia"||this._screenshotMethod===null&&typeof((t=navigator.mediaDevices)==null?void 0:t.getDisplayMedia)=="function")try{i=await this.captureDisplayMedia(),this._screenshotMethod="displayMedia"}catch(o){u.warn("getDisplayMedia failed, falling back to html2canvas:",o.message||o),this._screenshotMethod=null,i=await this.captureHtml2CanvasIsolated(),this._screenshotMethod="html2canvas"}else this._screenshotMethod="html2canvas",i=await this.captureHtml2CanvasIsolated();await this.xmds.submitScreenShot(i)?u.info(`Screenshot submitted (${this._screenshotMethod})`):u.warn("Screenshot submission failed")}catch(i){u.error("Failed to capture screenshot:",i)}finally{this._screenshotInFlight=!1}}async captureDisplayMedia(){const e=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});try{const t=e.getVideoTracks()[0],n=await new window.ImageCapture(t).grabFrame(),o=document.createElement("canvas");return o.width=n.width,o.height=n.height,o.getContext("2d").drawImage(n,0,0),n.close(),o.toDataURL("image/jpeg",.8).split(",")[1]}finally{e.getTracks().forEach(t=>t.stop())}}async captureHtml2CanvasIsolated(){var o,s;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];this._html2canvasMod||(this._html2canvasMod=(await F(async()=>{const{default:r}=await import("./html2canvas.esm-CBrSDip1.js");return{default:r}},[],import.meta.url)).default),this.renderer&&(this.renderer._resizeSuppressed=!0);const n=i.style.contain||"";i.style.contain="strict";try{const r=i.getBoundingClientRect(),a=getComputedStyle(i),l=a.backgroundColor;l&&l!=="transparent"&&l!=="rgba(0, 0, 0, 0)"&&(t.fillStyle=l,t.fillRect(r.left,r.top,r.width,r.height));const d=a.backgroundImage;if(d&&d!=="none"){const h=d.match(/url\(["']?(.*?)["']?\)/);if(h)try{const w=new Image;w.crossOrigin="anonymous",await new Promise(m=>{w.onload=()=>m(),w.onerror=()=>m(),setTimeout(()=>m(),2e3),w.src=h[1]}),w.naturalWidth&&t.drawImage(w,r.left,r.top,r.width,r.height)}catch{}}const c=i.querySelectorAll("img, video, iframe, canvas");let g=0;for(const h of c){const w=h;if(w.style.visibility==="hidden"||w.style.display==="none")continue;const m=h.getBoundingClientRect();if(!(m.width===0||m.height===0))try{if(h instanceof HTMLImageElement){if(!h.complete||!h.naturalWidth)continue;if(getComputedStyle(h).objectFit==="contain"&&h.naturalWidth&&h.naturalHeight){const b=this.containedRect(h.naturalWidth,h.naturalHeight,m);t.drawImage(h,b.x,b.y,b.w,b.h)}else t.drawImage(h,m.left,m.top,m.width,m.height);g++}else if(h instanceof HTMLVideoElement){if(h.readyState<2)continue;if(getComputedStyle(h).objectFit==="contain"&&h.videoWidth&&h.videoHeight){const b=this.containedRect(h.videoWidth,h.videoHeight,m);t.drawImage(h,b.x,b.y,b.w,b.h)}else t.drawImage(h,m.left,m.top,m.width,m.height);g++}else if(h instanceof HTMLCanvasElement)t.drawImage(h,m.left,m.top,m.width,m.height),g++;else if(h instanceof HTMLIFrameElement){const p=h.contentDocument;if(!(p!=null&&p.body))continue;const b=document.createElement("div");b.style.cssText=`position:fixed;left:-9999px;top:0;width:${m.width}px;height:${m.height}px;overflow:hidden;`;const _=[];for(const v of p.querySelectorAll("style"))b.appendChild(v.cloneNode(!0));for(const v of p.querySelectorAll('link[rel="stylesheet"]')){const S=document.createElement("link");S.rel="stylesheet",S.href=new URL(v.getAttribute("href")||"",p.baseURI).href,b.appendChild(S),_.push(new Promise(E=>{S.onload=()=>E(),S.onerror=()=>E()}))}const C=p.body.cloneNode(!0);for(const v of C.querySelectorAll("img[src]")){const S=v.getAttribute("src")||"";S&&!S.startsWith("http")&&!S.startsWith("data:")&&!S.startsWith("blob:")&&v.setAttribute("src",new URL(S,p.baseURI).href)}b.appendChild(C),document.body.appendChild(b);const O=p.querySelectorAll("img"),x=new Map;O.forEach((v,S)=>{v.naturalWidth&&v.naturalHeight&&x.set(String(S),{nw:v.naturalWidth,nh:v.naturalHeight})}),_.length>0&&await Promise.race([Promise.all(_),new Promise(v=>setTimeout(v,500))]);const T=await this._html2canvasMod(b,{useCORS:!0,allowTaint:!0,logging:!1,backgroundColor:null,width:m.width,height:m.height,onclone:v=>{const S=v.createElement("style");S.textContent="*, *::before, *::after { animation: none !important; transition: none !important; opacity: 1 !important; }",v.head.appendChild(S),v.querySelectorAll("img").forEach((I,R)=>{var de,ue;const A=(de=v.defaultView)==null?void 0:de.getComputedStyle(I);if(!A||A.objectFit!=="contain")return;const k=x.get(String(R));if(!k)return;const M=I.clientWidth||parseFloat(A.width)||0,P=I.clientHeight||parseFloat(A.height)||0;if(!M||!P)return;const ee=k.nw/k.nh,se=M/P;let te,J;ee>se?(te=M,J=M/ee):(J=P,te=P*ee);const re=v.createElement("div");re.style.cssText=`width:${M}px;height:${P}px;display:flex;align-items:center;justify-content:center;overflow:hidden;`,I.style.objectFit="fill",I.style.width=`${te}px`,I.style.height=`${J}px`,(ue=I.parentNode)==null||ue.insertBefore(re,I),re.appendChild(I)})}});document.body.removeChild(b),t.drawImage(T,m.left,m.top,m.width,m.height);const $=h.getBoundingClientRect();for(const v of p.querySelectorAll("video")){if(v.readyState<2)continue;const S=v.getBoundingClientRect();if(!(S.width===0||S.height===0))try{if(((s=(o=p.defaultView)==null?void 0:o.getComputedStyle(v))==null?void 0:s.objectFit)==="contain"&&v.videoWidth&&v.videoHeight){const I=this.containedRect(v.videoWidth,v.videoHeight,new DOMRect($.left+S.left,$.top+S.top,S.width,S.height));t.drawImage(v,I.x,I.y,I.w,I.h)}else t.drawImage(v,$.left+S.left,$.top+S.top,S.width,S.height)}catch{}}for(const v of p.querySelectorAll("canvas")){const S=v.getBoundingClientRect();if(!(S.width===0||S.height===0))try{t.drawImage(v,$.left+S.left,$.top+S.top,S.width,S.height)}catch{}}g++}}catch(p){u.warn("Screenshot: failed to draw element",h.tagName,p)}}return u.debug(`Screenshot: composed ${g}/${c.length} elements`),e.toDataURL("image/jpeg",.8).split(",")[1]}finally{i.style.contain=n,this.renderer&&(this.renderer._resizeSuppressed=!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&&!window.electronAPI&&F(()=>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(){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),G==null||G.clear(),this._probeTimer&&(clearTimeout(this._probeTimer),this._probeTimer=null),this._mediaStatusTimer&&(clearTimeout(this._mediaStatusTimer),this._mediaStatusTimer=null)}}function Ee(){const y=new ft;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",Ee):Ee();export{lt as D,bt as I,ie as L,rt as O,dt as P,at as R,st as S,St as a,ot as b,et as c,Pe as p,vt as s};
|
|
736
|
+
//# sourceMappingURL=main-GlNtH9kX.js.map
|